How to add HTML headers and footers to a page?

We want to add HTML headers and footers to a document. Currently, we have extended PdfPageEventHelper and overriden the onStartPage() and onEndPage() methods. This works fine for the first page, but it throws a RuntimeWorkerException when we get to 2+ pages.

 @Override
    void onStartPage(PdfWriter writer, Document document) {
        InputStream is = new ByteArrayInputStream(header?.getBytes());
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    }
Â
    @Override
    void onEndPage(PdfWriter writer, Document document) {
        InputStream is = new ByteArrayInputStream(footer?.getBytes());
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
Â
    }
Posted on StackOverflow on Oct 28, 2015 by froi

It is forbidden to add content in the onStartPage() event in general. It is forbidden to add content to the document object in the onEndPage(). You should add your header and your footer in the onEndPage() method using PdfWriter, NOT document. Also: you are wasting plenty of CPU by parsing the HTML over and over again.

Please take a look at the HtmlHeaderFooter example.

It has two snippets of HTML, one for the header, one for the footer.

public static final String HEADER =
    "
HeaderSome title
"";


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