How to change the color of pages?

I'm creating report based on client activity. I'm creating this report with the help of the iText PDF library. I want to create the first two pages with a blue background color (for product name and disclaimer notes) and the remaining pages in white (without a background color). I colored two pages at the very beginning of report with blue using following code.

 

Rectangle pageSize = new Rectangle(PageSize.A4);
pageSize.setBackgroundColor(new BaseColor(84, 141, 212));
Document document = new Document( pageSize );
But when I move to 3rd page using document.newpage(), the page is still in blue. I can't change the color of 3rd page. I want to change the color of 3rd page onward to white. How can I do this using iText?

Posted on StackOverflow on May 13, 2015 by Arun jk

Please take a look at the PageBackgrounds example and page_backgrounds.pdf

To set different backgrounds I create a page event handler using iText 7:

protected class PageBackgroundsEventHandler implements IEventHandler {
    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfPage page = docEvent.getPage();

        int pagenumber = docEvent.getDocument().getNumberOfPages();
        if (pagenumber % 2 == 1 && pagenumber != 1) {
            return;
        }
        PdfCanvas canvas = new PdfCanvas(page);
        Rectangle rect = page.getPageSize();
        canvas
                .saveState()
                .setFillColor(pagenumber + 1 

As you can see, I first check for the page number. If it's an odd number and if it's not equal to 1, I don't do anything.

However, if I'm on page 1 or 2, or if the page number is even, I get the PdfCanvas from the current PdfPage and the dimension of this page. I then set the fill color to either blue or light gray (depending on the page number), and construct the path for a rectangle that covers the complete page. Finally, I fill that rectangle with the fill color.

Now that we've got our custom PageBackgroundsEventHandler, we can use it like this:

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, new PageBackgroundsEventHandler());

Feel free to adapt the PageBackgroundsEventHandler class if you need a different behavior.

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



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