Skip to main content
Skip table of contents

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

How do I divide my header and footer into three sections?

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

Headers and footers should be added using 'page events'. Just create a class that extends PdfPageEventHelper and implement the onEndPage() method. People who read the documentation do not make the common mistake to use the onStartPage() method, but maybe you overlooked this, so I'm adding this as an extra caveat.

Add an instance of your class to the PdfWriter object with the setPageEvent() method.

I don't know if I understand what you mean by "multiple" headers. If you have more than one page event implementation, you can add them all using the setPageEvent() method and they will all be executed. If you want to switch from one page event implementation to another, you need to use setPageEvent(null) first.

Maybe you want the header to be different for different pages, just use a member-variable in your page event implementation and change it along the way. In one of the book examples named MovieHistory2, the text for the header is stored in a String array named header.

The position of the header depends on the page number:

public void onEndPage(PdfWriter writer, Document document) {
    Rectangle rect = writer.getBoxSize("art");
    switch(writer.getPageNumber() % 2) {
    case 0:
            Element.ALIGN_RIGHT, header[0],
            rect.getRight(), rect.getTop(), 0);
    case 1:
            Element.ALIGN_LEFT, header[1],
            rect.getLeft(), rect.getTop(), 0);
        Element.ALIGN_CENTER, new Phrase(String.format("page %d", pagenumber)),
        (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);

For even page numbers, the header is added to the right; for odd page numbers to the left. The footer is centered as you can see.

You also mention a header table. If you want to use a table, please take a look at the MovieCountries1 example.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.