Why do I get a StackOverflowException in the OnEndPage() event handler?

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.

If you want to add content in the OnEndPage() method, you need the writer, for instance writer.DirectContent.



Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now