Abady
Abady

Reputation: 111

How to add a watermark to a PDF file?

I'm using C# and iTextSharp to add a watermark to my PDF files:

Document document = new Document();
PdfReader pdfReader = new PdfReader(strFileLocation);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(strFileLocationOut, FileMode.Create, FileAccess.Write, FileShare.None));
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
img.SetAbsolutePosition(100, 300);
PdfContentByte waterMark;
//    
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
{
    waterMark = pdfStamper.GetOverContent(pageIndex);
    waterMark.AddImage(img);
}
//
pdfStamper.FormFlattening = true;
pdfStamper.Close();

It works fine, but my problem is that in some PDF files no watermark is added although the file size increased, any idea?

Upvotes: 10

Views: 21974

Answers (2)

Bruno Lowagie
Bruno Lowagie

Reputation: 77528

The fact that the file size increases is a good indication that the watermark is added. The main problem is that you're adding the watermark outside the visible area of the page. See How to position text relative to page using iText?

You need something like this:

Rectangle pagesize = reader.GetCropBox(pageIndex);
if (pagesize == null)
    pagesize = reader.GetMediaBox(pageIndex);
img.SetAbsolutePosition(
    pagesize.GetLeft(),
    pagesize.GetBottom());

That is: if you want to add the image in the lower-left corner of the page. You can add an offset, but make sure the offset in the x direction doesn't exceed the width of the page, and the offset in the y direction doesn't exceed the height of the page.

Upvotes: 8

plinth
plinth

Reputation: 49179

Although I don't know the specifics of iTextSharp, likely on the pages where your image is not showing, the previous PDF content has modified the current transformation matrix such that whatever you put on the page is moved off the page.

This can be fixed by emitting a gsave operator before the original page content and emitting a grestore operator after the original page content (but before yours). This, however may not fix all cases with a PDF document that modifies the CTM does a gsave and no grestore. This is not supposed to happen in theory, according to the PDF specification:

Occurrences of the q and Q operators shall be balanced within a given content stream (or within the sequence of streams specified in a page dictionary’s Contents array).

but I can tell you from experience that this is not the case in practice.

Upvotes: 0

Related Questions