Водяной знак относится к тексту и изображению, размещенным над или под содержимым файла PDF. Обычно он раскрывает специальную информацию о документе, например, об авторе или владельце, а также о том, является ли содержимое конфиденциальным. В этой статье я расскажу, как программно вставить текстовый водяной знак или водяной знак изображения в PDF, используя Free Spire.PDF для .NET с C# и VB.NET.
Добавить ссылки
Способ №1: Скачать Free Spire.PDF и разархивировать пакет где-нибудь на диске, чтобы найти папку BIN. В Spire.PDF есть библиотеки DLL, скомпилированные для нескольких версий .NET Framework, а также для .NET Core и других платформ. Выберите DLL из папки, которая вам точно нужна, и добавьте их все как зависимости в свой проект.
Способ №2: Создайте приложение .NET в своей Visual Studio и установите Free Spire.PDF напрямую через NuGet. Диспетчер пакетов NuGet автоматически установит правильную версию, соответствующую вашему приложению.
Примечание.Бесплатная версия ограничена 10 страницами при загрузке или создании PDF-файла.Чтобы избавиться от ограничения, вам необходимо использовать коммерческую версию. Шпиля.PDF.
Добавить текстовый водяной знак в PDF
Free Spire.PDF не предлагает интерфейс или класс для прямой работы с текстовым водяным знаком в PDF. Нам нужно нарисовать текст на холсте PDF в указанном месте, чтобы имитировать эффект водяного знака. Ниже приведены шаги по добавлению текстового водяного знака в центре каждой страницы под углом 45 градусов.
- Создайте объект PdfDocument.
- Загрузите образец PDF-файла с помощью метода PdfDocument.LoadFromFile().
- Создайте объект PdfTrueTypeFont.
- Укажите текст водяного знака и измерьте размер текста.
- Пролистайте все страницы документа.
- Задайте прозрачность холста для конкретной страницы с помощью метода PdfPageBase.Canvas.SetTransparency().
- Переведите систему координат с помощью метода PdfPageBase.Canvas.TranslateTransform(), чтобы текстовый водяной знак располагался в центре страницы.
- Поверните систему координат на 45 градусов против часовой стрелки, используя метод PdfPageBase.Canvas.RotateTransform().
- Нарисуйте текст водяного знака на определенной странице с помощью метода PdfPageBase.Canvas.DrawString().
- Сохраните документ в другой файл PDF с помощью метода PdfDocument.SaveToFile().
[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(@"C:\Users\Administrator\Desktop\Terms of Service.pdf"); //Create a PdfTrueTypeFont object PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 50f), true); //Set the watermark text string text = "DRAFT"; //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); float offset2 = (float)(textSize.Height * 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("AddTextWatermark.pdf"); } } }
[VB.NET]
Imports Spire.Pdf Imports Spire.Pdf.Graphics Imports System.Drawing Namespace AddTextWatermarkToPdf Class Program Shared Sub Main(ByVal args() As String) 'Create a PdfDocument object Dim pdf As PdfDocument = New PdfDocument() 'Load a sample PDF document pdf.LoadFromFile("C:\Users\Administrator\Desktop\Terms of Service.pdf") 'Create a PdfTrueTypeFont object Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Arial",50f),True) 'Set the watermark text Dim text As String = "DRAFT" '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 Dim page As PdfPageBase For Each 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) Next 'Save the changes to another file pdf.SaveToFile("AddTextWatermark.pdf") End Sub End Class End Namespace
Добавить водяной знак изображения в PDF
Точно так же нет прямого способа добавить водяной знак изображения в PDF с помощью Free Spire.PDF. Мы могли бы установить фоновое изображение каждой страницы, чтобы имитировать эффект водяного знака изображения. Ниже приведены шаги по добавлению водяного знака изображения в PDF на C# и VB.NET с использованием Free Spire.PDF для .NET.
- Создайте объект PdfDocument.
- Загрузите образец PDF-файла с помощью метода PdfDocument.LoadFromFile().
- Загрузите изображение из файла с помощью метода Image.FromFile() и получите ширину и высоту изображения.
- Пролистайте все страницы документа.
- Задайте прозрачность фона конкретной страницы с помощью свойства PdfPageBase.BackgroundOpacity.
- Установите фоновое изображение конкретной страницы с помощью свойства PdfPageBase.BackgroundImage.
- Поместите фоновое изображение в центр страницы с помощью свойства PdfPageBase.BackgroundRegion.
- Сохраните документ в другой файл PDF с помощью метода PdfDocument.SaveToFile().
[C#]
using Spire.Pdf; using System.Drawing; namespace AddImageWatermark { class Program { static void Main(string[] args) { //Create a PdfDocument object PdfDocument document = new PdfDocument(); //Load a sample PDF document document.LoadFromFile(@"C:\Users\Administrator\Desktop\Terms of Service.pdf"); //Load an image Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.jpg"); //Get the image width and height int imgWidth = image.Width; int imgHeight = image.Height; //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; float pageHeight = document.Pages[i].ActualSize.Height; //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); document.Pages[i].BackgroundRegion = rect; } //Save the document to file document.SaveToFile("AddImageWatermark.pdf"); document.Close(); } } }
[VB.NET]
Imports Spire.Pdf Imports System.Drawing Namespace AddImageWatermark Class Program Shared Sub Main(ByVal args() As String) 'Create a PdfDocument object Dim document As PdfDocument = New PdfDocument() 'Load a sample PDF document document.LoadFromFile("C:\Users\Administrator\Desktop\Terms of Service.pdf") 'Load an image Dim image As Image = Image.FromFile("C:\Users\Administrator\Desktop\logo.jpg") '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 For i = 0 To document.Pages.Count- 1 Step i + 1 '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.3f '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) / 2,(Integer)(pageHeight - imgHeight) / 2,imgWidth,imgHeight, Integer)) document.Pages(i).BackgroundRegion = rect Next 'Save the document to file document.SaveToFile("AddImageWatermark.pdf") document.Close() End Sub End Class End Namespace