Оглавление
Установлено через NuGet
PM> Install-Package Spire.PDF
Ссылки по теме
Чтобы предотвратить несанкционированное использование вашего PDF-документа, вы можете пометить документ водяным знаком с текстом или изображением. В этой статье вы узнаете, как программно добавить текстовые водяные знаки (однострочные и многострочные водяные знаки) в PDF в C# и VB.NET с использованием Spire.PDF for .NET.
Установите Spire.PDF for .NET
Для начала вам нужно добавить файлы DLL, включенные в пакет Spire.PDF for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Добавить текстовый водяной знак в PDF
Spire.PDF не предоставляет интерфейс или класс для работы с водяными знаками в файлах PDF. Однако вы можете нарисовать текст типа «конфиденциально», «для внутреннего пользования» или «черновик» на каждой странице, чтобы имитировать эффект водяного знака. Ниже приведены основные шаги по добавлению текстового водяного знака на все страницы PDF-документа.
- Создайте объект PdfDocument и загрузите образец PDF-документа с помощью метода PdfDocument.LoadFromFile().
- Создайте объект PdfTrueTypeFont, укажите текст водяного знака и измерьте размер текста с помощью метода PdfFontBase.MeasureString().
- Пролистайте все страницы документа.
- Перевести систему координат определенной страницы на заданные координаты с помощью метода PdfPageBase.Canvas.TraslateTransform() и повернуть систему координат на 45 градусов против часовой стрелки с помощью метода PdfPageBase.Canvas.RotateTransform(). Это гарантирует, что водяной знак появится в середине страницы под углом 45 градусов.
- Нарисуйте текст водяного знака на странице с помощью метода PdfPageBase.Canvas.DrawString().
- Сохраните документ в другой файл PDF с помощью метода PdfDocument.SaveToFile().
- C#
- VB.NET
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\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);
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("TextWatermark.pdf");
}
}
}
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\sample.pdf")
'Create a PdfTrueTypeFont object
Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Arial",50f),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
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("TextWatermark.pdf")
End Sub
End Class
End Namespace

Добавить многострочные текстовые водяные знаки в PDF
Бывают случаи, когда вам может понадобиться добавить в документ более одной строки текстовых водяных знаков. Чтобы добиться эффекта мозаичного водяного знака, вы можете использовать класс PdfTilingBrush, который создает мозаичный узор, который повторяется для заполнения графической области. Ниже приведены основные шаги по добавлению многострочных водяных знаков в документ PDF.
- Создайте объект PdfDocument и загрузите образец PDF-документа с помощью метода PdfDocument.LoadFromFile().
- Создайте пользовательский метод InsertMultiLineTextWatermark(PdfPageBase page, String watermarkText, шрифт PdfTrueTypeFont, int rowNum, int columnNum) для добавления многострочных текстовых водяных знаков на страницу PDF. Параметры rowNum и columnNum задают номер строки и столбца мозаичных водяных знаков.
- Просмотрите все страницы документа и вызовите пользовательский метод InsertMultiLineTextWatermark(), чтобы применить водяные знаки к каждой странице.
- Сохраните документ в другой файл, используя метод PdfDocument.SaveToFile().
- C#
- VB.NET
using System;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddMultiLineTextWatermark
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load a sample PDF document
pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
//Create a PdfTrueTypeFont object
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 20f), true);
//Traverse all the pages
for (int i = 0; i < pdf.Pages.Count; i++)
{
//Call InsertMultiLineTextWatermark() method to add text watermarks to the specified page
InsertMultiLineTextWatermark(pdf.Pages[i], "E-ICEBLUE CO LTD", font, 3, 3);
}
//Save the document to another file
pdf.SaveToFile("MultiLineTextWatermark.pdf");
}
//Create a custom method to insert multi-line text watermarks to a page
static void InsertMultiLineTextWatermark(PdfPageBase page, String watermarkText, PdfTrueTypeFont font, int rowNum, int columnNum)
{
//Measure the text size
SizeF textSize = font.MeasureString(watermarkText);
//Calculate the values of two offset variables, which will be used to calculate the translation amount of coordinate system
float offset1 = (float)(textSize.Width * System.Math.Sqrt(2) / 4);
float offset2 = (float)(textSize.Height * System.Math.Sqrt(2) / 4);
//Create a tile brush
PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.ActualSize.Width / columnNum, page.ActualSize.Height / rowNum));
brush.Graphics.SetTransparency(0.3f);
brush.Graphics.Save();
brush.Graphics.TranslateTransform(brush.Size.Width / 2 - offset1 - offset2, brush.Size.Height / 2 + offset1 - offset2);
brush.Graphics.RotateTransform(-45);
//Draw watermark text on the tile brush
brush.Graphics.DrawString(watermarkText, font, PdfBrushes.Violet, 0, 0);
brush.Graphics.Restore();
//Draw a rectangle (that covers the whole page) using the tile brush
page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.ActualSize));
}
}
}
Imports System
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing
Namespace AddMultiLineTextWatermark
Class Program
Shared Sub Main(ByVal args() As String)
'Create a PdfDocument instance
Dim pdf As PdfDocument = New PdfDocument()
'Load a sample PDF document
pdf.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")
'Create a PdfTrueTypeFont object
Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Arial",20f),True)
'Traverse all the pages
Dim i As Integer
For i = 0 To pdf.Pages.Count- 1 Step i + 1
'Call InsertMultiLineTextWatermark() method to add text watermarks to the specified page
InsertMultiLineTextWatermark(pdf.Pages(i), "E-ICEBLUE CO LTD", font, 3, 3)
Next
'Save the document to another file
pdf.SaveToFile("MultiLineTextWatermark.pdf")
End Sub
'Create a custom method to insert multi-line text watermarks to a page
Shared Sub InsertMultiLineTextWatermark(ByVal page As PdfPageBase, ByVal watermarkText As String, ByVal font As PdfTrueTypeFont, ByVal rowNum As Integer, ByVal columnNum As Integer)
'Measure the text size
Dim textSize As SizeF = font.MeasureString(watermarkText)
'Calculate the values of two offset variables, which will be used to calculate the translation amount of 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)
'Create a tile brush
Dim brush As PdfTilingBrush = New PdfTilingBrush(New SizeF(page.ActualSize.Width / columnNum,page.ActualSize.Height / rowNum))
brush.Graphics.SetTransparency(0.3f)
brush.Graphics.Save()
brush.Graphics.TranslateTransform(brush.Size.Width / 2 - offset1 - offset2, brush.Size.Height / 2 + offset1 - offset2)
brush.Graphics.RotateTransform(-45)
'Draw watermark text on the tile brush
brush.Graphics.DrawString(watermarkText, font, PdfBrushes.Violet, 0, 0)
brush.Graphics.Restore()
'Draw a rectangle (that covers the whole page) using the tile brush
page.Canvas.DrawRectangle(brush, New RectangleF(New PointF(0, 0), page.ActualSize))
End Sub
End Class
End Namespace

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.