PDF加水印
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
/// <summary>
/// PDF加水印
/// </summary>
/// <param name="inputfilepath">源PDF文件</param>
/// <param name="outputfilepath">加水印后PDF文件 </param>
/// <param name="ModelPicName">水印文件路径</param>
/// <param name="top">离顶部距离</param>
/// <param name="left">离左边距离,如果为负,则为离右边距离</param>
/// <param name="strMsg">返回信息</param>
/// <returns>返回</returns>
public static bool PDFWatermark(string inputfilepath, string outputfilepath, string ModelPicName, float top, float left, ref string strMsg)
{
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
try
{
pdfReader = new PdfReader(inputfilepath);
int numberOfPages = pdfReader.NumberOfPages;
iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
PdfContentByte waterMarkContent;
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ModelPicName);
image.GrayFill = 20;//透明度,灰色填充
//image.Rotation//旋转
//image.RotationDegrees//旋转角度
//水印的位置
if (left < 0)
{
left = width - image.Width + left;
}
image.SetAbsolutePosition(left, (height - image.Height) - top);
//每一页加水印,也可以设置某一页加水印
for (int i = 1; i <= numberOfPages; i++)
{
waterMarkContent = pdfStamper.GetUnderContent(i);
waterMarkContent.AddImage(image);
}
strMsg = "success";
return true;
}
catch (Exception ex)
{
strMsg = ex.Message.Trim();
return false;
}
finally
{
if (pdfStamper != null)
pdfStamper.Close();
if (pdfReader != null)
pdfReader.Close();
}
}