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 implement the IEventHandler interface (if you are using iText 7) and add your code to the handleEvent() method.

public class RectangleEventHandler implements IEventHandler {
    public RectangleEventHandler() {}
    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        PdfCanvas canvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), pdfDoc);
        canvas.setFillColor(new DeviceCmyk(1, 0, 0, 0))
                .rectangle(new Rectangle(20, 10, 10, 820))
                .fillStroke();
    }
}

Create an instance of your custom event class, and declare it to the PdfDocument pdfDoc:

RectangleEventHandler handler = new RectangleEventHandler();
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, handler);

Now your rectangle will be drawn on every page, on the top of any content you’ve added.

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


Share this article

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