C#: Compare PDF Documents
PDF has become the standard format for sharing and preserving documents across different platforms, playing a ubiquitous role in both professional and personal settings. However, creating high-quality PDF documents requires multiple checks and revisions. In this context, knowing how to efficiently compare PDF files and pinpoint their differences becomes crucial, which enables document editors to quickly identify discrepancies between different versions of a document, resulting in significant time savings during the document creation and review process. This article aims to demonstrate how to compare PDF documents effortlessly using Spire.PDF for .NET in C# programs.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Compare Two PDF Documents in C#
With Spire.PDF for .NET, developers can create an instance of the PdfComparer class, passing two PdfDocument objects as parameters, and then utilize the PdfComparer.Compare(String fileName) method to compare the two documents. The resulting comparison is saved as a new PDF document, allowing for further analysis or review of the differences between the two PDFs.
The resulting PDF document displays the two original documents on the left and the right, with the deleted items in red and the added items in yellow.
The following are the detailed steps for comparing two PDF documents:
- Create two objects of PdfDocument class and load two PDF documents using PdfDocument.LoadFromFile() method.
- Create an instance of PdfComparer class and pass the two PdfDocument objects as parameters.
- Compare the two documents and save the result as another PDF document using PdfComparer.Compare() method.
- C#
using Spire.Pdf; using Spire.Pdf.Comparison; namespace ExtractTablesToExcel { class Program { static void Main(string[] args) { //Create an object of PdfDocument class and load a PDF document PdfDocument pdf1 = new PdfDocument(); pdf1.LoadFromFile("Sample1.pdf"); //Create another object of PdfDocument class and load another PDF document PdfDocument pdf2 = new PdfDocument(); pdf2.LoadFromFile("Sample2.pdf"); //Create an object of PdfComparer class with the two document PdfComparer comparer = new PdfComparer(pdf1, pdf2); //Compare the two document and save the comparing result to another PDF document comparer.Compare("output/ComparingResult.pdf"); pdf1.Close(); pdf2.Close(); } } }
Compare a Specific Page Range of Two PDF Documents
After creating an instance of PdfComparer class, developers can also use the PdfComparer.Options.SetPageRange() method to set the page range to be compared. This allows for comparing only the specified page range in two PDF documents. The detailed steps are as follows:
- Create two objects of PdfDocument class and load two PDF documents using PdfDocument.LoadFromFile() method.
- Create an instance of PdfComparer class and pass the two PdfDocument objects as parameters.
- Set the page range to be compared using PdfComparer.Options.SetPageRange() method.
- Compare the specified page range in the two PDF documents and save the result as another PDF document using PdfComparer.Compare() method.
- C#
using Spire.Pdf; using Spire.Pdf.Comparison; namespace ExtractTablesToExcel { class Program { static void Main(string[] args) { //Create an object of PdfDocument class and load a PDF document PdfDocument pdf1 = new PdfDocument(); pdf1.LoadFromFile("Sample1.pdf"); //Create another object of PdfDocument class and load another PDF document PdfDocument pdf2 = new PdfDocument(); pdf2.LoadFromFile("Sample2.pdf"); //Create an object of PdfComparer class with the two document PdfComparer comparer = new PdfComparer(pdf1, pdf2); //Set the page range to be compared comparer.Options.SetPageRanges(1, 1, 1, 1); //Compare the specified page range and save the comparing result to another PDF document comparer.Compare("output/PageRangeComparingResult.pdf"); pdf1.Close(); pdf2.Close(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#/VB.NET: Create a PDF Document
Creating PDF documents from code offers a wide range of benefits. For example, you can easily incorporate dynamic content such as user input, database records, or real-time data. Code-based PDF generation allows for greater customization and automation, minimizing manual intervention in creating highly tailored documents. In this article, you will learn how to create a PDF document from scratch in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Background Knowledge
A page in Spire.PDF (represented by PdfPageBase) consists of client area and margins all around. The content area is for users to write various contents, and the margins are usually blank edges.
As shown in the figure below, the origin of the coordinate system on the page is located at the top left corner of the client area, with the x-axis extending horizontally to the right and the y-axis extending vertically down. All elements added to the client area must be based on the specified coordinates.
In addition, the following table lists the important classes and methods, which can help you easily understand the code snippet provided in the following section.
Member | Description |
PdfDocument class | Represents a PDF document model. |
PdfPageBase class | Represents a page in a PDF document. |
PdfSolidBrush class | Represents a brush that fills any object with a solid color. |
PdfTrueTypeFont class | Represents a true type font. |
PdfStringFormat class | Represents text format information, such as alignment, characters spacing and indent. |
PdfTextWidget class | Represents the text area with the ability to span several pages. |
PdfTextLayout class | Represents the text layout information. |
PdfDocument.Pages.Add() method | Adds a page to a PDF document. |
PdfPageBase.Canvas.DrawString() method | Draws string on a page at the specified location with specified font and brush objects. |
PdfTextWidget.Draw() method | Draws the text widget on a page at the specified location. |
PdfDocument.Save() method | Saves the document to a PDF file. |
Create a PDF Document from Scratch in C# and VB.NET
Although Spire.PDF for .NET supports adding various kinds of elements to PDF documents, this article only demonstrates how to create a PDF document with plain text. The following are the detailed steps.
- Create a PdfDocument object.
- Add a page using PdfDocument.Pages.Add() method.
- Create brush and font objects.
- Draw string on the page at a specified coordinate using PdfPageBase.Canvas.DrawString() method.
- Create a PdfTextWidget object to hold a chunk of text.
- Draw the text widget on the page at a specified location using PdfTextWidget.Draw() method
- Save the document to a PDF file using PdfDocument.Save() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace CreatePdfDocument { class Program { static void Main(string[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Add a page PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(35f)); //Specify heading text String titleText = "What is MySQL"; //Create solid brushes PdfSolidBrush titleBrush = new PdfSolidBrush(new PdfRGBColor(Color.Blue)); PdfSolidBrush paraBrush = new PdfSolidBrush(new PdfRGBColor(Color.Black)); //Create true type fonts PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Times New Roman", 18f, FontStyle.Bold),true); PdfTrueTypeFont paraFont = new PdfTrueTypeFont(new Font("Times New Roman", 12f, FontStyle.Regular), true); //Set the text alignment via PdfStringFormat class PdfStringFormat format = new PdfStringFormat(); format.Alignment = PdfTextAlignment.Center; //Draw heading on the center of the page page.Canvas.DrawString(titleText, titleFont, titleBrush, page.Canvas.ClientSize.Width / 2, 20, format); //Get paragraph content from a .txt file string paraText = File.ReadAllText("C:\\Users\\Administrator\\Desktop\\content.txt"); //Create a PdfTextWidget object to hold the paragrah content PdfTextWidget widget = new PdfTextWidget(paraText, paraFont, paraBrush); //Create a rectangle where the paragraph content will be placed RectangleF rect = new RectangleF(0, 50, page.Canvas.ClientSize.Width, page.Canvas.ClientSize.Height); //Set the PdfLayoutType to Paginate to make the content paginated automatically PdfTextLayout layout = new PdfTextLayout(); layout.Layout = PdfLayoutType.Paginate; //Draw the widget on the page widget.Draw(page, rect, layout); //Save to file doc.SaveToFile("CreatePdfDocument.pdf"); doc.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#/VB.NET: Create a Tagged PDF Document
A tagged PDF (also known as PDF/UA) is a type of PDF that includes an underlying tag tree, similar to HTML, that defines the structure of the document. These tags can help screen readers to navigate throughout the document without any loss of information. This article introduces how to create a tagged PDF from scratch in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Create a Tagged PDF with Rich Elements
To add structure elements in a tagged PDF document, we must first create an object of PdfTaggedContent class. Then, add an element to the root using PdfTaggedContent.StructureTreeRoot.AppendChildElement() method. The following are the detailed steps to add a "heading" element to a tagged PDF using Spire.PDF for .NET.
- Create a PdfDocument object and add a page to it using PdfDocument.Pages.Add() method.
- Create an object of PdfTaggedContent class.
- Make the document compliance to PDF/UA identification using PdfTaggedContent.SetPdfUA1Identification() method.
- Add a "document" element to the root of the document using PdfTaggedContent.StructureTreeRoot.AppendChildElement() method.
- Add a "heading" element under the "document" element using PdfStructureElement.AppendChildElement() method.
- Add a start tag using PdfStructureElement.BeginMarkedContent() method, which indicates the beginning of the heading element.
- Draw heading text on the page using PdfPageBase.Canvas.DrawString() method.
- Add an end tag using PdfStructureElement.BeginMarkedContent() method, which implies the heading element ends here.
- Save the document to a PDF file using PdfDocument.SaveToFile() method.
The following code snippet provides an example on how to create various elements including document, heading, paragraph, figure and table in a tagged PDF document in C# and VB.NET.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Interchange.TaggedPdf; using Spire.Pdf.Tables; using System.Data; using System.Drawing; namespace CreatePDFUA { class Program { static void Main(string[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Add a page PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(20)); //Set tab order page.SetTabOrder(TabOrder.Structure); //Create an object of PdfTaggedContent class PdfTaggedContent taggedContent = new PdfTaggedContent(doc); //Set language and title for the document taggedContent.SetLanguage("en-US"); taggedContent.SetTitle("test"); //Set PDF/UA1 identification taggedContent.SetPdfUA1Identification(); //Create font and brush PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 14), true); PdfSolidBrush brush = new PdfSolidBrush(Color.Black); //Add a "document" element PdfStructureElement document = taggedContent.StructureTreeRoot.AppendChildElement(PdfStandardStructTypes.Document); //Add a "heading" element PdfStructureElement heading1 = document.AppendChildElement(PdfStandardStructTypes.HeadingLevel1); heading1.BeginMarkedContent(page); string headingText = "What Is a Tagged PDF?"; page.Canvas.DrawString(headingText, font, brush, new PointF(0, 0)); heading1.EndMarkedContent(page); //Add a "paragraph" element PdfStructureElement paragraph = document.AppendChildElement(PdfStandardStructTypes.Paragraph); paragraph.BeginMarkedContent(page); string paragraphText = "“Tagged PDF” doesn’t seem like a life-changing term. But for some, it is. For people who are " + "blind or have low vision and use assistive technology (such as screen readers and connected Braille displays) to " + "access information, an untagged PDF means they are missing out on information contained in the document because assistive " + "technology cannot “read” untagged PDFs. Digital accessibility has opened up so many avenues to information that were once " + "closed to people with visual disabilities, but PDFs often get left out of the equation."; RectangleF rect = new RectangleF(0, 30, page.Canvas.ClientSize.Width, page.Canvas.ClientSize.Height); page.Canvas.DrawString(paragraphText, font, brush, rect); paragraph.EndMarkedContent(page); //Add a "figure" element to PdfStructureElement figure = document.AppendChildElement(PdfStandardStructTypes.Figure); figure.BeginMarkedContent(page); PdfImage image = PdfImage.FromFile(@"C:\Users\Administrator\Desktop\pdfua.png"); page.Canvas.DrawImage(image, new PointF(0, 150)); figure.EndMarkedContent(page); //Add a "table" element PdfStructureElement table = document.AppendChildElement(PdfStandardStructTypes.Table); table.BeginMarkedContent(page); PdfTable pdfTable = new PdfTable(); pdfTable.Style.DefaultStyle.Font = font; DataTable dataTable = new DataTable(); dataTable.Columns.Add("Name"); dataTable.Columns.Add("Age"); dataTable.Columns.Add("Sex"); dataTable.Rows.Add(new string[] { "John", "22", "Male" }); dataTable.Rows.Add(new string[] { "Katty", "25", "Female" }); pdfTable.DataSource = dataTable; pdfTable.Style.ShowHeader = true; pdfTable.Draw(page.Canvas, new PointF(0, 280), 300f); table.EndMarkedContent(page); //Save the document to file doc.SaveToFile("CreatePDFUA.pdf"); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Download PDF Document from URL in C#/VB.NET
This article shows you how to download a PDF document from an URL using Spire.PDF with C# and VB.NET.
using System.IO; using System.Net; using Spire.Pdf; namespace DownloadPdfFromUrl { class Program { static void Main(string[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Create a WebClient object WebClient webClient = new WebClient(); //Download data from URL and save as memory stream using (MemoryStream ms = new MemoryStream(webClient.DownloadData("https://www.e-iceblue.com/article/toDownload.pdf"))) { //Load the stream doc.LoadFromStream(ms); } //Save to PDF file doc.SaveToFile("result.pdf", FileFormat.PDF); } } }
Imports System.IO Imports System.Net Imports Spire.Pdf Namespace DownloadPdfFromUrl Class Program Shared Sub Main(ByVal args() As String) 'Create a PdfDocument object Dim doc As PdfDocument = New PdfDocument() 'Create a WebClient object Dim webClient As WebClient = New WebClient() 'Download data from URL and save as memory stream Imports(MemoryStream ms = New MemoryStream(webClient.DownloadData("https:'www.e-iceblue.com/article/toDownload.pdf"))) { 'Load the stream doc.LoadFromStream(ms) } 'Save to PDF file doc.SaveToFile("result.pdf", FileFormat.PDF) End Sub End Class End Namespace
C#/VB.NET: Create a PDF Portfolio
A PDF portfolio is a collection of files that can contain text documents, spreadsheets, emails, images, PowerPoint presentations and drawings. Although a PDF portfolio assembles different types of files into a single unit, each of the files in it retains their original formatting, resolutions and sizes. In this article, you will learn how to programmatically create a PDF portfolio using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Create a PDF Portfolio and Add Files to It
As a PDF portfolio is a collection of files, Spire.PDF for .NET allows you to create it easily using PdfDocument.Collection property. Then you can add files to the PDF portfolio using PdfCollection.AddFile() method. The detailed steps are as follows:
- Specify the files that need to be added to the PDF portfolio.
- Create PdfDocument instance.
- Create a PDF portfolio and add files to it using PdfDocument.Collection.AddFile() method.
- Save the result file using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using System; using Spire.Pdf; namespace CreatePDFPortfolio { class Program { static void Main(string[] args) { // Specify the files String[] files = new String[] { "input.pdf", "sample.docx", "report.xlsx", "Intro.pptx", "logo.png" }; //Create a PdfDocument instance using (PdfDocument pdf = new PdfDocument()) { //Create a PDF portfolio and add files to it for (int i = 0; i < files.Length; i++) { pdf.Collection.AddFile(files[i]); } //Save the result file pdf.SaveToFile("PortfolioWithFiles.pdf", FileFormat.PDF); pdf.Dispose(); } } } }
Create a PDF Portfolio and Add Folders to It
After creating a PDF portfolio, Spire.PDF for .NET also allows you to create folders within the PDF portfolio to further manage the files. The detailed steps are as follows:
- Specify the files that need to be added to the PDF portfolio.
- Create PdfDocument instance.
- Create a PDF Portfolio using PdfDocument.Collection property.
- Add folders to the PDF portfolio using PdfCollection.Folders.CreateSubfolder() method, and then add files to the folders using PdfFolder.AddFile() method.
- Save the result file using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using System; using Spire.Pdf; using Spire.Pdf.Collections; namespace CreatePDFPortfolio { class Program { static void Main(string[] args) { // Specify the files String[] files = new String[] { "input.pdf", "sample.docx", "report.xlsx", "Intro.pptx", "logo.png" }; //Create a PdfDocument instance using (PdfDocument pdf = new PdfDocument()) { //Create a PDF portfolio and add folders to it for (int i = 0; i < files.Length; i++) { PdfFolder folder = pdf.Collection.Folders.CreateSubfolder("Folder" + i); //Add files to the folders folder.AddFile(files[i]); } //Save the result file pdf.SaveToFile("PortfolioWithFolders.pdf", FileFormat.PDF); pdf.Dispose(); } } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Detect if a PDF file is PDF/A in C#
Spire.PDF provides developers two methods to detect if a PDF file is PDF/A. The one is to use PdfDocument.Conformance property, the other is to use PdfDocument.XmpMetaData property. The following examples demonstrate how we can detect if a PDF file is PDF/A using these two methods.
Below is the screenshot of the sample file we used for demonstration:
Using PdfDocument.Conformance
using Spire.Pdf; using System; namespace Detect { class Program { static void Main(string[] args) { //Initialize a PdfDocument object PdfDocument pdf = new PdfDocument(); //Load the PDF file pdf.LoadFromFile("Example.pdf"); //Get the conformance level of the PDF file PdfConformanceLevel conformance = pdf.Conformance; Console.WriteLine("This PDF file is " + conformance.ToString()); } } }
Output:
Using PdfDocument.XmpMetaData
using Spire.Pdf; using Spire.Pdf.Xmp; using System; using System.Xml; namespace Detect { class Program { static void Main(string[] args) { //Initialize a PdfDocument object PdfDocument pdf = new PdfDocument(); //Load the PDF file pdf.LoadFromFile("Example.pdf"); //Get the XMP MetaData of the file XmpMetadata xmpData = pdf.XmpMetaData; //Get the XMP MetaData in XML format XmlDocument xmlData = xmpData.XmlData; string s = xmlData.InnerXml; Console.WriteLine(s); } } }
Output:
From the following output, we can see there is an XML tag named pdfaid:part and another XML tag named pdfaid:conformance. The PDF/A specification indicates that pdfaid:part references the PDF/A version identifier, and pdfaid:conformance references the PDF/A conformance level (A or B in case of PDF/A-1). In this example, the PDF/A version is 1 and the PDF/A conformance level is A. That is to say, this file is PDF/A-1a.
Detect if a PDF File is a Portfolio in C#/VB.NET
A PDF Portfolio can combine a wide range of file types such as Word, Excel, PDF and Image files, compared with merging files into a single PDF file, PDF Portfolio remains the individual identities of the files, and you can easily open, read, edit, and format each of them independently of the other files in the PDF Portfolio.
Spire.PDF allows developers to detect if a PDF file is a Portfolio programmatically using c# and vb.net. The following example uses a PDF Portfolio consists of an image, a PDF document and a Word file:
Detail steps:
Step 1: Instantiate a PdfDocument object and load the PDF file.
PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Portfolio.pdf");
Step 2: Detect if the PDF file is a Portfolio.
bool isPortfolio = pdf.IsPortfolio; if (isPortfolio) { Console.WriteLine("It's a Portfolio!"); }
Screenshot:
Full code:
using System; using Spire.Pdf; namespace Detect_if_a_PDF_is_a_Portfolio { class Program { static void Main(string[] args) { PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Portfolio.pdf"); bool isPortfolio = pdf.IsPortfolio; if (isPortfolio) { Console.WriteLine("It's a Portfolio!"); } Console.ReadKey(); } } }
Imports Spire.Pdf Namespace Detect_if_a_PDF_is_a_Portfolio Class Program Private Shared Sub Main(args As String()) Dim pdf As New PdfDocument() pdf.LoadFromFile("Portfolio.pdf") Dim isPortfolio As Boolean = pdf.IsPortfolio If isPortfolio Then Console.WriteLine("It's a Portfolio!") End If Console.ReadKey() End Sub End Class End Namespace
Show or Hide PDF Layers in C#
When creating a PDF layer, Spire.PDF allows developers to set an initial visibility state for the layer. While it also supports to change the visibility of existing layers in a PDF document. This article explains how to show or hide the existing layers using Spire.PDF.
PdfLayer.Visibility property is used to change the visibility of a PDF layer. To show a hidden layer, set the PdfLayer.Visibility property to PdfVisibility.On. To hide an existing layer, set the PdfLayer.Visibility to PdfVisibility.Off.
The following example shows how to hide a specific PDF layers:
using Spire.Pdf; using Spire.Pdf.Graphics.Layer; namespace HideLayer { class Program { static void Main(string[] args) { using (PdfDocument doc = new PdfDocument("AddLayers.pdf")) { //Hide the layer by index doc.Layers[1].Visibility = PdfVisibility.Off; //Hide the layer by Name //doc.Layers["BlueLine"].Visibility = PdfVisibility.Off; //Save the file doc.SaveToFile("HideLayer.pdf"); } } } }
To show or hide all of the layers:
using Spire.Pdf; using Spire.Pdf.Graphics.Layer; namespace ShowLayer { class Program { static void Main(string[] args) { using (PdfDocument doc = new PdfDocument("AddLayers.pdf")) { for (int i = 0; i < doc.Layers.Count; i++) { //Show all of the layers //doc.Layers[i].Visibility = PdfVisibility.On; //Hide all of the layers doc.Layers[i].Visibility = PdfVisibility.Off; } //Save the file doc.SaveToFile("HideAllLayers.pdf"); } } } }
Screeshot of the sample PDF document:
Screenshot after hiding all of the layers:
C#/VB.NET: Add, Hide or Delete Layers in PDF
PDF layer is a feature that arranges the content of a PDF file in layers, which allows users to selectively set some content to be visible and others to be invisible in the same PDF file. PDF layers are a common element used in layered artwork, maps and CAD drawings. This article will demonstrate how to programmatically add, hide or delete layers in a PDF file using Spire.PDF for .NET.
- Add Layers to a PDF Document in C# and VB.NET
- Set Visibility of Layers in a PDF Document in C# and VB.NET
- Delete Layers in a PDF Document in C# and VB.NET
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Add Layers to a PDF Document in C# and VB.NET
Spire.PDF for .NET provides PdfDocument.Layers.AddLayer() method to add a layer in a PDF document, and you can then draw text, lines, images or shapes on the PDF layer. The detailed steps are as follows.
- Create a PdfDocument instance.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Add a layer with specified name in the PDF using PdfDocument.Layers.AddLayer(String) method. Or you can also set the visibility of the layer while adding it using PdfDocument.Layers.AddLayer(String, PdfVisibility) method.
- Create a canvas for the layer using PdfLayer.CreateGraphics() method.
- Draw text, image or other elements on the canvas.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Graphics.Layer; using System.Drawing; namespace AddLayersToPdf { class Program { static void Main(string[] args) { //Create a PdfDocument instance and load a sample PDF file PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.pdf"); //Invoke AddLayerWatermark method to add a watermark layer AddLayerWatermark(pdf); //Invoke AddLayerHeader method to add a header layer AddLayerHeader(pdf); //Save to file pdf.SaveToFile("AddLayers.pdf"); pdf.Close(); } private static void AddLayerWatermark(PdfDocument doc) { //Create a layer named "Watermark" PdfLayer layer = doc.Layers.AddLayer("Watermark"); //Create a font PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 48), true); //Specify the watermark text string watermarkText = "CONFIDENTIAL"; //Get text size SizeF fontSize = font.MeasureString(watermarkText); //Calculate two offsets float offset1 = (float)(fontSize.Width * System.Math.Sqrt(2) / 4); float offset2 = (float)(fontSize.Height * System.Math.Sqrt(2) / 4); //Get page count int pageCount = doc.Pages.Count; //Declare two variables PdfPageBase page; PdfCanvas canvas; //Loop through the pages for (int i = 0; (i < pageCount); i++) { page = doc.Pages[i]; //Create a canvas from layer canvas = layer.CreateGraphics(page.Canvas); canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2); canvas.SetTransparency(0.4f); canvas.RotateTransform(-45); //Draw sting on the canvas of layer canvas.DrawString(watermarkText, font, PdfBrushes.DarkBlue, 0, 0); } } private static void AddLayerHeader(PdfDocument doc) { // Create a layer named "Header" PdfLayer layer = doc.Layers.AddLayer("Header"); //Get page size SizeF size = doc.Pages[0].Size; //Specify the initial values of X and y float x = 90; float y = 40; //Get page count int pageCount = doc.Pages.Count; //Declare two variables PdfPageBase page; PdfCanvas canvas; //Loop through the pages for (int i = 0; (i < pageCount); i++) { //Draw an image on the layer PdfImage pdfImage = PdfImage.FromFile(@"C:\Users\Administrator\Desktop\img.jpg"); float width = pdfImage.Width; float height = pdfImage.Height; page = doc.Pages[i]; canvas = layer.CreateGraphics(page.Canvas); canvas.DrawImage(pdfImage, x, y, width, height); //Draw a line on the layer PdfPen pen = new PdfPen(PdfBrushes.DarkGray, 2); canvas.DrawLine(pen, x, (y + (height + 5)), (size.Width - x), (y + (height + 2))); } } } }
Set Visibility of Layers in a PDF Document in C# and VB.NET
To set the visibility of an existing layer, you'll need to get a specified layer by its index or name using PdfDocument.Layers property, and then show or hide the layer using PdfLayer.Visibility property. The detailed steps are as follows.
- Create a PdfDocument instance.
- Load a sample PDF document using PdfDocument.LoadFromFile() method.
- Set the visibility of a specified layer using PdfDocument.Layers.Visibility property.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics.Layer; namespace HideLayer { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample PDF document pdf.LoadFromFile("AddLayers.pdf"); //Hide a specified layer by index pdf.Layers[0].Visibility = PdfVisibility.Off; //Hide a specified layer by name //pdf.Layers["Watermark"].Visibility = PdfVisibility.Off; //Save the result document pdf.SaveToFile("HideLayer.pdf"); } } }
Delete Layers in a PDF Document in C# and VB.NET
Spire.PDF for .NET also allows you to remove an existing layer by its name using PdfDocument.Layers.RemoveLayer(String) method. But kindly note that the names of PDF layers may not be unique and this method will remove all PDF layers with the same name. The detailed steps are as follows.
- Create a PdfDocument instance.
- Load a sample PDF document using PdfDocument.LoadFromFile() method.
- Delete a specified layer by its name using PdfDocument.Layers.RemoveLayer(String) method.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; namespace DeleteLayer { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample PDF document pdf.LoadFromFile("AddLayers.pdf"); //Remove a layer by name pdf.Layers.RemoveLayer(("Watermark")); //Save the result document pdf.SaveToFile("DeleteLayer.pdf", FileFormat.PDF); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#/VB.NET: Compress PDF Documents
Large PDF files can be cumbersome to work with, taking up valuable storage space and slowing down transfers and uploads. Compressing PDF documents is a simple and effective way to reduce their file size and optimize them for various uses. By compressing PDFs, you can make them easier to share over email or cloud storage platforms, speed up downloads, and improve overall document management. In this article, you will learn how to compress a PDF document in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Compress Fonts and Images in a PDF Document in C#, VB.NET
Fonts and high-quality images are two main factors that contribute to the size of a PDF document. To reduce the PDF document size, you can compress the font resources (or even unembed fonts) and the image quality. The following are the steps to compress PDF documents using Spire.PDF for .NET.
- Load a PDF document while initializing the PdfCompressor object.
- Get text compression options through PdfCompressor.Options.TextCompressionOptions property.
- Compress font resources by setting TextCompressionOptions.CompressFonts to true.
- Get image compression options through PdfCompressor.Options.ImageCompressionOptions property.
- Set the image compression level through ImageCompressionOptions.ImageQuality property.
- Compress images by setting ImageCompressionOptions.CompressImage to true.
- Save the compressed document to file using PdfCompressor.CompressToFile() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Conversion.Compression; namespace CompressPdf { class Program { static void Main(string[] args) { //Load a PDF document while initializing the PdfCompressor object PdfCompressor compressor = new PdfCompressor("C:\\Users\\Administrator\\Desktop\\ToCompress.pdf"); //Get text compression options TextCompressionOptions textCompression = compressor.Options.TextCompressionOptions; //Compress fonts textCompression.CompressFonts = true; //Unembed fonts //textCompression.UnembedFonts = true; //Get image compression options ImageCompressionOptions imageCompression = compressor.Options.ImageCompressionOptions; //Set the compressed image quality imageCompression.ImageQuality = ImageQuality.High; //Resize images imageCompression.ResizeImages = true; //Compress images imageCompression.CompressImage = true; //Save the compressed document to file compressor.CompressToFile("Compressed.pdf"); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.