Skip to main content
Skip table of contents

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

I want to apply the background image to all of the pages, but it is only showing up on the last page. Why is that?

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

It works only with 1 page, but when I generate a PDF that contains many records and has 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;
    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)

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 How to set a fixed background image for all my pages? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.