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 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"
:
Java
C#
1
2
3
| 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:
Java
C#
1
2
3
| PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE,
new PaginationEventHandler(srcDoc.getFirstPage().copyAsFormXObject(pdfDoc))); |
PaginationEventHandler
is looking like this:
Java
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| 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
:
Java
C#
1
2
3
4
5
6
7
8
9
10
11
| 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(StandardFonts.HELVETICA_BOLD)));
for (int i = 1; i < 101; i++) {
doc.add(new Paragraph("Hello " + i));
doc.add(p);
} |
Note that there are no PdfImportedPage
and ColumnText
classes in iText 7, hence this sample differs from iText 5 a lot.
Click this link if you want to see how to answer this question in iText 5.