C#/VB.NET: inserisci, sostituisci o elimina immagini in PDF
Sommario
Installato tramite NuGet
PM> Install-Package Spire.PDF
Link correlati
Rispetto ai documenti di solo testo, i documenti contenenti immagini sono senza dubbio più vividi e coinvolgenti per i lettori. Quando generi o modifichi un documento PDF, a volte potrebbe essere necessario inserire immagini per migliorarne l'aspetto e renderlo più accattivante. In questo articolo imparerai come inserire, sostituire o eliminare immagini nei documenti PDF in C# e VB.NET utilizzando Spire.PDF for .NET.
- Inserisci un'immagine in un documento PDF
- Sostituisci un'immagine con un'altra immagine in un documento PDF
- Elimina un'immagine specifica in un documento PDF
Installa Spire.PDF for .NET
Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.PDF for.NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.
PM> Install-Package Spire.PDF
Inserisci un'immagine in un documento PDF in C# e VB.NET
I seguenti passaggi mostrano come inserire un'immagine in un documento PDF esistente:
- Inizializza un'istanza della classe PdfDocument.
- Carica un documento PDF utilizzando il metodo PdfDocument.LoadFromFile().
- Ottieni la pagina desiderata nel documento PDF tramite la proprietà PdfDocument.Pages[pageIndex].
- Carica un'immagine utilizzando il metodo PdfImage.FromFile().
- Specificare la larghezza e l'altezza dell'area dell'immagine sulla pagina.
- Specificare le coordinate X e Y per iniziare a disegnare l'immagine.
- Disegna l'immagine sulla pagina utilizzando il metodo PdfPageBase.Canvas.DrawImage().
- Salvare il documento risultante utilizzando il metodo PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics; namespace InsertImage { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Input.pdf"); //Get the first page in the PDF document PdfPageBase page = pdf.Pages[0]; //Load an image PdfImage image = PdfImage.FromFile("image.jpg"); //Specify the width and height of the image area on the page float width = image.Width * 0.50f; float height = image.Height * 0.50f; //Specify the X and Y coordinates to start drawing the image float x = 180f; float y = 70f; //Draw the image at a specified location on the page page.Canvas.DrawImage(image, x, y, width, height); //Save the result document pdf.SaveToFile("AddImage.pdf", FileFormat.PDF); } } }
Sostituisci un'immagine con un'altra immagine in un documento PDF in C# e VB.NET
I seguenti passaggi dimostrano come sostituire un'immagine con un'altra immagine in un documento PDF:
- Inizializza un'istanza della classe PdfDocument.
- Carica un documento PDF utilizzando il metodo PdfDocument.LoadFromFile().
- Ottieni la pagina desiderata nel documento PDF tramite la proprietà PdfDocument.Pages[pageIndex].
- Carica un'immagine utilizzando il metodo PdfImage.FromFile().
- Inizializza un'istanza della classe PdfImageHelper.
- Ottieni le informazioni sull'immagine dalla pagina utilizzando il metodo PdfImageHelper.GetImagesInfo().
- Sostituisci un'immagine specifica sulla pagina con l'immagine caricata utilizzando il metodo PdfImageHelper.ReplaceImage().
- Salvare il documento risultante utilizzando il metodo PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Utilities; namespace ReplaceImage { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument doc = new PdfDocument(); //Load a PDF document doc.LoadFromFile("AddImage.pdf"); //Get the first page PdfPageBase page = doc.Pages[0]; //Load an image PdfImage image = PdfImage.FromFile("image1.jpg"); //Create a PdfImageHelper instance PdfImageHelper imageHelper = new PdfImageHelper(); //Get the image information from the page PdfImageInfo[] imageInfo = imageHelper.GetImagesInfo(page); //Replace the first image on the page with the loaded image imageHelper.ReplaceImage(imageInfo[0], image); //Save the result document doc.SaveToFile("ReplaceImage.pdf", FileFormat.PDF); } } }
Elimina un'immagine specifica in un documento PDF in C# e VB.NET
I seguenti passaggi mostrano come eliminare un'immagine da un documento PDF:
- Inizializza un'istanza della classe PdfDocument.
- Carica un documento PDF utilizzando il metodo PdfDocument.LoadFromFile().
- Ottieni la pagina desiderata nel documento PDF tramite la proprietà PdfDocument.Pages[pageIndex].
- Elimina un'immagine specifica sulla pagina utilizzando il metodo PdfPageBase.DeleteImage().
- Salvare il documento risultante utilizzando il metodo PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf; namespace DeleteImage { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.LoadFromFile("AddImage.pdf"); //Get the first page PdfPageBase page = pdf.Pages[0]; //Delete the first image on the page page.DeleteImage(0); //Save the result document pdf.SaveToFile("DeleteImage.pdf", FileFormat.PDF); } } }
Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.
C#/VB.NET : insérer, remplacer ou supprimer des images dans un PDF
Table des matières
Installé via NuGet
PM> Install-Package Spire.PDF
Liens connexes
Comparés aux documents contenant uniquement du texte, les documents contenant des images sont sans aucun doute plus vivants et plus attrayants pour les lecteurs. Lors de la génération ou de la modification d'un document PDF, vous devrez parfois insérer des images pour améliorer son apparence et le rendre plus attrayant. Dans cet article, vous apprendrez comment insérer, remplacer ou supprimer des images dans des documents PDF en C# et VB.NET en utilisant Spire.PDF for .NET.
- Insérer une image dans un document PDF
- Remplacer une image par une autre image dans un document PDF
- Supprimer une image spécifique dans un document PDF
Installer Spire.PDF for .NET
Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF for.NET comme références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.
PM> Install-Package Spire.PDF
Insérer une image dans un document PDF en C# et VB.NET
Les étapes suivantes montrent comment insérer une image dans un document PDF existant :
- Initialisez une instance de la classe PdfDocument.
- Chargez un document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Obtenez la page souhaitée dans le document PDF via la propriété PdfDocument.Pages[pageIndex].
- Chargez une image à l’aide de la méthode PdfImage.FromFile().
- Spécifiez la largeur et la hauteur de la zone d'image sur la page.
- Spécifiez les coordonnées X et Y pour commencer à dessiner l'image.
- Dessinez l'image sur la page à l'aide de la méthode PdfPageBase.Canvas.DrawImage().
- Enregistrez le document résultat à l'aide de la méthode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics; namespace InsertImage { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Input.pdf"); //Get the first page in the PDF document PdfPageBase page = pdf.Pages[0]; //Load an image PdfImage image = PdfImage.FromFile("image.jpg"); //Specify the width and height of the image area on the page float width = image.Width * 0.50f; float height = image.Height * 0.50f; //Specify the X and Y coordinates to start drawing the image float x = 180f; float y = 70f; //Draw the image at a specified location on the page page.Canvas.DrawImage(image, x, y, width, height); //Save the result document pdf.SaveToFile("AddImage.pdf", FileFormat.PDF); } } }
Remplacer une image par une autre image dans un document PDF en C# et VB.NET
Les étapes suivantes montrent comment remplacer une image par une autre image dans un document PDF :
- Initialisez une instance de la classe PdfDocument.
- Chargez un document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Obtenez la page souhaitée dans le document PDF via la propriété PdfDocument.Pages[pageIndex].
- Chargez une image à l’aide de la méthode PdfImage.FromFile().
- Initialisez une instance de la classe PdfImageHelper.
- Obtenez les informations sur l’image de la page à l’aide de la méthode PdfImageHelper.GetImagesInfo().
- Remplacez une image spécifique sur la page par l'image chargée à l'aide de la méthode PdfImageHelper.ReplaceImage().
- Enregistrez le document résultat à l'aide de la méthode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Utilities; namespace ReplaceImage { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument doc = new PdfDocument(); //Load a PDF document doc.LoadFromFile("AddImage.pdf"); //Get the first page PdfPageBase page = doc.Pages[0]; //Load an image PdfImage image = PdfImage.FromFile("image1.jpg"); //Create a PdfImageHelper instance PdfImageHelper imageHelper = new PdfImageHelper(); //Get the image information from the page PdfImageInfo[] imageInfo = imageHelper.GetImagesInfo(page); //Replace the first image on the page with the loaded image imageHelper.ReplaceImage(imageInfo[0], image); //Save the result document doc.SaveToFile("ReplaceImage.pdf", FileFormat.PDF); } } }
Supprimer une image spécifique dans un document PDF en C# et VB.NET
Les étapes suivantes montrent comment supprimer une image d'un document PDF :
- Initialisez une instance de la classe PdfDocument.
- Chargez un document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Obtenez la page souhaitée dans le document PDF via la propriété PdfDocument.Pages[pageIndex].
- Supprimez une image spécifique sur la page à l’aide de la méthode PdfPageBase.DeleteImage().
- Enregistrez le document résultat à l'aide de la méthode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf; namespace DeleteImage { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.LoadFromFile("AddImage.pdf"); //Get the first page PdfPageBase page = pdf.Pages[0]; //Delete the first image on the page page.DeleteImage(0); //Save the result document pdf.SaveToFile("DeleteImage.pdf", FileFormat.PDF); } } }
Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.
C#/VB.NET: Adicionar marcas d'água de imagem ao PDF
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
Uma marca d'água de imagem geralmente é um logotipo ou sinal que aparece no fundo de documentos digitais, indicando o proprietário dos direitos autorais do conteúdo. Colocar uma marca d'água em seu documento PDF com uma imagem pode impedir que seus dados sejam reutilizados ou modificados. Este artigo demonstra como adicione uma marca d'água de imagem a PDF em C# e VB.NET usando Spire.PDF for .NET.
Instalar o Spire.PDF for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.PDF for.NET como referências em seu projeto .NET. Os arquivos DLLs podem ser baixados deste link ou instalados via NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Adicionar uma marca d'água de imagem ao PDF
A seguir estão as principais etapas para adicionar uma marca d'água de imagem a um documento PDF.
- Crie um objeto PdfDocument e carregue um arquivo PDF de amostra usando o método PdfDocument.LoadFromFile().
- Carregue um arquivo de imagem usando o método Image.FromFile().
- Percorra as páginas do documento e obtenha a página específica por meio da propriedade PdfDocument.Pages[].
- Defina a imagem como plano de fundo/imagem de marca d'água da página atual por meio da propriedade PdfPageBase.BackgroundImage. Defina a posição e o tamanho da imagem por meio da propriedade PdfPageBase.BackgroundRegion.
- Salve o documento em um arquivo PDF diferente usando o método 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
Solicitar uma licença temporária
Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.
C#/VB.NET: добавление водяных знаков изображений в PDF
Установлено через 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-дневную пробную лицензию для себя.
C#/VB.NET: Bildwasserzeichen zu PDF hinzufügen
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.PDF
verwandte Links
Ein Bildwasserzeichen ist normalerweise ein Logo oder Zeichen, das auf dem Hintergrund digitaler Dokumente erscheint und den Urheberrechtsinhaber des Inhalts angibt. Wenn Sie Ihr PDF-Dokument mit einem Bild mit einem Wasserzeichen versehen, können Sie verhindern, dass Ihre Daten wiederverwendet oder geändert werden. Dieser Artikel zeigt, wie es geht Fügen Sie dem PDF ein Bildwasserzeichen hinzu in C# und VB.NET mit Spire.PDF for .NET.
Installieren Sie Spire.PDF for .NET
Zunächst müssen Sie die im Spire.PDF for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLLs-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.
- Package Manager
PM> Install-Package Spire.PDF
Fügen Sie ein Bildwasserzeichen zu PDF hinzu
Im Folgenden finden Sie die wichtigsten Schritte zum Hinzufügen eines Bildwasserzeichens zu einem PDF-Dokument.
- Erstellen Sie ein PdfDocument-Objekt und laden Sie eine Beispiel-PDF-Datei mit der Methode PdfDocument.LoadFromFile(). method.
- Laden Sie eine Bilddatei mit der Methode Image.FromFile().
- Durchlaufen Sie die Seiten im Dokument und rufen Sie die spezifische Seite über die Eigenschaft PdfDocument.Pages[] ab.
- Legen Sie das Bild über die Eigenschaft PdfPageBase.BackgroundImage als Hintergrund-/Wasserzeichenbild der aktuellen Seite fest. Legen Sie die Bildposition und -größe über die Eigenschaft PdfPageBase.BackgroundRegion fest.
- Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer anderen PDF-Datei.
- 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
Beantragen Sie eine temporäre Lizenz
Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.
C#/VB.NET: Agregar marcas de agua de imagen a PDF
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.PDF
enlaces relacionados
Una marca de agua de imagen suele ser un logotipo o signo que aparece en el fondo de los documentos digitales, indicando el propietario de los derechos de autor del contenido. La marca de agua de su documento PDF con una imagen puede evitar que sus datos se reutilicen o modifiquen. Este artículo demuestra cómo agregue una marca de agua de imagen a PDF en C# y VB.NET usando Spire.PDF for .NET.
Instalar Spire.PDF for .NET
Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.PDF for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Agregar una marca de agua de imagen a PDF
Los siguientes son los pasos principales para agregar una marca de agua de imagen a un documento PDF.
- Cree un objeto PdfDocument y cargue un archivo PDF de muestra utilizando el método PdfDocument.LoadFromFile().
- Cargue un archivo de imagen usando el método Image.FromFile().
- Recorra las páginas del documento y obtenga la página específica a través de la propiedad PdfDocument.Pages[].
- Establezca la imagen como imagen de fondo/marca de agua de la página actual a través de la propiedad PdfPageBase.BackgroundImage. Establezca la posición y el tamaño de la imagen a través de la propiedad PdfPageBase.BackgroundRegion.
- Guarde el documento en un archivo PDF diferente usando el método 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
Solicitar una Licencia Temporal
Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.
C#/VB.NET: PDF에 이미지 워터마크 추가
핍으로 설치
PM> Install-Package Spire.PDF
NuGet을 통해 설치됨
이미지 워터마크는 일반적으로 디지털 문서의 배경에 나타나는 로고 또는 기호로 콘텐츠의 저작권 소유자를 나타냅니다. PDF 문서에 이미지를 워터마킹하면 데이터가 재사용되거나 수정되는 것을 방지할 수 있습니다. 이 문서에서는 다음을 수행하는 방법을 보여줍니다 PDF에 이미지 워터마크 추가 Spire.PDF for .NET 사용하는 C# 및 VB.NET.
Spire.PDF for .NET 설치
먼저 Spire.PDF for .NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
- Package Manager
PM> Install-Package Spire.PDF
PDF에 이미지 워터마크 추가
다음은 PDF 문서에 이미지 워터마크를 추가하는 주요 단계입니다.
- PdfDocument 개체를 만들고 PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 파일을 로드합니다.
- Image.FromFile() 메서드를 사용하여 이미지 파일을 로드합니다.
- 문서의 페이지를 반복하고 PdfDocument.Pages[] 속성을 통해 특정 페이지를 가져옵니다.
- PdfPageBase.BackgroundImage 속성을 통해 이미지를 현재 페이지의 배경/워터마크 이미지로 설정합니다. PdfPageBase.BackgroundRegion 속성을 통해 이미지 위치 및 크기를 설정합니다.
- PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 PDF 파일로 저장합니다.
- 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일 평가판 라이선스 요청 자신을 위해.
C#/VB.NET: aggiungi filigrane di immagini al PDF
Installato tramite NuGet
PM> Install-Package Spire.PDF
Link correlati
Una filigrana di immagine è solitamente un logo o un segno che appare sullo sfondo di documenti digitali, indicando il proprietario del copyright del contenuto. La filigrana del documento PDF con un'immagine può impedire il riutilizzo o la modifica dei dati. Questo articolo illustra come aggiungere una filigrana immagine al PDF in C# e VB.NET utilizzando Spire.PDF for .NET.
Installa Spire.PDF for .NET
Per cominciare, è necessario aggiungere i file DLL inclusi nel pacchetto Spire.PDF for.NET come riferimenti nel progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Aggiungi una filigrana immagine al PDF
Di seguito sono riportati i passaggi principali per aggiungere una filigrana immagine a un documento PDF.
- Creare un oggetto PdfDocument e caricare un file PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
- Carica un file immagine usando il metodo Image.FromFile().
- Scorrere le pagine del documento e ottenere la pagina specifica tramite la proprietà PdfDocument.Pages[].
- Impostare l'immagine come immagine di sfondo/filigrana della pagina corrente tramite la proprietà PdfPageBase.BackgroundImage. Impostare la posizione e le dimensioni dell'immagine tramite la proprietà PdfPageBase.BackgroundRegion.
- Salvare il documento in un file PDF diverso utilizzando il metodo 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
Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni delle funzioni, per favore richiedere una licenza di prova di 30 giorni per te.
C#/VB.NET : ajouter des filigranes d'image au PDF
Table des matières
Installé via NuGet
PM> Install-Package Spire.PDF
Liens connexes
Un filigrane d'image est généralement un logo ou un signe qui apparaît sur l'arrière-plan des documents numériques, indiquant le titulaire du droit d'auteur du contenu. Ajouter un filigrane à votre document PDF avec une image peut empêcher la réutilisation ou la modification de vos données. Cet article montre comment ajouter un filigrane d'image au PDF en C# et VB.NET en utilisant Spire.PDF for .NET.
Installer Spire.PDF for .NET
Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF for .NET en tant que références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Ajouter un filigrane d'image au PDF
Voici les principales étapes pour ajouter un filigrane d'image à un document PDF.
- Créez un objet PdfDocument et chargez un exemple de fichier PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Chargez un fichier image à l'aide de la méthode Image.FromFile().
- Parcourez les pages du document et obtenez la page spécifique via la propriété PdfDocument.Pages[].
- Définissez l'image comme image d'arrière-plan/filigrane de la page actuelle via la propriété PdfPageBase.BackgroundImage. Définissez la position et la taille de l'image via la propriété PdfPageBase.BackgroundRegion.
- Enregistrez le document dans un autre fichier PDF à l'aide de la méthode 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
Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.
C#/VB.NET: Adicionar marcas d'água de texto ao PDF
Índice
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
Para evitar que seu documento PDF seja usado de maneira não autorizada, você pode colocar uma marca d'água no documento com texto ou imagem. Neste artigo, você aprenderá como programaticamente adicione marcas d'água de texto (marcas d'água de linha única e multilinha) a PDF em C# e VB.NET usando Spire.PDF for .NET.
Instalar o Spire.PDF for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.PDF for.NET como referências em seu projeto .NET. Os arquivos DLLs podem ser baixados deste link ou instalado via NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Adicionar uma marca d'água de texto ao PDF
O Spire.PDF não fornece uma interface ou uma classe para lidar com marcas d'água em arquivos PDF. Você pode, no entanto, desenhar texto como "confidencial", "uso interno" ou "rascunho" em cada página para imitar o efeito da marca d'água. A seguir estão as principais etapas para adicionar uma marca d'água de texto a todas as páginas de um documento PDF.
- Crie um objeto PdfDocument e carregue um documento PDF de amostra usando o método PdfDocument.LoadFromFile().
- Crie um objeto PdfTrueTypeFont, especifique o texto da marca d'água e meça o tamanho do texto usando o método PdfFontBase.MeasureString().
- Atravesse todas as páginas do documento.
- Traduza o sistema de coordenadas de uma determinada página por coordenadas especificadas usando o método PdfPageBase.Canvas.TraslateTransform() e gire o sistema de coordenadas 45 graus no sentido anti-horário usando o método PdfPageBase.Canvas.RotateTransform(). Isso garante que a marca d'água apareça no meio da página em um ângulo de 45 graus.
- Desenhe o texto da marca d'água na página usando o método PdfPageBase.Canvas.DrawString().
- Salve o documento em um arquivo PDF diferente usando o método 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
Adicionar marcas d'água de texto de várias linhas ao PDF
Há momentos em que você pode querer adicionar mais de uma linha de marcas d'água de texto ao seu documento. Para obter o efeito de marca d'água lado a lado, você pode usar a classe PdfTilingBrush, que produz um padrão lado a lado que é repetido para preencher uma área de gráficos. A seguir estão as principais etapas para adicionar marcas d'água de várias linhas a um documento PDF.
- Crie um objeto PdfDocument e carregue um documento PDF de amostra usando o método PdfDocument.LoadFromFile().
- Crie um método personalizado InsertMultiLineTextWatermark(PdfPageBase page, String watermarkText, fonte PdfTrueTypeFont, int rowNum, int columnNum) para adicionar marcas d'água de texto de várias linhas a uma página PDF. Os parâmetros rowNum e columnNum especificam o número da linha e da coluna das marcas d'água lado a lado.
- Percorra todas as páginas do documento e chame o método personalizado InsertMultiLineTextWatermark() para aplicar marcas d'água a cada página.
- Salve o documento em outro arquivo usando o método 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
Solicitar uma licença temporária
Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.