Чтобы предотвратить несанкционированное использование вашего 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

C#/VB.NET: Add Text Watermarks to PDF

Добавить многострочные текстовые водяные знаки в 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

C#/VB.NET: Add Text Watermarks to PDF

Подать заявку на временную лицензию

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

Смотрите также

Über NuGet installiert

PM> Install-Package Spire.PDF

verwandte Links

Um zu verhindern, dass Ihr PDF-Dokument unbefugt verwendet wird, können Sie das Dokument mit einem Wasserzeichen mit Text oder einem Bild versehen. In diesem Artikel erfahren Sie, wie Sie programmgesteuert vorgehen Fügen Sie Textwasserzeichen (einzeilige und mehrzeilige Wasserzeichen) zu PDF 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 Textwasserzeichen zu PDF hinzu

Spire.PDF bietet keine Schnittstelle oder Klasse zum Umgang mit Wasserzeichen in PDF-Dateien. Sie können jedoch auf jeder Seite Text wie „vertraulich“, „interner Gebrauch“ oder „Entwurf“ zeichnen, um den Wasserzeicheneffekt nachzuahmen. Im Folgenden finden Sie die wichtigsten Schritte zum Hinzufügen eines Textwasserzeichens zu allen Seiten eines PDF-Dokuments.

  • Erstellen Sie ein PdfDocument-Objekt und laden Sie ein Beispiel-PDF-Dokument mit der Methode PdfDocument.LoadFromFile().
  • Erstellen Sie ein PdfTrueTypeFont-Objekt, geben Sie den Wasserzeichentext an und messen Sie die Textgröße mit der Methode PdfFontBase.MeasureString().
  • Durchlaufen Sie alle Seiten im Dokument.
  • Verschieben Sie das Koordinatensystem einer bestimmten Seite um bestimmte Koordinaten mit der Methode PdfPageBase.Canvas.TraslateTransform() und drehen Sie das Koordinatensystem mit der Methode PdfPageBase.Canvas.RotateTransform() um 45 Grad gegen den Uhrzeigersinn. Dadurch wird sichergestellt, dass das Wasserzeichen in einem 45-Grad-Winkel in der Mitte der Seite erscheint.
  • Zeichnen Sie den Wasserzeichentext mit der Methode PdfPageBase.Canvas.DrawString() auf der Seite.
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer anderen PDF-Datei.
  • 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

C#/VB.NET: Add Text Watermarks to PDF

Fügen Sie mehrzeilige Textwasserzeichen zu PDF hinzu

Es kann vorkommen, dass Sie Ihrem Dokument mehr als eine Zeile Textwasserzeichen hinzufügen möchten. Um den gekachelten Wasserzeicheneffekt zu erzielen, können Sie die PdfTilingBrush-Klasse verwenden, die ein gekacheltes Muster erzeugt, das wiederholt wird, um einen Grafikbereich zu füllen. Im Folgenden finden Sie die wichtigsten Schritte zum Hinzufügen mehrzeiliger Wasserzeichen zu einem PDF-Dokument.

  • Erstellen Sie ein PdfDocument-Objekt und laden Sie ein Beispiel-PDF-Dokument mit der Methode PdfDocument.LoadFromFile().
  • Erstellen Sie eine benutzerdefinierte Methode InsertMultiLineTextWatermark(PdfPageBase page, String watermarkText, PdfTrueTypeFont font, int rowNum, int columnsNum), um mehrzeilige Textwasserzeichen zu einer PDF-Seite hinzuzufügen. Die Parameter rowNum und columnsNum geben die Zeilen- und Spaltennummer der gekachelten Wasserzeichen an.
  • Durchlaufen Sie alle Seiten im Dokument und rufen Sie die benutzerdefinierte Methode InsertMultiLineTextWatermark() auf, um Wasserzeichen auf jede Seite anzuwenden.
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer anderen Datei.
  • 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

C#/VB.NET: Add Text Watermarks to PDF

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.

Siehe auch

Instalado a través de NuGet

PM> Install-Package Spire.PDF

enlaces relacionados

Para evitar que su documento PDF se use de manera no autorizada, puede marcar el documento con texto o una imagen. En este artículo, aprenderá a programar agregue marcas de agua de texto (marcas de agua de una o varias líneas) 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 instalado a través de NuGet.

  • Package Manager
PM> Install-Package Spire.PDF 

Agregar una marca de agua de texto a PDF

