How to set a fixed background image for all my pages?

Category: 
Tags: page eventsbackgroundimagesiText 7

On Button Click, I generate 4 pages on my PDF, I added this image to provide a background image:

string imageFilePath = parent + "/Images/bg_image.jpg";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
jpg.ScaleToFit(1700, 1000);
jpg.Alignment = iTextSharp.text.Image.UNDERLYING;
jpg.SetAbsolutePosition(0, 0);
document.Add(jpg);
It works only with 1 page, but when I generate a PDF that contains many records and have several pages, the bg image is only at the last page. I want to apply the background image to all of the pages.

Posted on StackOverflow on Nov 1, 2014 by dandy

It is normal that the background is added only once, because you're adding it only once.

If you want to add content to every page, you should not do that manually because you don't know when a new page will be created by iText. Instead you should use an event handler.

In iText 7 the idea is to create an implementation of the IEventHandler interface and override the handleEvent() method:

public class BackgroundEventHandler implements IEventHandler {
    protected Image img;
 
    public BackgroundEventHandler(Image img) {
        this.img = img;
    }
    @Override
    public void handleEvent(Event event) {
 
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        PdfCanvas canvas = new PdfCanvas(page.newContentStreamBefore(),
                page.getResources(), pdfDoc);
        Rectangle area = page.getPageSize();
        new Canvas(canvas, pdfDoc, area)
                .add(img);
    }
}

From that moment on, your background image will be added directly to the content each time a page is finalized. We use the PdfCanvas wrapping and newContentStreamBefore() method to get the content stream under the page content.

Now you should create an instance of this custom event and set it on the PdfDocumentEvent.END_PAGE event:

BackgroundEventHandler handler = new BackgroundEventHandler(img);
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, handler);

Image object is defined like this:

Image img = new Image(ImageDataFactory.create(imgSrc))
            .scaleToFit(1700, 1000)
            .setFixedPosition(0, 0);

Note that 1700 and 1000 seems quite big. Are you sure those are the dimensions of your page?

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