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

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 How to add a text to the left and to the right in a header? if you want to see how to answer this question in iText 5.

JavaScript errors detected

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

If this problem persists, please contact our support.