Spire.PDF no proporciona una interfaz o una clase para manejar marcas de agua en archivos PDF. Sin embargo, puede dibujar texto como "confidencial", "uso interno" o "borrador" en cada página para imitar el efecto de marca de agua. Los siguientes son los pasos principales para agregar una marca de agua de texto a todas las páginas de un documento PDF.

  • Cree un objeto PdfDocument y cargue un documento PDF de muestra utilizando el método PdfDocument.LoadFromFile().
  • Cree un objeto PdfTrueTypeFont, especifique el texto de la marca de agua y mida el tamaño del texto con el método PdfFontBase.MeasureString().
  • Recorra todas las páginas del documento.
  • Traduzca el sistema de coordenadas de una página determinada según las coordenadas especificadas mediante el método PdfPageBase.Canvas.TraslateTransform() y gire el sistema de coordenadas 45 grados en sentido contrario a las agujas del reloj mediante el método PdfPageBase.Canvas.RotateTransform(). Esto asegura que la marca de agua aparecerá en el medio de la página en un ángulo de 45 grados.
  • Dibuje el texto de la marca de agua en la página usando el método PdfPageBase.Canvas.DrawString().
  • Guarde el documento en un archivo PDF diferente usando el 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

C#/VB.NET: Add Text Watermarks to PDF

Agregue marcas de agua de texto de varias líneas a PDF

En ocasiones, es posible que desee agregar más de una línea de marcas de agua de texto a su documento. Para lograr el efecto de marca de agua en mosaico, puede utilizar la clase PdfTilingBrush, que produce un patrón en mosaico que se repite para llenar un área de gráficos. Los siguientes son los pasos principales para agregar marcas de agua de varias líneas a un documento PDF.

  • Cree un objeto PdfDocument y cargue un documento PDF de muestra utilizando el método PdfDocument.LoadFromFile().
  • Cree un método personalizado InsertMultiLineTextWatermark(PdfPageBase page, String watermarkText, PdfTrueTypeFont font, int rowNum, int columnNum) para agregar marcas de agua de texto de varias líneas a una página PDF. Los parámetros rowNum y columnNum especifican el número de fila y columna de las marcas de agua en mosaico.
  • Recorra todas las páginas del documento y llame al método personalizado InsertMultiLineTextWatermark() para aplicar marcas de agua a cada página.
  • Guarde el documento en otro archivo usando el 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

C#/VB.NET: Add Text Watermarks to PDF

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.

Ver también

NuGet을 통해 설치됨

PM> Install-Package Spire.PDF

관련된 링크들

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에 텍스트 워터마크 추가

Spire.PDF는 PDF 파일의 워터마크를 처리하기 위한 인터페이스나 클래스를 제공하지 않습니다. 그러나 워터마크 효과를 모방하기 위해 각 페이지에 "기밀", "내부용" 또는 "초안"과 같은 텍스트를 그릴 수 있습니다. 다음은 PDF 문서의 모든 페이지에 텍스트 워터마크를 추가하는 주요 단계입니다.

  • PdfDocument 개체를 만들고 PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 문서를 로드합니다.
  • PdfTrueTypeFont 개체를 만들고 워터마크 텍스트를 지정하고 PdfFontBase.MeasureString() 메서드를 사용하여 텍스트 크기를 측정합니다.
  • 문서의 모든 페이지를 탐색합니다.
  • PdfPageBase.Canvas.TraslateTransform() 메서드를 사용하여 특정 페이지의 좌표계를 지정된 좌표로 변환하고 PdfPageBase.Canvas.RotateTransform() 메서드를 사용하여 좌표계를 시계 반대 방향으로 45도 회전합니다. 이렇게 하면 워터마크가 페이지 중앙에 45도 각도로 나타납니다.
  • PdfPageBase.Canvas.DrawString() 메서드를 사용하여 페이지에 워터마크 텍스트를 그립니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 PDF 파일로 저장합니다.
  • 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

C#/VB.NET: Add Text Watermarks to PDF

PDF에 여러 줄 텍스트 워터마크 추가

