How to add image background to pdf for every page?

2019-01-15 17:47发布

问题:

I'm trying to set a background to a pdf and managed to set it with an image my pdf has a big table so the pages are added automatically not with the Document.NewPage() method so the image background is set only on the first page. This is the code that adds the background:

    Image backImg = Image.GetInstance(@"D:\websites\DIS\bugs\130208\A4.png");
    backImg.SetAbsolutePosition(0, 0);
    backImg.Alignment = Image.UNDERLYING;

    var doc = new Document(pageSize);
    PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
    doc.Open();

    doc.Add(backImg);
    ...
    creating a big table

and not using the doc.NewPage() method. Do I have to loop throw every page and add the background image at the end before closing the doc, but how do I put it in the background not on top of the other elements?

回答1:

Whenever you want to apply something to every page, you should use page events, more specifically PdfPageEvent.onEndPage(), to do it. You can find samples for its usage by keyword Page events > onEndPage --- these samples are taken from iText in Action 2nd Edition. The samples mainly add footers and headers while you want to add background graphics.

Be aware that you shouldn't add content to the Document instance here but instead directly to the PdfWriter, and as you want the image to be under the page content , not above it, you will need to use PdfWriter.getDirectContentUnder() like in the sample Stationery and not PdfWriter.getDirectContent() like in the other samples.

PS: The analogous samples for .Net can be found here.

PPS: The sample ImageDirect.java / ImageDirect.cs shows how to add an image to some direct content which might be the information missing here.



回答2:

go for

PdfPageEvent.onStartPage()

. In this event, write your code to insert the image (as you are doing it). What it will do is that as soon as a new page is created, it will add the image to it and then the content over it; giving a watermark effect.



标签: c# itextsharp