Add Text/Image Watermarks to PDF in C#/VB.NET
We will take a detailed look at the methods for applying watermark PDF in this article. This article will be divided into three parts that will outline how you can add text/image watermarks to PDF using C#/VB.NET code. To achieve this functionality, you just need to follow a few simple steps. Read on for more information.
Programming Environment
In this test, Free Spire.PDF
for .NET is introduced into the program. The Spire.PDF.dll file can be
referenced by:
Method 1:
Download Free
Spire.PDF for .NET locally, unzip it, and install it. After the
installation is complete, find Spire.PDF.dll in the BIN folder under the
installation path. Then open the "Solution Explorer" in Visual
Studio, right-click "References", "Add Reference", and add
a reference to the dll file in the BIN folder of the local path to the program.
Method 2:
Install via NuGet. It can
be installed by the following 2 methods:
(1) You can open the
"Solution Explorer" in Visual Studio, right-click
"References", "Manage NuGet Packages", then search for
"Free Spire.PDF", and click "Install". Wait for the program
installation to complete.
(2) Copy the following
content to the PM console installation.
Install-Package FreeSpire.PDF -Version 8.6.0
The watermarks come in three
different styles, you can select one you like the best.
Add Text Watermark to PDF
Specific Steps:
l Create a PdfDocument object and load the sample document using
PdfDocument.LoadFromFile() method.
l Set the watermark text and Measure the text size using
PdfFontBase.MeasureString() method.
l Traverse all the pages in the document.
l Translate the coordinate system of a certain page by specified
coordinates using PdfPageBase.Canvas.TraslateTransform() method, and rotate the
coordinate system 45 degrees counterclockwise using
PdfPageBase.Canvas.RotateTransform() method.
l Draw the watermark text on the page using PdfPageBase.Canvas.DrawString()
method.
l Save the document to another PDF file using
PdfDocument.SaveToFile() method.
The following code sample shows how to add text watermarks to
PDF.
【C#】
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddTextWatermarkToPdf
class Program
{
static void Main(string[] args)
//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
//Load a sample PDF document
pdf.LoadFromFile("Sample.pdf");
//Create a PdfTrueTypeFont object
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 50f), true);
//Set the watermark text
string text = "CONFIDENTIAL";
//Measure the text size
SizeF textSize = font.MeasureString(text);
//Calculate the values of two offset variables,
//which will be used to calculate the translation amount of the coordinate system
float offset1 = (float)(textSize.Width * System.Math.Sqrt(2) / 4);
//Traverse all the pages in the document
foreach (PdfPageBase page in pdf.Pages)
//Set the page transparency
page.Canvas.SetTransparency(0.8f);
//Translate the coordinate system by specified coordinates
page.Canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2);
//Rotate the coordinate system 45 degrees counterclockwise
page.Canvas.RotateTransform(-45);
//Draw watermark text on the page
page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0);
}
//Save the changes to another file
pdf.SaveToFile("TextWatermark.pdf");
}
}
【VB.NET】
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing
Namespace AddTextWatermarkToPdf
Class Program
Private Shared Sub Main(ByVal args() As String)
'Create a PdfDocument object
Dim pdf As PdfDocument = New PdfDocument
'Load a sample PDF document
pdf.LoadFromFile("Sample.pdf")
'Create a PdfTrueTypeFont object
Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Arial", 50!), true)
'Set the watermark text
Dim text As String = "CONFIDENTIAL"
'Measure the text size
Dim textSize As SizeF = font.MeasureString(text)
'Calculate the values of two offset variables,
'which will be used to calculate the translation amount of the coordinate system
Dim offset1 As Single = CType((textSize.Width _
* (System.Math.Sqrt(2) / 4)),Single)
Dim offset2 As Single = CType((textSize.Height _
* (System.Math.Sqrt(2) / 4)),Single)
'Traverse all the pages in the document
For Each page As PdfPageBase In pdf.Pages
'Set the page transparency
page.Canvas.SetTransparency(0.8!)
'Translate the coordinate system by specified coordinates
page.Canvas.TranslateTransform(((page.Canvas.Size.Width / 2) _
- (offset1 - offset2)), ((page.Canvas.Size.Height / 2) _
+ (offset1 - offset2)))
'Rotate the coordinate system 45 degrees counterclockwise
page.Canvas.RotateTransform(-45)
'Draw watermark text on the page
page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0)
Next
'Save the changes to another file
pdf.SaveToFile("TextWatermark.pdf")
End Sub
End Class
End Namespace
The code path is for reference only, and you can customize the path as you want.
Effective shot:
Add Multi-Line Text Watermarks to PDF
l Create a PDF document and load the file using PdfDocument. LoadFromFile()method.
【C#】
namespace TextWaterMark
class Program
{
static void Main(string[] args)
//Create a pdf document and load file from disk
PdfDocument doc = new PdfDocument();
//Get the first page
PdfPageBase page = doc.Pages[0];
//Draw text watermark
PdfTilingBrush brush
= new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));
brush.Graphics.Save();
brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
brush.Graphics.RotateTransform(-45);
brush.Graphics.DrawString("internal use",
brush.Graphics.SetTransparency(1);
page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));
//Save pdf file
doc.SaveToFile("TextWaterMark1.pdf");
}
}
}
【VB.NET】
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Namespace TextWaterMark
Class Program
Private Shared Sub Main(ByVal args() As String)
'Create a pdf document and load file from disk
Dim doc As PdfDocument = New PdfDocument
doc.LoadFromFile("Sample1.pdf")
'Get the first page
Dim page As PdfPageBase = doc.Pages(0)
'Draw text watermark
Dim brush As PdfTilingBrush = New PdfTilingBrush(New SizeF((page.Canvas.ClientSize.Width / 2), (page.Canvas.ClientSize.Height / 3)))
brush.Graphics.SetTransparency(0.3!)
brush.Graphics.Save
brush.Graphics.TranslateTransform((brush.Size.Width / 2), (brush.Size.Height / 2))
brush.Graphics.RotateTransform(-45)
brush.Graphics.DrawString("internal use", 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))
'Save pdf file
doc.SaveToFile("TextWaterMark1.pdf")
End Sub
End Class
End Namespace
Effective shot:
Add an Image Watermarks to PDF
Specific Steps:
l Using Image.FromFile() method to load an image.
l Get the image width and height
l Loop through the pages in the document, and get the specific
page through PdfDocument.Pages() property.
l Set the image as watermark image of the current page through
PdfPageBase.BackgroundImage property. Set the image position and size through
PdfPageBase.BackgroundRegion property.
l Save the document to file using PdfDocument.SaveToFile() method.
Full code:
【C#】
namespace AddImageWatermark
class Program
{
static void Main(string[] args)
//Create a PdfDocument object
PdfDocument document = new PdfDocument();
//Load a sample PDF document
document.LoadFromFile("sample.pdf");
//Load an image
Image image = Image.FromFile("logo.png");
//Get the image width and height
int imgWidth = image.Width;
//Loop through the pages
for (int i = 0; i < document.Pages.Count; i++)
//Get the page width and height
float pageWidth = document.Pages[i].ActualSize.Width;
//Set the background opacity
document.Pages[i].BackgroudOpacity = 0.3f;
//Set the background image of current page
document.Pages[i].BackgroundImage = image;
//Position the background image at the center of the page
Rectangle rect = new Rectangle((int)(pageWidth - imgWidth) / 2, (int)(pageHeight - imgHeight) / 2, imgWidth, imgHeight);
}
//Save the document to file
document.SaveToFile("AddImageWatermark.pdf");
}
}
}
【VB.NET】
Imports Spire.Pdf
Imports System.Drawing
Namespace AddImageWatermark
Class Program
Private Shared Sub Main(ByVal args() As String)
'Create a PdfDocument object
Dim document As PdfDocument = New PdfDocument
'Load a sample PDF document
document.LoadFromFile("sample.pdf")
'Load an image
Dim image As Image = Image.FromFile("logo.png")
'Get the image width and height
Dim imgWidth As Integer = image.Width
Dim imgHeight As Integer = image.Height
'Loop through the pages
Dim i As Integer = 0
Do While (i < document.Pages.Count)
'Get the page width and height
Dim pageWidth As Single = document.Pages(i).ActualSize.Width
Dim pageHeight As Single = document.Pages(i).ActualSize.Height
'Set the background opacity
document.Pages(i).BackgroudOpacity = 0.3!
'Set the background image of current page
document.Pages(i).BackgroundImage = image
'Position the background image at the center of the page
Dim rect As Rectangle = New Rectangle((CType((pageWidth - imgWidth),Integer) / 2), (CType((pageHeight - imgHeight),Integer) / 2), imgWidth, imgHeight)
document.Pages(i).BackgroundRegion = rect
i = (i + 1)
Loop
'Save the document to file
document.SaveToFile("AddImageWatermark.pdf")
document.Close
End Sub
End Class
End Namespace
Effective shot:
Conclusion:
In this post, you have learned how to add different types of
watermarks to PDF in C#/VB.NET. Not only that, we also have other functions,
such as,
Extract Image from PDF and Save it to New PDF File, Draw
Text in PDF with Different Styles and so on. Apart from that, if you'd like to learn more, you
can visit the Spire.PDF
Program Guide Content for .NET to explore more about for Spire.PDF
for .NET.
Comments
Post a Comment