How to add text at an absolute position on the top of the first page?
How can I add text automatically to the 1st page, instead of the last?
I have a script that creates a PDF file and writes contents to it. After the execution is complete I need to write the status (fail, success) to the PDF, but the status should be on the top of the page. So the solution I came up with is to use absolute positioned text like this:
PdfContentByte cb = writer.DirectContent;
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SaveState();
cb.BeginText();
cb.MoveText(700, 30);
cb.SetFontAndSize(bf, 12);
cb.ShowText("My status");
cb.EndText();
cb.RestoreState();
But as the PDF creates multiple pages, this text is added to the last page of the PDF. How can I add it to the 1st page?
Posted on StackOverflow on Nov 9, 2015 by BiJ
iText was designed to flush content from memory as soon as possible: if a page is finished, that page is sent to the OutputStream
and there is no way to return to that page.
That doesn't mean your requirement is impossible. PDF has a concept known as Form XObject
. In iText 7, this concept is implemented under the PdfFormXObject
class. Such a PdfFormXObject
is a rectangular area with a fixed size that can be added to a page without being part of that page.
Please take a look at the WriteOnFirstPage example. We create a template and wrap it inside an Image object. By doing this, we can add the PdfFormXObject
to the document just like any other object:
PdfFormXObject template = new PdfFormXObject(new Rectangle(523, 50));
PdfCanvas templateCanvas = new PdfCanvas(template, pdfDoc);
doc.add(new Image(template));
Now we can add as much data as we want:
for (int i = 0; i < 100; i++) {
doc.add(new Paragraph("test"));
}
Adding 100 "test" lines will cause iText 7 to create 4 pages. Once we're on page 4, we no longer have access to page 1, but we can still write content to the template object created before:
templateCanvas
.beginText()
.setFontAndSize(PdfFontFactory.createFont(FontConstants.HELVETICA), 12)
.showText(String.format("There are %s pages in this document", pdfDoc.getNumberOfPages()))
.endText()
.stroke();
If you check the resulting PDF write_on_first_page.pdf, you'll notice that the text we've added last is indeed on the first page.
Click How to add text at an absolute position on the top of the first page? if you want to see how to answer this question in iText 5.