Change the color of pdf pages alternatively using iText pdf in java

社会主义新天地 提交于 2019-11-28 13:02:49
Bruno Lowagie

This is a follow-up question of How can I add page background color of pdf using iText in java

While the advice given in the answer to that question works, it's not the best advice you could get. If I had seen your original question earlier, I would have answered it differently. I would have recommended you to use page events, as is done in the PageBackgrounds example.

In this example, I create a blue background for page 1 and 2, and a grey background for all the subsequent even pages. See page_backgrounds.pdf

How is this achieved? Well, using the same technique as used in my answer to this related question: How to draw border for whole pdf pages using iText library 5.5.2

I create a page event like this:

public class Background extends PdfPageEventHelper {
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        int pagenumber = writer.getPageNumber();
        if (pagenumber % 2 == 1 && pagenumber != 1)
            return;
        PdfContentByte canvas = writer.getDirectContentUnder();
        Rectangle rect = document.getPageSize();
        canvas.setColorFill(pagenumber < 3 ? BaseColor.BLUE : BaseColor.LIGHT_GRAY);
        canvas.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight());
        canvas.fill();
    }
}

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 content from the writer, and I get the dimension of the page from the document. I then set the fill color to either blue or light gray (depending on the page number), and I 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 Background event, we can use it like this:

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
Background event = new Background();
writer.setPageEvent(event);

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!