How to continue field output on a second page?

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

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)); pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, 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;
    }

    @Override
    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 

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.



Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now