Reputation: 139
Looking into many Java code examples within my organization, on the internet, as well as examples from iTextPdf, there is a common pattern of subtracting 1 from the returned number of pages, for instance: numberOfPages = writer.getPageNumber() - 1; // writer is of type PdfWriter It looks like iTextPdf considers a potentially next page, whether it exist or not. This does not make a lot of sense to me, but it works.
The context when this happens, is when using getPageNumber()
in the onCloseDocument()
method of a page event in order to get the total number of pages. In that case the returned value exceeds the number by one.
Upvotes: 1
Views: 2147
Reputation: 77528
This answer is for iText 5 only; iText 7 uses a completely different approach.
newPage()
method to finalize the last page in the document. The newPage()
method also initializes a new page, but as no content can be added after closing the document, that new page will be empty and it will never show up in your document (because empty pages are ignored). During the initialization of the new page that will never fully exist, the page count is incremented by one.onCloseDocument()
method is one of the last methods that is called. It is called after the newPage()
method was used, which also means: after the page number was incremented by one.So when you use the getPageNumber()
method in the onCloseDocument()
method, you need to subtract one page.
There is only one reason for this strange behavior: iText has grown organically, and the PDF creation process (the "5 steps") predates page events. We didn't think of adding page events when iText was initially designed. Page events were bolted on the original design, and that had some consequences, such as the "problem" you mention in your question.
As explained in our JavaOne talk "Oops, we broke our API", we have decided not to break the API for a long time, even when breaking the API would have led to more elegance and less quirks like the one you mentioned. With iText 7, we have decided to rewrite iText from scratch (breaking all backward compatibility) so that this sort of strange phenomena no longer exist.
Upvotes: 3