Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...