Table des matières
Installé via NuGet
PM> Install-Package Spire.PDF
Liens connexes
Pour empêcher que votre document PDF ne soit utilisé de manière non autorisée, vous pouvez filigraner le document avec du texte ou une image. Dans cet article, vous apprendrez à programmer ajouter des filigranes de texte (filigranes à une seule ligne et multilignes) 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 de texte au PDF
Spire.PDF ne fournit pas d'interface ou de classe pour gérer les filigranes dans les fichiers PDF. Vous pouvez cependant dessiner du texte comme "confidentiel", "usage interne" ou "brouillon" sur chaque page pour imiter l'effet de filigrane. Voici les principales étapes pour ajouter un filigrane de texte à toutes les pages d'un document PDF.
- Créez un objet PdfDocument et chargez un exemple de document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Créez un objet PdfTrueTypeFont, spécifiez le texte du filigrane et mesurez la taille du texte à l'aide de la méthode PdfFontBase.MeasureString().
- Parcourir toutes les pages du document.
- Traduisez le système de coordonnées d'une certaine page par des coordonnées spécifiées à l'aide de la méthode PdfPageBase.Canvas.TraslateTransform() et faites pivoter le système de coordonnées de 45 degrés dans le sens antihoraire à l'aide de la méthode PdfPageBase.Canvas.RotateTransform(). Cela garantit que le filigrane apparaîtra au milieu de la page à un angle de 45 degrés.
- Dessinez le texte du filigrane sur la page à l'aide de la méthode PdfPageBase.Canvas.DrawString().
- Enregistrez le document dans un autre fichier PDF à l'aide de la méthode 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

Ajouter des filigranes de texte multilignes au PDF
Il peut arriver que vous souhaitiez ajouter plusieurs lignes de filigranes de texte à votre document. Pour obtenir l'effet de filigrane en mosaïque, vous pouvez utiliser la classe PdfTilingBrush, qui produit un motif en mosaïque répété pour remplir une zone graphique. Voici les principales étapes pour ajouter des filigranes multilignes à un document PDF.
- Créez un objet PdfDocument et chargez un exemple de document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Créez une méthode personnalisée InsertMultiLineTextWatermark(PdfPageBase page, String watermarkText, PdfTrueTypeFont font, int rowNum, int columnNum) pour ajouter des filigranes de texte multiligne à une page PDF. Les paramètres rowNum et columnNum spécifient le numéro de ligne et de colonne des filigranes en mosaïque.
- Parcourez toutes les pages du document et appelez la méthode personnalisée InsertMultiLineTextWatermark() pour appliquer des filigranes à chaque page.
- Enregistrez le document dans un autre fichier à l'aide de la méthode 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

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.