문서에 두 줄 이상의 텍스트 워터마크를 추가하려는 경우가 있습니다. 타일 워터마크 효과를 얻으려면 그래픽 영역을 채우기 위해 반복되는 타일 패턴을 생성하는 PdfTilingBrush 클래스를 사용할 수 있습니다. 다음은 PDF 문서에 여러 줄 워터마크를 추가하는 주요 단계입니다.

  • PdfDocument 개체를 만들고 PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 문서를 로드합니다.
  • 사용자 지정 메서드 InsertMultiLineTextWatermark(PdfPageBase page, String watermarkText, PdfTrueTypeFont font, int rowNum, int columnNum)를 만들어 여러 줄 텍스트 워터마크를 PDF 페이지에 추가합니다. 매개변수 rowNumcolumnNum은 타일 워터마크의 행 및 열 번호를 지정합니다.
  • 문서의 모든 페이지를 탐색하고 사용자 지정 메서드 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

C#/VB.NET: Add Text Watermarks to PDF

임시 면허 신청

생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.

또한보십시오

Installato tramite NuGet

PM> Install-Package Spire.PDF

Link correlati

Per evitare che il tuo documento PDF venga utilizzato in modo non autorizzato, puoi filigranare il documento con testo o un'immagine. In questo articolo imparerai a programmaticamente aggiungere filigrane di testo (filigrane a riga singola e multilinea) a 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 di testo al PDF

Spire.PDF non fornisce un'interfaccia o una classe per gestire le filigrane nei file PDF. Potresti, tuttavia, disegnare testo come "riservato", "uso interno" o "bozza" su ogni pagina per imitare l'effetto filigrana. Di seguito sono riportati i passaggi principali per aggiungere una filigrana di testo a tutte le pagine di un documento PDF.

  • Creare un oggetto PdfDocument e caricare un documento PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
  • Creare un oggetto PdfTrueTypeFont, specificare il testo della filigrana e misurare la dimensione del testo utilizzando il metodo PdfFontBase.MeasureString().
  • Attraversa tutte le pagine del documento.
  • Traduci il sistema di coordinate di una determinata pagina in base alle coordinate specificate utilizzando il metodo PdfPageBase.Canvas.TraslateTransform() e ruota il sistema di coordinate di 45 gradi in senso antiorario utilizzando il metodo PdfPageBase.Canvas.RotateTransform(). Ciò garantisce che la filigrana appaia al centro della pagina con un angolo di 45 gradi.
  • Disegna il testo della filigrana sulla pagina utilizzando il metodo PdfPageBase.Canvas.DrawString().
  • Salvare il documento in un file PDF diverso utilizzando il metodo 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

C#/VB.NET: Add Text Watermarks to PDF

Aggiungi filigrane di testo multilinea al PDF

Ci sono momenti in cui potresti voler aggiungere più di una riga di filigrane di testo al tuo documento. Per ottenere l'effetto filigrana piastrellato, è possibile utilizzare la classe PdfTilingBrush, che produce un motivo piastrellato che viene ripetuto per riempire un'area grafica. Di seguito sono riportati i passaggi principali per aggiungere filigrane multilinea a un documento PDF.

  • Creare un oggetto PdfDocument e caricare un documento PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
  • Creare un metodo personalizzato InsertMultiLineTextWatermark(PdfPageBase page, String watermarkText, PdfTrueTypeFont font, int rowNum, int columnNum) per aggiungere filigrane di testo su più righe a una pagina PDF. I parametri rowNum e columnNum specificano il numero di riga e di colonna delle filigrane affiancate.
  • Attraversa tutte le pagine del documento e chiama il metodo personalizzato InsertMultiLineTextWatermark() per applicare filigrane a ogni pagina.
  • Salvare il documento in un altro file utilizzando il metodo 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

C#/VB.NET: Add Text Watermarks to PDF

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.

Guarda anche

Installé via NuGet

PM> Install-Package Spire.PDF

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

C#/VB.NET: Add Text Watermarks to PDF

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

C#/VB.NET: Add Text Watermarks to 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 de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Thursday, 24 August 2023 08:34

C#/VB.NET: Extrair tabelas de PDF

Instalado via NuGet

PM> Install-Package Spire.PDF

Links Relacionados

O PDF é um dos formatos de documento mais populares para compartilhar e gravar dados. Você pode encontrar a situação em que precisa extrair dados de documentos PDF, especialmente os dados em tabelas. Por exemplo, há informações úteis armazenadas nas tabelas de suas faturas em PDF e você deseja extrair os dados para análise ou cálculo posterior. Este artigo demonstra como extrair dados de tabelas PDF e salve-o em um arquivo TXT 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 

Extrair dados de tabelas PDF

