How to add text as a header or footer?

Tags: EventHandlerheaderfooteriText 7

I'm creating a pdf with iText 5 and want to add a footer. I did everything like the book "iText in action" says. There are no errors but the footer doesn't show up. Can somebody tell me what I'm doing wrong?

class MyFooter extends PdfPageEventHelper {
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer(),
            (document.right() - document.left()) / 2 + document.leftMargin(),
   + 10, 0);
    private Phrase footer() {
        Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);
        Phrase p = new Phrase("this is a footer");
        return p;
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
writer.setPageEvent(new MyFooter());

Posted on StackOverflow on January 5, 2015 by Hiasl

The problem you report can not be reproduced. I have taken your example and I create the TextFooter example for iText 7. You should implement IEventHandler like this:

protected class TextFooterEventHandler implements IEventHandler {
    protected Document doc;
    public TextFooterEventHandler(Document doc) {
        this.doc = doc;
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfCanvas canvas = new PdfCanvas(docEvent.getPage());
        Rectangle pageSize = docEvent.getPage().getPageSize();
        try {
            canvas.setFontAndSize(PdfFontFactory.createFont(FontConstants.HELVETICA_OBLIQUE), 5);
        } catch (IOException e) {
        canvas.moveText((pageSize.getRight() - doc.getRightMargin() - (pageSize.getLeft() + doc.getLeftMargin())) / 2 + doc.getLeftMargin(), pageSize.getTop() - doc.getTopMargin() + 10)
                .showText("this is a header")
                .moveText(0, (pageSize.getBottom() + doc.getBottomMargin()) - (pageSize.getTop() + doc.getTopMargin()) - 20)
                .showText("this is a footer")

There is no ColumnText class in iText 7 anymore, so we use PdfCanvas instead and add content to it. To get the desired positions on the top and bottom of the page we use a PageSize instance and the appropriate methods.

There was also an error in your footer() method, you didn’t apply a font to the Phrase. However in iText 7 such method will look like this (Phrases don’t exist anymore and fonts are defined in a different way):

private Paragraph footer() throws IOException {
    PdfFont ffont = PdfFontFactory.createFont(FontConstants.HELVETICA);
    Paragraph p = new Paragraph("this is a footer")
    return p;

Now when we look at the resulting PDF, we clearly see the text that was added as a header and a footer to each page.

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