How to add a rectangle to every page of a document?

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:

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. 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().



Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now