How to continue field output on a second page?

Tags: formsfill formflatten formcontinue on next pageiText 7

I have generated a PDF from a template. The PDF has a field in the middle of it that is of variable length. I am trying to work it so that if the field's content overflows, then the program will use a second instance template as a second page and continue in the same field there. Is this possible?

Posted on StackOverflow on Nov 10, 2014 by Carlos Mendieta

I've written a proof of concept, AddExtraPage, where I have a PDF form src that has a field named "body":

PdfDocument srcDoc = new PdfDocument(new PdfReader(src));
PdfAcroForm form = PdfAcroForm.getAcroForm(srcDoc, false);
Rectangle rect = form.getField("body").getWidgets().get(0).getRectangle().toRectangle();

First, we need to create a template of the first page which is going to be copied each time the content overflows:

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        new PaginationEventHandler(srcDoc.getFirstPage().copyAsFormXObject(pdfDoc)));

PaginationEventHandler is looking like this:

protected class PaginationEventHandler implements IEventHandler {
    protected PdfFormXObject background;
    public PaginationEventHandler(PdfFormXObject background) throws IOException {
        this.background = background;
    public void handleEvent(Event event) {
        PdfDocument pdfDoc = ((PdfDocumentEvent) event).getDocument();
        // Add the background
        new PdfCanvas(((PdfDocumentEvent) event).getPage().newContentStreamBefore(), ((PdfDocumentEvent) event).getPage().getResources(), pdfDoc)
                .addXObject(background, 0, 0);

Now we can add the content at the position defined by the field using ColumnDocumentRenderer:

Document doc = new Document(pdfDoc);
doc.setRenderer(new ColumnDocumentRenderer(doc, new Rectangle[]{rect}));
Paragraph p = new Paragraph();
p.add("Hello ");
p.add(new Text("World").setFont(PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD)));
for (int i = 1; i < 101; i++) {
    doc.add(new Paragraph("Hello " + i));

Note that there are no PdfImportedPage and ColumnText classes in iText 7, hence this sample differs from iText 5’s a lot.

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