Watermark, generally divided into text watermark and picture watermark, is a document anti-counterfeiting, declaring the rights of the important protection means. It's common to add watermarks to word and how to do it in PDF. The following describes how to implement a PDF document to add a watermark.
using Tools: Free spire.pdf for. NET
Note: You must download and install the component first, and add the reference spire.pdf for. NET to the namespace
One, add text watermark
The main code is as follows:
//创建一个新的PDF实例,导入PDF文件 PdfDocument pdf= new PdfDocument();pdf.LoadFromFile("sample.pdf");//获取PDF文件的第一页PdfPageBase page = pdf.Pages[0];//添加文本水印到文件的第一页,设置文本格式PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3)); brush.Graphics.SetTransparency(0.3f); brush.Graphics.Save(); brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2); brush.Graphics.RotateTransform(-45); brush.Graphics.DrawString("Draft Version", new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Blue,0, 0, new PdfStringFormat(PdfTextAlignment.Center)); brush.Graphics.Restore(); brush.Graphics.SetTransparency(1); page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));//保存文件为PDF格式,命名为"TextWaterMark.pdf"pdf.SaveToFile("TextWaterMark.pdf");
Examples of effects:
Second, add image watermark
The main code is as follows:
//创建一个新的PDF实例,导入PDF文件 PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("sample.pdf");//获取PDF文件的第一页 PdfPageBase page = pdf.Pages[0];//导入图片并把它设置为PDF文件的背景Image img = Image.FromFile("img.jpg"); page.BackgroundImage = img;//保存文件为PDF格式,命名为"ImageWaterMark.pdf"pdf.SaveToFile("ImageWaterMark.pdf");
Examples of effects:
How to add a PDF watermark to C #