How to add a text to the left and to the right in a header?

I need to add more than one header and footer to my document. In header I want title heading on left and some text in the center.

Likewise in footer I need to print my company name on the left side, the page number in the middle and some info regarding the contents in my table to the right.

Posted on StackOverflow on Feb 20, 2013 by Vignesh Vino

If you are using iText 7 you should write the implementation of the IEventHandler interface like this:

protected class HeadertFooterHandler implements IEventHandler {
    protected String info;
    public void setInfo(String info) { = info;
    public String getInfo() {
        return info;
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfPage page = docEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        PdfDocument pdfDoc = ((PdfDocumentEvent) event).getDocument();
        PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
        new Canvas(pdfCanvas, pdfDoc, pageSize)
            .showTextAligned("title heading", 70, pageSize.getTop() - 20, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 0)
            .showTextAligned("some text", pageSize.getWidth() / 2, pageSize.getTop() - 20, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 0)
            .showTextAligned(Integer.toString(pdfDoc.getPageNumber(page)), pageSize.getWidth() / 2, 30, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 0)
            .showTextAligned(info, pageSize.getWidth() - 60, 30, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 0);

And then just add a HeadertFooterHandler instance to your pdf.

HeadertFooterHandler handler = new HeadertFooterHandler();
pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, handler);
handler.setInfo("cool info");

You can add any sort of data to the document and don't forget to close it: Table table = new Table(2); for (int i = 0; i

This is how the result looks like:





According to your question strings are left-aligned/centered in header and centered/right-aligned in footer.

Click this link if you want to see how to answer this question in iText 5.

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

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