A seguir estão as principais etapas para extrair tabelas de um documento PDF.

  • Crie uma instância da classe PdfDocument.
  • Carregue o documento PDF de amostra usando o método PdfDocument.LoadFromFile().
  • Extraia tabelas de uma página específica usando o método PdfTableExtractor.ExtractTable(int pageIndex).
  • Obtenha o texto de uma determinada célula da tabela usando o método PdfTable.GetText(int rowIndex, int columnIndex).
  • Salve os dados extraídos em um arquivo .txt.
  • C#
  • VB.NET
using System.IO;
    using System.Text;
    using Spire.Pdf;
    using Spire.Pdf.Utilities;
    
    namespace ExtractPdfTable
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load the sample PDF file
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\table.pdf");
    
                //Create a StringBuilder object
                StringBuilder builder = new StringBuilder();
    
                //Initialize an instance of PdfTableExtractor class
                PdfTableExtractor extractor = new PdfTableExtractor(doc);
    
                //Declare a PdfTable array
                PdfTable[] tableList = null;
    
                //Loop through the pages
                for (int pageIndex = 0; pageIndex < doc.Pages.Count; pageIndex++)
                {
                    //Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex);
    
                    //Determine if the table list is null
                    if (tableList != null && tableList.Length > 0)
                    {
                        //Loop through the table in the list
                        foreach (PdfTable table in tableList)
                        {
                            //Get row number and column number of a certain table
                            int row = table.GetRowCount();
                            int column = table.GetColumnCount();
    
                            //Loop though the row and colunm
                            for (int i = 0; i < row; i++)
                            {
                                for (int j = 0; j < column; j++)
                                {
                                    //Get text from the specific cell
                                    string text = table.GetText(i, j);
    
                                    //Add text to the string builder
                                    builder.Append(text + " ");
                                }
                                builder.Append("\r\n");
                            }
                        }
                    }
                }
    
                //Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString());
            }
        }
    }
Imports System.IO
    Imports System.Text
    Imports Spire.Pdf
    Imports Spire.Pdf.Utilities
    
    Namespace ExtractPdfTable
        Class Program
            Shared  Sub Main(ByVal args() As String)
                'Create a PdfDocument object
                Dim doc As PdfDocument =  New PdfDocument()
    
                'Load the sample PDF file
                doc.LoadFromFile("C:\Users\Administrator\Desktop\table.pdf")
    
                'Create a StringBuilder object
                Dim builder As StringBuilder =  New StringBuilder()
    
                'Initialize an instance of PdfTableExtractor class
                Dim extractor As PdfTableExtractor =  New PdfTableExtractor(doc)
    
                'Declare a PdfTable array
                Dim tableList() As PdfTable =  Nothing
    
                'Loop through the pages
                Dim pageIndex As Integer
                For  pageIndex = 0 To  doc.Pages.Count- 1  Step  pageIndex + 1
                    'Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex)
    
                    'Determine if the table list is null
                    If tableList <> Nothing And tableList.Length > 0 Then
                        'Loop through the table in the list
                        Dim table As PdfTable
                        For Each table In tableList
                            'Get row number and column number of a certain table
                            Dim row As Integer =  table.GetRowCount()
                            Dim column As Integer =  table.GetColumnCount()
    
                            'Loop though the row and colunm
                            Dim i As Integer
                            For  i = 0 To  row- 1  Step  i + 1
                                Dim j As Integer
                                For  j = 0 To  column- 1  Step  j + 1
                                    'Get text from the specific cell
                                    Dim text As String =  table.GetText(i,j)
    
                                    'Add text to the string builder
                                    builder.Append(text + " ")
                                Next
                                builder.Append("\r\n")
                            Next
                        Next
                    End If
                Next
    
                'Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString())
            End Sub
        End Class
    End Namespace

C#/VB.NET: Extract Tables from PDF

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.

Veja também

Установлено через NuGet

PM> Install-Package Spire.PDF 

Ссылки по теме

PDF — один из самых популярных форматов документов для обмена и записи данных. Вы можете столкнуться с ситуацией, когда вам необходимо извлечь данные из PDF-документов, особенно данные в таблицах. Например, в таблицах ваших счетов в формате PDF хранится полезная информация, и вы хотите извлечь данные для дальнейшего анализа или расчета. В этой статье показано, как извлекать данные из таблиц PDF и сохраните его в файле TXT с помощью 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().
  • Извлеките таблицы с определенной страницы с помощью метода PdfTableExtractor.ExtractTable(int pageIndex).
  • Получите текст определенной ячейки таблицы, используя метод PdfTable.GetText(int rowIndex, int columnsIndex).
  • Сохраните извлеченные данные в файле .txt.
  • C#
  • VB.NET
