0

I am trying to add background color to page. I am having A4 page size with 1/3 inch margin on top, left, right of page. bottom margin is 1 inch.

Rectangle a4 = PageSize.A4;
a4.setBackgroundColor(BaseColor.CYAN);
Document document = new Document(a4,24,24,24,72);

Background color get apply to all page. I want to apply it to page content excluding margin space.

Harshal
  • 193
  • 1
  • 2
  • 9

1 Answers1

1

You need to use a PdfPageEvent to achieve that. Take a look at the answer to this question: Change the color of pdf pages alternatively using iText pdf in java

In this example, we create a colored background that covers the full page:

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();
    }
}

Now let's adapt this example:

public class Background extends PdfPageEventHelper {
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte canvas = writer.getDirectContentUnder();
        Rectangle rect = document.getPageSize();
        canvas.setColorFill(BaseColor.BLUE);
        canvas.rectangle(rect.getLeft() + 36, rect.getBottom() + 36, rect.getWidth() - 72, rect.getHeight() - 72);
        canvas.fill();
    }
}

By changing the parameters of the rectangle() method, we introduced a margin of 36 user units on every side.

Obviously, you need to declare the page event to the PdfWriter:

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
Background event = new Background();
writer.setPageEvent(event);
Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165