Watermark is a recognizable text or image that appears under document text. A watermark is useful in the examination of paper because it can be widely used for trademarks, locations and so on. This article aims at introducing how to add PDF text watermark for WPF through a simple WPF PDF API Spire.PDF for WPF. Also it can implement PDF watermark by image.
First we need to complete the preparatory work:
- Download the latest Spire.PDF and install it on your machine.
- Add the Spire.PDF.WPF.dll files as reference.
- Open bin folder and select the three dll files under .NET 4.0.
- Right click property and select properties in its menu.
- Set the target framework as .NET 4.
- Add Spire.PDF as namespace.
Here comes to the explanation of the code.
Step 1: Create an instance of Spire.PDF.Document
[C#]
PdfDocument doc = new PdfDocument();
Step 2: Load the file base on a specified file path
[C#]
doc.LoadFromFile(@"..\..\Sample1.pdf");
Step 3: Add the text watermark to the first page
[C#]
PdfPageBase page = doc.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("Spire.Pdf Demo",new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 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));
Step 4: Save the PDF file
[C#]
doc.SaveToFile("TextWaterMark.pdf");
Full code:
[C#]
private void button1_Click(object sender, RoutedEventArgs e) { PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"..\..\Sample1.pdf"); PdfPageBase page = doc.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("Spire.Pdf Demo",new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 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)); doc.SaveToFile("TextWaterMark.pdf"); }
Effect screenshot: