How to add PDF watermark in C#

Adding watermarks can be divided into adding text watermarks and adding image watermarks. This article will introduce how to add watermarks by using the free component Free Spire.PDF for .NET. This article is transferred from http://www.cnblogs.com/Yesi/p/4913603.html

1. Add image watermark

//Instantiate an instance of the PdfDocument class and load the PDF document
PdfDocument pdf = new PdfDocument();  
pdf.LoadFromFile("sample.pdf");

//Get the first page of the PDF
PdfPageBase page = pdf.Pages[0];
//Load the image and set it as a watermark
Image img = Image.FromFile("img.jpg");  
page.BackgroundImage = img;
//save to file
pdf.SaveToFile("ImageWaterMark.pdf");

Document after adding image watermark:



 

2. Add text watermark

//Create a PdfDocument class object and load the PDF document
PdfDocument pdf= new PdfDocument();
pdf.LoadFromFile("sample.pdf");
//Get the first page of the PDF
PdfPageBase page = pdf.Pages[0];
//Add a text watermark to the first page of the file, set the text format
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));
// save the document
pdf.SaveToFile("TextWaterMark.pdf");

Document after adding text watermark:



 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326301934&siteId=291194637