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

Tags: headeralignmentiText 7

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 < 100; 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.