C#给PDF文件添加水印
本文实例为大家分享了C#添加PDF文件水印的具体代码,供大家参考,具体内容如下
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingiTextSharp.text.html.simpleparser;
usingiTextSharp.text.pdf;
usingiTextSharp.text;
usingSystem.IO;
usingSystem.Web.UI.HtmlControls;
usingSystem.Drawing;
//itextsharp.dllversion:5.1.10
protectedvoidButton1_Click(objectsender,EventArgse)
{
stringsource=@"D:\My.Sample\C#NET\Exoport2PDF\Web2\Chap1011.pdf";//模板路径
stringoutput=@"D:\My.Sample\C#NET\Exoport2PDF\Web2\Chap1012.pdf";//导出水印背景后的PDF
stringwatermark=@"D:\My.Sample\C#NET\Exoport2PDF\Web2\gp0.jpg";//水印图片
boolisSurrcess=PDFWatermark(source,output,watermark,10,10);
}
publicboolPDFWatermark(stringinputfilepath,stringoutputfilepath,stringModelPicName,floattop,floatleft)
{
//thrownewNotImplementedException();
PdfReaderpdfReader=null;
PdfStamperpdfStamper=null;
try
{
pdfReader=newPdfReader(inputfilepath);
intnumberOfPages=pdfReader.NumberOfPages;
iTextSharp.text.Rectanglepsize=pdfReader.GetPageSize(1);
floatwidth=psize.Width;
floatheight=psize.Height;
pdfStamper=newPdfStamper(pdfReader,newFileStream(outputfilepath,FileMode.Create));
PdfContentBytewaterMarkContent;
iTextSharp.text.Imageimage=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(inti=1;i<=numberOfPages;i++)
{
waterMarkContent=pdfStamper.GetUnderContent(i);
waterMarkContent.AddImage(image);
}
//strMsg="success";
returntrue;
}
catch(Exceptionex)
{
ex.Message.Trim();
returnfalse;
}
finally
{
if(pdfStamper!=null)
pdfStamper.Close();
if(pdfReader!=null)
pdfReader.Close();
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
