Reputation: 6012
I am creating a pdf using itext like this :
Document document = new Document();
PdfWriter writer= PdfWriter.getInstance(document, new FileOutputStream(test+ "/"+filename));
Now, in the whole program, there are many places where I am creating a new page using document.newPage()
I am writing some text on the new pages using canvas.showText(Integer.toString(123));
Is it possible to go back to , say page 3 and add text to that page without reading the created pdf using PDFReader ?
i have tried document.setPageCount(3), but It doesnt seem to work(i am unsure if that is the method that I need).
Upvotes: 2
Views: 1492
Reputation: 77528
The answer to your question is yes and no.
No, it is not possible to go back to a previous page because iText was originally designed (by me) to be used in an internet context. As soon as a document.newPage()
is triggered, the byte stream with the content of the previous page is flushed to the OutputStream
. By designing it this way, I deliberately broke the design pattern used by slow MVC-based PDF libraries such as Apache FOP in order to create a really fast PDF library.
Yes, it is possible to introduce placeholders on pages. In iText terminology, we call them PdfTemplate
objects. In PDF jargon, they are called Form XObjects. The most common use case is the Page X of Y problem as demonstrated in the MovieCountries1 example. When you create a PDF on the fly, you don't know in advance how many pages the document will eventually have. You want to add page numbers such as page 1 of total
, page 2 of total
, and so on. But at the time those pages are flushed to the end user's browser, you don't know the value of total
. Instead of adding the value (that is unknown), you will add a PdfTemplate
object without any content. Only as soon as you know the value of total
, you will write the value to the PdfTemplate
. Internally, each page will have a reference from the page stream to that external object (that's why it's called an XObject).
So in answer to your question: if you want to add a value to page 3, but you don't know that value until you're on page 4, you need to add a PdfTemplate
to page 3, add the content to that PdfTemplate
when you're on page 4. Once you are sure that the value on the PdfTemplate
won't change anymore, you can release the PdfTemplate
. At the moment you release the PdfTemplate
, the content stream of the XObject will be written to the OutputStream
.
Upvotes: 6