c给PDF所有页加上文字水印
给一个PDF的所有页加上文字水印,效果如下
新建一个项目,直接上代码了:usingiTextSharp。text;usingiTextSharp。text。pdf;usingSystem;usingSystem。IO;usingSystem。Windows。Forms;namespace111{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}privatevoidbutton1Click(objectsender,EventArgse){stringpApplication。StartupPath;stringrAddTextShuiYin(ptest。pdf,ptest1。pdf,0。5f,HELLO);MessageBox。Show(r);}publicstaticstringAddTextShuiYin(stringPdfPath,stringOutPdfPath,floattoumingdu,stringShuiYinText){if(File。Exists(OutPdfPath)){File。Delete(OutPdfPath);}PdfReaderreadernull;PdfStamperShuiYinOBJnull;PdfContentByteShuiYinQu;try{readernewPdfReader(PdfPath);得到原PDF的页数和宽高PDFATTattnewPDFATT(PdfPath);intnatt。PageCount();floatwatt。Width();floathatt。Height();从第0页开始inti0;ShuiYinOBJnewPdfStamper(reader,newFileStream(OutPdfPath,FileMode。Create));PdfGStategsnewPdfGState();设置透明度gs。FillOpacitytoumingdu;BaseFontfontBaseFont。CreateFont(C:WINDOWSFontsSIMFANG。TTF,BaseFont。IDENTITYH,BaseFont。EMBEDDED);while(in){i;在正文内容下加水印,不挡内容ShuiYinQuShuiYinOBJ。GetUnderContent(i);在正文内容上加水印,挡内容ShuiYinQuShuiYinOBJ。GetOverContent(i);ShuiYinQu。SetGState(gs);for(floatleft0;leftw;left200){for(floattop0;toph;top100){透明度gs。FillOpacitytoumingdu;ShuiYinQu。SetGState(gs);开始写入文本ShuiYinQu。BeginText();ShuiYinQu。SetColorFill(iTextSharp。text。Color。RED);ShuiYinQu。SetFontAndSize(font,180);ShuiYinQu。SetTextMatrix(2,2);ShuiYinQu。ShowTextAligned(Element。ALIGNCENTER,ShuiYinText,w2,h2,30);ShuiYinQu。AddImage(im);}}ShuiYinQu。EndText();}ShuiYinOBJ。Close();reader。Close();returnOK;}catch(Exceptionex){returnex。ToString();}}classPDFATT{PdfReaderreader;publicPDFATT(stringiPdfFilePath){readernewPdfReader(iPdfFilePath);}publicintPageCount(){returnreader。NumberOfPages;}publicfloatWidth(){returnreader。GetPageSize(1)。Width;}publicfloatHeight(){returnreader。GetPageSize(1)。Height;}}}}调用方法说明
stringpApplication。StartupPath;
参数:源文件地址,新文件地址,透明度(float型),水印文本
stringrAddTextShuiYin(ptest。pdf,ptest1。pdf,0。5f,HELLO);
MessageBox。Show(r);水印位置
这里我是w2和h2,大概在页中间,当然这里我为了演示没有精确计算,
30是旋转角度
ShuiYinQu。ShowTextAligned(Element。ALIGNCENTER,ShuiYinText,w2,h2,30);下次研究下加图片水印