如何添加水印到PDF文件? [英] How to add a watermark to a PDF file?

查看:126
本文介绍了如何添加水印到PDF文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#和iTextSharp的添加水印到我的PDF文件:

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

它工作正常,但我的问题是,在某些PDF文件没有水印添加,虽然文件大小增加,任何想法?

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

推荐答案

事实上,文件大小增加是一个很好的迹象,水印添加。主要的问题是,您要添加的页面的可视区域之外的水印。见<一href=\"http://stackoverflow.com/questions/17439520/how-to-position-text-relative-to-page-using-itext/17442368#17442368\">How利用iText以相对文本位置页?

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?

您需要的是这样的:

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

即:如果要在页面的左下角添加的图片。可以添加的偏移,但要确保在x方向上的偏移量不超过页面的宽度,并在y方向上的偏移量不超过页的高度。

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.

这篇关于如何添加水印到PDF文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