Why does it not work when I override the OnEndPage event to add a paragraph to the document?

In the code below, you can see that I've overridden the OnEndPage event and tried to add a paragraph to the document. However, I get a System.StackOverflowException error when attempting to run the code. Does anyone have any idea why this is happening and how I can fix it?

public override void OnEndPage(PdfWriter writer, Document document)
{
    base.OnEndPage(writer, document);
    Paragraph p = new Paragraph("Paragraph");
    document.Add(p);
}

Posted on StackOverflow on Jun 18, 2014 by Ognjen Koprivica

It is forbidden to use document.Add() in a page event. The document object passed as a parameter is actually a PdfDocument object. It is not the Document you have created in your code, but an internal object that is used by iText. You should use it for read-only purposes only.

In iText 7 we implement the IEventHandler interface and add it to the PdfDocument like this:

pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, new MyEventHandler());

If you want to add content you need a PdfCanvas instance inside MyEventHandler implementation. It can be done like this:

protected class MyEventHandler implements IEventHandler {
    protected Document doc;
    public MyEventHandler(Document doc) {
        this.doc = doc;
    }
    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfCanvas canvas = new PdfCanvas(docEvent.getPage());
        Rectangle pageSize = docEvent.getPage().getPageSize();
        canvas.beginText();
        canvas.setFontAndSize(PdfFontFactory.createFont(FontConstants.HELVETICA_OBLIQUE), 5);
        canvas.moveText((pageSize.getRight() - doc.getRightMargin() - (pageSize.getLeft() + doc.getLeftMargin())) / 2 + doc.getLeftMargin(), pageSize.getTop() - doc.getTopMargin() + 10)
                .showText("Paragraph")
                .endText()
                .release();
    }
}

Take a look at the examples from this package to learn more.

Click Why do I get a StackOverflowException in the OnEndPage() event handler? if you want to see how to answer this question in iText 5.