Using iText7 (Java) to add a table to an existing PDF and continue on additional pages

佐手、 提交于 2019-12-12 02:44:07

问题


I am attempting to complete a project with almost identical requirements as those associated with this question asked in 2015.

The answer provided by Bruno was perfect, but related to iText5. I am relatively new to iText, and am desperately trying to get up-to-speed to complete a current project.

  • I need to populate the fields of a PDF document
  • I need to add a table below the populated section, and the table needs to span multiple pages thereafter

Can anyone assist with the translation of Bruno's answer from iText5 to iText7?

Thanks so much in advance for any/all assistance!


回答1:


You should write something like that:

    PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
    Document doc = new Document(pdfDoc);
    PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
    Map<String, PdfFormField> fields = form.getFormFields();
    fields.get("Name").setValue("Jeniffer");
    fields.get("Company").setValue("iText's next customer");
    fields.get("Country").setValue("No Man's Land");
    form.flattenFields();

    Table table = new Table(UnitValue.createPercentArray(new float[]{1, 15}));
    table.addHeaderCell("#");
    table.addHeaderCell("description");
    for (int i = 1; i <= 150; i++) {
        table.addCell(String.valueOf(i));
        table.addCell("test " + i);
    }

    doc.setRenderer(new DocumentRenderer(doc) {
        @Override
        protected LayoutArea updateCurrentArea(LayoutResult overflowResult) {
            LayoutArea area = super.updateCurrentArea(overflowResult);
            if (area.getPageNumber() == 1) {
                area.getBBox().decreaseHeight(266);
            }
            return area;
        }
    });

    doc.add(table);

    doc.close();

Probably the most interesting part is about extending DocumentRenderer. The instance of this class associated with document handles its layout and overrided method (updateCurrentArea), as the name stands for, updates area for layout.

What is important to mention: All iText5 SO answers are ported in iText7 and you can find them on iText's website: https://developers.itextpdf.com/content/itext-7-examples .



来源:https://stackoverflow.com/questions/44036916/using-itext7-java-to-add-a-table-to-an-existing-pdf-and-continue-on-additional

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!