using System.IO;
    using System.Text;
    using Spire.Pdf;
    using Spire.Pdf.Utilities;
    
    namespace ExtractPdfTable
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load the sample PDF file
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\table.pdf");
    
                //Create a StringBuilder object
                StringBuilder builder = new StringBuilder();
    
                //Initialize an instance of PdfTableExtractor class
                PdfTableExtractor extractor = new PdfTableExtractor(doc);
    
                //Declare a PdfTable array
                PdfTable[] tableList = null;
    
                //Loop through the pages
                for (int pageIndex = 0; pageIndex < doc.Pages.Count; pageIndex++)
                {
                    //Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex);
    
                    //Determine if the table list is null
                    if (tableList != null && tableList.Length > 0)
                    {
                        //Loop through the table in the list
                        foreach (PdfTable table in tableList)
                        {
                            //Get row number and column number of a certain table
                            int row = table.GetRowCount();
                            int column = table.GetColumnCount();
    
                            //Loop though the row and colunm
                            for (int i = 0; i < row; i++)
                            {
                                for (int j = 0; j < column; j++)
                                {
                                    //Get text from the specific cell
                                    string text = table.GetText(i, j);
    
                                    //Add text to the string builder
                                    builder.Append(text + " ");
                                }
                                builder.Append("\r\n");
                            }
                        }
                    }
                }
    
                //Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString());
            }
        }
    }
Imports System.IO
    Imports System.Text
    Imports Spire.Pdf
    Imports Spire.Pdf.Utilities
    
    Namespace ExtractPdfTable
        Class Program
            Shared  Sub Main(ByVal args() As String)
                'Create a PdfDocument object
                Dim doc As PdfDocument =  New PdfDocument()
    
                'Load the sample PDF file
                doc.LoadFromFile("C:\Users\Administrator\Desktop\table.pdf")
    
                'Create a StringBuilder object
                Dim builder As StringBuilder =  New StringBuilder()
    
                'Initialize an instance of PdfTableExtractor class
                Dim extractor As PdfTableExtractor =  New PdfTableExtractor(doc)
    
                'Declare a PdfTable array
                Dim tableList() As PdfTable =  Nothing
    
                'Loop through the pages
                Dim pageIndex As Integer
                For  pageIndex = 0 To  doc.Pages.Count- 1  Step  pageIndex + 1
                    'Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex)
    
                    'Determine if the table list is null
                    If tableList <> Nothing And tableList.Length > 0 Then
                        'Loop through the table in the list
                        Dim table As PdfTable
                        For Each table In tableList
                            'Get row number and column number of a certain table
                            Dim row As Integer =  table.GetRowCount()
                            Dim column As Integer =  table.GetColumnCount()
    
                            'Loop though the row and colunm
                            Dim i As Integer
                            For  i = 0 To  row- 1  Step  i + 1
                                Dim j As Integer
                                For  j = 0 To  column- 1  Step  j + 1
                                    'Get text from the specific cell
                                    Dim text As String =  table.GetText(i,j)
    
                                    'Add text to the string builder
                                    builder.Append(text + " ")
                                Next
                                builder.Append("\r\n")
                            Next
                        Next
                    End If
                Next
    
                'Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString())
            End Sub
        End Class
    End Namespace

C#/VB.NET: Extract Tables from PDF

Подать заявку на временную лицензию

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

Смотрите также

Thursday, 24 August 2023 08:31

C#/VB.NET: Tabellen aus PDF extrahieren

Über NuGet installiert

PM> Install-Package Spire.PDF 

verwandte Links

PDF ist eines der beliebtesten Dokumentformate zum Teilen und Schreiben von Daten. Es kann vorkommen, dass Sie Daten aus PDF-Dokumenten extrahieren müssen, insbesondere Daten in Tabellen. Beispielsweise sind in den Tabellen Ihrer PDF-Rechnungen nützliche Informationen gespeichert und Sie möchten die Daten zur weiteren Analyse oder Berechnung extrahieren. Dieser Artikel zeigt, wie es geht Extrahieren Sie Daten aus PDF-Tabellen und speichern Sie es in einer TXT-Datei, indem Sie Spire.PDF for .NETverwenden.

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 

