研究PDF,刚刚完成了给pdf文件加图片水印的过程,贴出来分享一下

本函数能控制图片水印是从pdf页的左上角开始铺满整个页面还是只在页面正中心加一个水印图片:

using iTextSharp.text.pdf; using System; using System.IO; using System.Windows.Forms; namespace _111 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string p = Application.StartupPath + "\"; string r = AddPicShuiYin(p + "test.pdf", p + "test1.pdf", p + "sign.jpg", 0.5f, 100, 100, false); MessageBox.Show(r); } public static string AddPicShuiYin(string PdfPath, string OutPdfPath, string Shiyinpic,float toumingdu,int xjianju,int yjianju,bool OnlyOne) { if (File.Exists(OutPdfPath)) { File.Delete(OutPdfPath); } PdfReader reader = null; PdfStamper ShuiYinOBJ = null; PdfContentByte ShuiYinQu; try { reader = new PdfReader(PdfPath); //得到原PDF的页数和宽高 PDFATT att = new PDFATT(PdfPath); int n = att.PageCount(); float w = att.Width(); float h = att.Height(); //从第0页开始 int i = 0; ShuiYinOBJ = new PdfStamper(reader, new FileStream(OutPdfPath, FileMode.Create)); PdfGState gs = new PdfGState(); //设置透明度 gs.FillOpacity = toumingdu; //图片水平和垂直方向间距 iTextSharp.text.Image sypic = iTextSharp.text.Image.GetInstance(Shiyinpic); float imgWidth = (float)Math.Cos(Math.PI / 4) * sypic.Width + xjianju; float imgHeight = (float)Math.Sin(Math.PI / 4) * sypic.Width + yjianju; while (i < n) { i++; //在内容下加水印 ShuiYinQu = ShuiYinOBJ.GetUnderContent(i); //在内容上加水印 //ShuiYinQu = ShuiYinOBJ.GetOverContent(i); ShuiYinQu.SetGState(gs); if (OnlyOne) { //这里设置水印效果,有些效果我也不知道有啥用 iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(Shiyinpic); im.Rotation = 30;//旋转,这个就不起作用,不知道啥意思 //旋转角度 im.RotationDegrees = 45; im.SetAbsolutePosition(w / 2, h / 2); ShuiYinQu.AddImage(im); } else { for (float left = 0; left < w; left += imgWidth) { for (float top = 0; top < h; top += imgHeight) { //这里设置水印效果,有些效果我也不知道有啥用 iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(Shiyinpic); im.Rotation = 30;//旋转,这个就不起作用,不知道啥意思 //旋转角度 im.RotationDegrees = 45; im.SetAbsolutePosition(left, h - im.Height - top); ShuiYinQu.AddImage(im); } } } } ShuiYinOBJ.Close(); reader.Close(); return "OK"; } catch (Exception ex) { return ex.ToString(); } } class PDFATT { PdfReader reader; public PDFATT(string iPdfFilePath) { reader = new PdfReader(iPdfFilePath); } public int PageCount() { return reader.NumberOfPages; } public float Width() { return reader.GetPageSize(1).Width; } public float Height() { return reader.GetPageSize(1).Height; } } } }

用法就是:

string p = Application.StartupPath + "\";

//0.5f是透明度,

//100,100是当在页面上循环水印图片时各图片的水平和垂直间距

//false,是从左上角循环图片,还是只在正中心加一个水印图片

string r = AddPicShuiYin(p + "test.pdf", p + "test1.pdf", p + "sign.jpg", 0.5f, 100, 100, false);

运行结果

多个水印图片循环

只在中间有一个水印图片