How can I add an image to all pages of my PDF?

Category: 
Tags: page eventsimagesbackgroundiText 7

I have been trying to add an image to all pages using iTextSharp. The image needs to be OVER all content of every page. I have used the following code below all the otherdoc.add()

Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 30, 1);
PdfWriter writer = PdfWriter.GetInstance(doc,
    new FileStream(Server.MapPath("~/pdf/" + fname), FileMode.Create));
doc.Open();
Image image = Image.GetInstance(Server.MapPath("~/images/draft.png"));
image.SetAbsolutePosition(12, 300);
writer.DirectContent.AddImage(image, false);
doc.Close();
The above code only inserts an image in the last page. Is there any way to insert the image in the same way in all pages?

Posted on StackOverflow on Feb 20, 2014 by Neville Nazerane

It's normal that the image is only added once; after all: you're adding it only once.

In iText 7 you should implement IEventHandler interface:

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

Then set it on the PdfDocumentEvent.END_PAGE event:

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

So your code will look like this:

public void createPdf(String dest) throws IOException {
    Image img = new Image(ImageDataFactory.create(IMG)).setFixedPosition(12, 300);
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    ImageEventHandler handler = new ImageEventHandler(img);
    pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, handler);
    //add any content…
    pdfDoc.close();
}

This way the image will appear on every page at fixed position (12, 300). If you want an iText for C# example, you'll discover that it is very easy to port the Java to C#.

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