Extrahieren Sie Daten aus PDF-Tabellen

Im Folgenden sind die wichtigsten Schritte zum Extrahieren von Tabellen aus einem PDF-Dokument aufgeführt.

  • Erstellen Sie eine Instanz der PdfDocument-Klasse.
  • Laden Sie das Beispiel-PDF-Dokument mit der Methode PdfDocument.LoadFromFile().
  • Extrahieren Sie Tabellen aus einer bestimmten Seite mit der Methode PdfTableExtractor.ExtractTable(int pageIndex).
  • Rufen Sie den Text einer bestimmten Tabellenzelle mit der Methode PdfTable.GetText(int rowIndex, int columnsIndex) ab.
  • Speichern Sie die extrahierten Daten in einer TXT-Datei.
  • C#
  • VB.NET
using System.IO;
    using System.Text;
    using Spire.Pdf;
    using Spire.Pdf.Utilities;
    
    namespace ExtractPdfTable
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load the sample PDF file
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\table.pdf");
    
                //Create a StringBuilder object
                StringBuilder builder = new StringBuilder();
    
                //Initialize an instance of PdfTableExtractor class
                PdfTableExtractor extractor = new PdfTableExtractor(doc);
    
                //Declare a PdfTable array
                PdfTable[] tableList = null;
    
                //Loop through the pages
                for (int pageIndex = 0; pageIndex < doc.Pages.Count; pageIndex++)
                {
                    //Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex);
    
                    //Determine if the table list is null
                    if (tableList != null && tableList.Length > 0)
                    {
                        //Loop through the table in the list
                        foreach (PdfTable table in tableList)
                        {
                            //Get row number and column number of a certain table
                            int row = table.GetRowCount();
                            int column = table.GetColumnCount();
    
                            //Loop though the row and colunm
                            for (int i = 0; i < row; i++)
                            {
                                for (int j = 0; j < column; j++)
                                {
                                    //Get text from the specific cell
                                    string text = table.GetText(i, j);
    
                                    //Add text to the string builder
                                    builder.Append(text + " ");
                                }
                                builder.Append("\r\n");
                            }
                        }
                    }
                }
    
                //Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString());
            }
        }
    }
Imports System.IO
    Imports System.Text
    Imports Spire.Pdf
    Imports Spire.Pdf.Utilities
    
    Namespace ExtractPdfTable
        Class Program
            Shared  Sub Main(ByVal args() As String)
                'Create a PdfDocument object
                Dim doc As PdfDocument =  New PdfDocument()
    
                'Load the sample PDF file
                doc.LoadFromFile("C:\Users\Administrator\Desktop\table.pdf")
    
                'Create a StringBuilder object
                Dim builder As StringBuilder =  New StringBuilder()
    
                'Initialize an instance of PdfTableExtractor class
                Dim extractor As PdfTableExtractor =  New PdfTableExtractor(doc)
    
                'Declare a PdfTable array
                Dim tableList() As PdfTable =  Nothing
    
                'Loop through the pages
                Dim pageIndex As Integer
                For  pageIndex = 0 To  doc.Pages.Count- 1  Step  pageIndex + 1
                    'Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex)
    
                    'Determine if the table list is null
                    If tableList <> Nothing And tableList.Length > 0 Then
                        'Loop through the table in the list
                        Dim table As PdfTable
                        For Each table In tableList
                            'Get row number and column number of a certain table
                            Dim row As Integer =  table.GetRowCount()
                            Dim column As Integer =  table.GetColumnCount()
    
                            'Loop though the row and colunm
                            Dim i As Integer
                            For  i = 0 To  row- 1  Step  i + 1
                                Dim j As Integer
                                For  j = 0 To  column- 1  Step  j + 1
                                    'Get text from the specific cell
                                    Dim text As String =  table.GetText(i,j)
    
                                    'Add text to the string builder
                                    builder.Append(text + " ")
                                Next
                                builder.Append("\r\n")
                            Next
                        Next
                    End If
                Next
    
                'Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString())
            End Sub
        End Class
    End Namespace

C#/VB.NET: Extract Tables from PDF

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.

Siehe auch

Thursday, 24 August 2023 08:29

C#/VB.NET: extraer tablas de PDF

Instalado a través de NuGet

PM> Install-Package Spire.PDF

enlaces relacionados

