itextPage events (iText 5) versus Event handlers and Renderers (iText 7)


Remarks

In iText 5, we introduced the concept of page events to allow developers to add specific behavior when a document is opened, when a new page is opened, when a page ends, and when a document is closed.

In the documentation, we made it very clear that it was forbidden to add content in the onStartPage() method; content can only be added in the onEndPage() method. We also made it very clear that the Document object passed to the page event methods was passed for read-only purposes only. It was forbidden to use document.add() even in the onEndPage() method.

Unfortunately, many developers completely ignore the documentation, which led to problems such as:

I can't remember how many times I got agitated because yet another developer posted a duplicate of these questions. People often wonder why they get a harsh answer, but they don't realize that a minimum of effort from their side would have saved everyone, including themselves, plenty of time. All of these questions could have been answered by saying "Read The (you-know-which) Manual."

Another option was a complete overhaul of iText so that these kind of problems can be avoided.

Due to the organic growth of iText, the page event class had also been extended with functionality that was unrelated to page events. It contained generic chunk functionality, it registered the start and the end of paragraphs, and so on.

What we fixed in iText 7:

We removed the page event functionality.

For all events with respect to pages, we now implement the IEventHandler interface, and we use the addEventHandler to add this handler as a PdfDocumentEvent to the PdfDocument. In the example, we use an END_PAGE event, but we could also have used a START_PAGE event. It doesn't matter any more whether you add content at the start or at the end. You can read more about this in Handling events; setting viewer preferences and writer properties which is chapter 7 in the iText 7: Building Blocks tutorial.

We improved the building blocks in the sense that we made them more hierarchical (see Before we start: Overview of the classes and interfaces which is the introduction of the iText 7: Building Blocks tutorial). We also introduced a set of Renderer classes, one for each building block, and we allow developers to adapt these renderers so that a building block shows a different behavior when rendered. See for instance the renderer example in Adding AbstractElement objects (part 1) which is chapter 7 in the iText 7: Building Blocks tutorial.

These changes simplify the functionality for developers who don't (want to) know much about PDF and iText, while at the same time offering an abundance of flexibility to those developers who aren't afraid to dig deep into the iText code to create a PDF exactly the way they want it.

Want to know more? Get the free ebook!