Skip to main content
Skip table of contents

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

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. 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 How to add a rectangle to every page of a document? if you want to see how to answer this question in iText 5.

JavaScript errors detected

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

If this problem persists, please contact our support.