Установлено через 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
Ниже приведены основные шаги по добавлению водяного знака изображения в документ PDF.
- Создайте объект PdfDocument и загрузите образец PDF-файла с помощью метода PdfDocument.LoadFromFile().
- Загрузите файл изображения с помощью метода Image.FromFile().
- Прокрутите страницы в документе и получите конкретную страницу через свойство PdfDocument.Pages[].
- Установите изображение в качестве фона/водяного знака текущей страницы через свойство PdfPageBase.BackgroundImage. Установите положение и размер изображения с помощью свойства PdfPageBase.BackgroundRegion.
- Сохраните документ в другой файл PDF с помощью метода PdfDocument.SaveToFile().
- C#
- VB.NET
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\sample.pdf");
//Load an image
Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
//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();
}
}
}
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\sample.pdf")
'Load an image
Dim image As Image = Image.FromFile("C:\Users\Administrator\Desktop\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
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

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