Carla Urrea Stabile
Carla Urrea Stabile

Reputation: 869

How can I add Rectangle on every page of a document using iText?

I'm using iText 5.3.5 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 pretty sure of how to do this. I tried adding this at the end of my code (I found it on the internet):

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?

Hope I explained myself. Thanks in advance for your help. :)

Upvotes: 2

Views: 3163

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77528

Please take a look at the entries for the keyword Page events on the official iText site. 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().

Take a look at the Stationery example if you need some working source code. Please consult the official iText site in the future instead of saying you've found something "on the internet" without mentioning the source.

Upvotes: 2

Related Questions