How to add a table on a form (and maybe insert a new page)?

Tags: formsfill formflatten formcontinue on next pagetablesposition tablefield positioniText 7

I have two parts to my java project.

  • I need to populate the fields of a PDF
  • I need to add a table below the populated section on the blank area of the page (and this table needs to be able to roll over to the next page).

I am able to do these things separately (populate the PDF and create a table). But I cannot effectively merge them. I have tried doing doc.add(table) which will result in the table being on the next page of the PDF, which I don't want.

I essentially just need to be able to specify where the table starts on the page (so it wouldn't overlap the existing content) and then stamp the table onto the existing PDF.

Posted on StackOverflow on Feb 18, 2015 by Jennifer

Please take a look at the AddExtraTable example. It's a simplification of the AddExtraPage example written in answer to the question “How to continue field output on a second page?”

That question is almost an exact duplicate of your question, with as only difference the fact that your requirement is easier to achieve.

I simplified the code like this:

protected void manipulatePdf(String dest) throws Exception {
    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(new float[]{1, 15});
    table.setWidthPercent(80);
    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();
}

As you can see, in iText 7 we create a DocumentRenderer and specify the area for printing the content by overriding the updateCurrentArea() method. This way the table is able to roll over the next page.

Click this link if you want to see how to answer this question in iText 5.