PDF es uno de los formatos de documentos más populares para compartir y escribir datos. Puede encontrarse con la situación en la que necesita extraer datos de documentos PDF, especialmente los datos en tablas. Por ejemplo, hay información útil almacenada en las tablas de sus facturas en PDF y desea extraer los datos para su posterior análisis o cálculo. Este artículo demuestra cómo extraer datos de tablas PDF y guárdelo en un archivo TXT utilizando 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 

Extraer datos de tablas PDF

Los siguientes son los pasos principales para extraer tablas de un documento PDF.

  • Cree una instancia de la clase PdfDocument.
  • Cargue el documento PDF de muestra utilizando el método PdfDocument.LoadFromFile().
  • Extraiga tablas de una página específica utilizando el método PdfTableExtractor.ExtractTable(int pageIndex).
  • Obtenga el texto de una determinada celda de tabla usando el método PdfTable.GetText(int rowIndex, int columnIndex).
  • Guarde los datos extraídos en un archivo .txt.
  • C#
  • VB.NET
using System.IO;
    using System.Text;
    using Spire.Pdf;
    using Spire.Pdf.Utilities;
    
    namespace ExtractPdfTable
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load the sample PDF file
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\table.pdf");
    
                //Create a StringBuilder object
                StringBuilder builder = new StringBuilder();
    
                //Initialize an instance of PdfTableExtractor class
                PdfTableExtractor extractor = new PdfTableExtractor(doc);
    
                //Declare a PdfTable array
                PdfTable[] tableList = null;
    
                //Loop through the pages
                for (int pageIndex = 0; pageIndex < doc.Pages.Count; pageIndex++)
                {
                    //Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex);
    
                    //Determine if the table list is null
                    if (tableList != null && tableList.Length > 0)
                    {
                        //Loop through the table in the list
                        foreach (PdfTable table in tableList)
                        {
                            //Get row number and column number of a certain table
                            int row = table.GetRowCount();
                            int column = table.GetColumnCount();
    
                            //Loop though the row and colunm
                            for (int i = 0; i < row; i++)
                            {
                                for (int j = 0; j < column; j++)
                                {
                                    //Get text from the specific cell
                                    string text = table.GetText(i, j);
    
                                    //Add text to the string builder
                                    builder.Append(text + " ");
                                }
                                builder.Append("\r\n");
                            }
                        }
                    }
                }
    
                //Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString());
            }
        }
    }
Imports System.IO
    Imports System.Text
    Imports Spire.Pdf
    Imports Spire.Pdf.Utilities
    
    Namespace ExtractPdfTable
        Class Program
            Shared  Sub Main(ByVal args() As String)
                'Create a PdfDocument object
                Dim doc As PdfDocument =  New PdfDocument()
    
                'Load the sample PDF file
                doc.LoadFromFile("C:\Users\Administrator\Desktop\table.pdf")
    
                'Create a StringBuilder object
                Dim builder As StringBuilder =  New StringBuilder()
    
                'Initialize an instance of PdfTableExtractor class
                Dim extractor As PdfTableExtractor =  New PdfTableExtractor(doc)
    
                'Declare a PdfTable array
                Dim tableList() As PdfTable =  Nothing
    
                'Loop through the pages
                Dim pageIndex As Integer
                For  pageIndex = 0 To  doc.Pages.Count- 1  Step  pageIndex + 1
                    'Extract tables from a specific page
                    tableList = extractor.ExtractTable(pageIndex)
    
                    'Determine if the table list is null
                    If tableList <> Nothing And tableList.Length > 0 Then
                        'Loop through the table in the list
                        Dim table As PdfTable
                        For Each table In tableList
                            'Get row number and column number of a certain table
                            Dim row As Integer =  table.GetRowCount()
                            Dim column As Integer =  table.GetColumnCount()
    
                            'Loop though the row and colunm
                            Dim i As Integer
                            For  i = 0 To  row- 1  Step  i + 1
                                Dim j As Integer
                                For  j = 0 To  column- 1  Step  j + 1
                                    'Get text from the specific cell
                                    Dim text As String =  table.GetText(i,j)
    
                                    'Add text to the string builder
                                    builder.Append(text + " ")
                                Next
                                builder.Append("\r\n")
                            Next
                        Next
                    End If
                Next
    
                'Write to a .txt file
                File.WriteAllText("Table.txt", builder.ToString())
            End Sub
        End Class
    End Namespace

C#/VB.NET: Extract Tables from PDF

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.

Ver también