Using iText7 (Java) to add a table to an existing

2019-09-14 19:04发布

问题:

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 .



标签: java pdf itext7