Adding table to existing PDF on the same page – ITEXT

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:

public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
    PdfReader reader = new PdfReader(src);
    Rectangle pagesize = reader.getPageSize(1);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    AcroFields form = stamper.getAcroFields();
    form.setField("Name", "Jennifer");
    form.setField("Company", "iText's next customer");
    form.setField("Country", "No Man's Land");
    PdfPTable table = new PdfPTable(2);
    table.addCell("#");
    table.addCell("description");
    table.setHeaderRows(1);
    table.setWidths(new int[]{ 1, 15 });
    for (int i = 1; i <= 150; i++) {
        table.addCell(String.valueOf(i));
        table.addCell("test " + i);
    }
    ColumnText column = new ColumnText(stamper.getOverContent(1));
    Rectangle rectPage1 = new Rectangle(36, 36, 559, 540);
    column.setSimpleColumn(rectPage1);
    column.addElement(table);
    int pagecount = 1;
    Rectangle rectPage2 = new Rectangle(36, 36, 559, 806);
    int status = column.go();
    while (ColumnText.hasMoreText(status)) {
        status = triggerNewPage(stamper, pagesize, column, rectPage2, ++pagecount);
    }
    stamper.setFormFlattening(true);
    stamper.close();
    reader.close();
}

public int triggerNewPage(PdfStamper stamper, Rectangle pagesize, ColumnText column, Rectangle rect, int pagecount) throws DocumentException {
    stamper.insertPage(pagecount, pagesize);
    PdfContentByte canvas = stamper.getOverContent(pagecount);
    column.setCanvas(canvas);
    column.setSimpleColumn(rect);
    return column.go();
}

As you can see, the main differences are:

  1. We create a rectPage1 for the first page and a rectPage2 for page 2 and all pages that follow. That’s because we don’t need a full page on the first page.
  2. We don’t need to load a PdfImportedPage, instead we’re just adding blank pages of the same size as the first page.

Possible improvements: I hardcoded the Rectangle instances. It goes without saying that rect1Page depends on the location of your original form. I also hardcoded rect2Page. If I had more time, I would calculate rect2Page based on the pagesize value.

See the following questions and answers of the official FAQ:

Leave a Comment