Skip to main content
Skip table of contents

How to add a rectangle to every page of a document? | iText 5 PDF Development Guide

Why does my code only add the rectangle on the last page?


I'm using iText to create a PDF document. Right now I am trying to get a rectangle on every single page of the document but I'm not sure how to do this. I tried adding this at the end of my code:


PdfContentByte cb = writer.getDirectContent();
for (int pgCnt = 1; pgCnt  writer.getPageNumber(); pgCnt++) {
    cb.saveState();
    cb.setColorStroke(new CMYKColor(1f, 0f, 0f, 0f));
    cb.setColorFill(new CMYKColor(1f, 0f, 0f, 0f));
    cb.rectangle(20,10,10,820);
    cb.fill();
    cb.restoreState();
}     

but this only adds the rectangle on the last page and it kind of make sense because I'm not using the pgCnt anywhere. How can I specify that I want the rectangle on page number pgCnt, so I can add the rectangle on every page?

Posted on StackOverflow on Mar 19, 2013 by Carla Stabille

Please take a look at the entries for the tag Page events - iText 5 Documentation. You'll discover that you need to extend the PdfPageEventHelper class and add your code to the onEndPage() method.

public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    cb.setColorStroke(new CMYKColor(1f, 0f, 0f, 0f));
    cb.setColorFill(new CMYKColor(1f, 0f, 0f, 0f));
    cb.rectangle(20,10,10,820);
    cb.fill();
    cb.restoreState();
}

Create an instance of your custom page event class, and declare it to the writer before opening the document:

writer.setPageEvent(myPageEventInstance);

Now your rectangle will be drawn on every page, on top of the existing content. If you want the rectangle under the existing content: replace getDirectContent() with getDirectContentUnder().

JavaScript errors detected

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

If this problem persists, please contact our support.