How to Edit a PDF in C#

Introduction

Iron Software has simplified many different PDF edit functions into easy-to-read and understand methods in the IronPDF library. Be it adding signatures, adding HTML footers, stamping watermarks, or adding annotations, IronPDF is the tool for you, allowing you to have readable code, programmatic PDF generation, easy debugging, and easy deployment to any supported environment or platform.

IronPDF has countless features when it comes to editing PDFs. In this tutorial article, we will walk through some of the major ones with code examples and explanations. With this article, you will have a good understanding of how to use IronPDF to edit your PDFs in C#.

Table of Contents

Edit Document Structure

Manipulate Pages

Adding PDFs at specific indexes, copying pages out as a range or one by one, and deleting pages from any PDF is a walk in the park with IronPDF which takes care of everything behind the scenes.

Add Pages

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-1.cs
using System; // Import System namespace for general types. using IronPdf; // Use IronPdf namespace for PDF manipulation. // This code appends a cover page to an existing PDF document and saves it as a new file. // Create a PDF document from an existing PDF file named "report.pdf". var pdf = PdfDocument.FromFile("report.pdf"); // Initialize a PDF renderer that uses the Chrome engine to render HTML to PDF. using (var renderer = new ChromePdfRenderer()) { // Render an HTML string as a PDF document. // This will be the cover page that we want to add to the existing PDF. var coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"); // Prepend the rendered cover page PDF to the existing PDF document. // This action combines the cover page with the original PDF, with the cover page at the beginning. pdf.PrependPdf(coverPagePdf); // Save the combined PDF to a new file called "report_with_cover.pdf". // This file now contains the original PDF prefaced with the new cover page. pdf.SaveAs("report_with_cover.pdf"); } // Note: Make sure to add appropriate error handling and validation for production use, // as this example assumes all operations succeed without exceptions.
Imports System ' Import System namespace for general types. Imports IronPdf ' Use IronPdf namespace for PDF manipulation. ' This code appends a cover page to an existing PDF document and saves it as a new file. ' Create a PDF document from an existing PDF file named "report.pdf". Private pdf = PdfDocument.FromFile("report.pdf") ' Initialize a PDF renderer that uses the Chrome engine to render HTML to PDF. Using renderer = New ChromePdfRenderer()	' Render an HTML string as a PDF document.	' This will be the cover page that we want to add to the existing PDF.	Dim coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>")	' Prepend the rendered cover page PDF to the existing PDF document.	' This action combines the cover page with the original PDF, with the cover page at the beginning.	pdf.PrependPdf(coverPagePdf)	' Save the combined PDF to a new file called "report_with_cover.pdf".	' This file now contains the original PDF prefaced with the new cover page.	pdf.SaveAs("report_with_cover.pdf") End Using ' Note: Make sure to add appropriate error handling and validation for production use, ' as this example assumes all operations succeed without exceptions.
$vbLabelText   $csharpLabel

Copy Pages

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-2.cs
// The code snippet uses a hypothetical PdfDocument class and its methods // to open a PDF file, select specific pages, and save them as a new PDF document. // Create an instance of the PdfDocument class to open "report.pdf". var pdf = new PdfDocument("report.pdf"); // Assumption: PdfDocument has a method `CopyPages` that allows copying a range of pages from // the opened document. Pages are typically 0-based index. So pages 5 to 7 are index 4 to 6. // Copy pages 5 to 7 and save them as a new document called "report_highlight.pdf". // Assumption: The `CopyPages` method takes a starting page index and an ending page index. // The `SaveAs` method then saves the copied pages as a new PDF document. pdf.CopyPages(4, 6).SaveAs("report_highlight.pdf");
' The code snippet uses a hypothetical PdfDocument class and its methods ' to open a PDF file, select specific pages, and save them as a new PDF document. ' Create an instance of the PdfDocument class to open "report.pdf". Dim pdf = New PdfDocument("report.pdf") ' Assumption: PdfDocument has a method `CopyPages` that allows copying a range of pages from ' the opened document. Pages are typically 0-based index. So pages 5 to 7 are index 4 to 6. ' Copy pages 5 to 7 and save them as a new document called "report_highlight.pdf". ' Assumption: The `CopyPages` method takes a starting page index and an ending page index. ' The `SaveAs` method then saves the copied pages as a new PDF document. pdf.CopyPages(4, 6).SaveAs("report_highlight.pdf")
$vbLabelText   $csharpLabel

Delete Pages

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-3.cs
// <summary> // Represents a simplified illustration of manipulating a PDF document in C#. // The code assumes the presence of a PdfDocument class that manages PDF files. // The PdfDocument class is expected to provide methods for loading, manipulating, and saving PDF documents. // This code snippet demonstrates opening a PDF, removing the last page (if present), and saving the result. // </summary> // Create a new PdfDocument instance representing the file "report.pdf". var pdf = new PdfDocument("report.pdf"); // Conditional check to ensure there is at least one page in the document if (pdf.PageCount > 0) { // Remove the last page from the PDF. // Pages are zero-indexed, so pdf.PageCount - 1 refers to the last page. pdf.RemovePage(pdf.PageCount - 1); // Save the modified PDF to a new file named "report_minus_one_page.pdf". pdf.SaveAs("report_minus_one_page.pdf"); } else { // Log information or take appropriate action when there are no pages in the document Console.WriteLine("The document has no pages to remove."); }
' <summary> ' Represents a simplified illustration of manipulating a PDF document in C#. ' The code assumes the presence of a PdfDocument class that manages PDF files. ' The PdfDocument class is expected to provide methods for loading, manipulating, and saving PDF documents. ' This code snippet demonstrates opening a PDF, removing the last page (if present), and saving the result. ' </summary> ' Create a new PdfDocument instance representing the file "report.pdf". Dim pdf = New PdfDocument("report.pdf") ' Conditional check to ensure there is at least one page in the document If pdf.PageCount > 0 Then	' Remove the last page from the PDF.	' Pages are zero-indexed, so pdf.PageCount - 1 refers to the last page.	pdf.RemovePage(pdf.PageCount - 1)	' Save the modified PDF to a new file named "report_minus_one_page.pdf".	pdf.SaveAs("report_minus_one_page.pdf") Else	' Log information or take appropriate action when there are no pages in the document	Console.WriteLine("The document has no pages to remove.") End If
$vbLabelText   $csharpLabel

Merge and Split PDFs

Merging PDFs into one PDF or splitting up an existing PDF is easily achieved with IronPDF's intuitive API.

Join Multiple Existing PDFs into a Single PDF Document

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-4.cs
// Import necessary namespaces using System; using System.Collections.Generic; // Assuming a namespace for PdfDocument class is required using SomePdfLibrary; // Main code execution starts here // Create a list to hold PdfDocument objects var pdfs = new List<PdfDocument> { // Load PdfDocuments from files PdfDocument.FromFile("A.pdf"), PdfDocument.FromFile("B.pdf"), PdfDocument.FromFile("C.pdf") }; // Merge the PDF documents into a single PDF document // Assuming PdfDocument has a static Merge method that takes a list of PdfDocuments PdfDocument mergedPdf = PdfDocument.Merge(pdfs); // Save the merged PDF document to a file named "merged.pdf" // Assuming PdfDocument has a method SaveAs to save the document to a file mergedPdf.SaveAs("merged.pdf"); // Dispose of each PdfDocument to release unmanaged resources // This loop iterates over each PdfDocument in the list 'pdfs' and calls the Dispose method foreach (var pdf in pdfs) { pdf.Dispose(); } // If the mergedPdf also requires disposal mergedPdf.Dispose(); 
' Import necessary namespaces Imports System Imports System.Collections.Generic ' Assuming a namespace for PdfDocument class is required Imports SomePdfLibrary ' Main code execution starts here ' Create a list to hold PdfDocument objects Private pdfs = New List(Of PdfDocument) From {PdfDocument.FromFile("A.pdf"), PdfDocument.FromFile("B.pdf"), PdfDocument.FromFile("C.pdf")} ' Merge the PDF documents into a single PDF document ' Assuming PdfDocument has a static Merge method that takes a list of PdfDocuments Private mergedPdf As PdfDocument = PdfDocument.Merge(pdfs) ' Save the merged PDF document to a file named "merged.pdf" ' Assuming PdfDocument has a method SaveAs to save the document to a file mergedPdf.SaveAs("merged.pdf") ' Dispose of each PdfDocument to release unmanaged resources ' This loop iterates over each PdfDocument in the list 'pdfs' and calls the Dispose method For Each pdf In pdfs	pdf.Dispose() Next pdf ' If the mergedPdf also requires disposal mergedPdf.Dispose()
$vbLabelText   $csharpLabel

Splitting a PDF and Extracting Pages

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-5.cs
using System; using PdfSharp.Pdf; using PdfSharp.Pdf.IO; // This code assumes you are using a library such as PdfSharp to manipulate PDF files. // Ensure you have added the necessary library references in your project. // Open the original PDF file in read-only mode var pdf = PdfReader.Open("sample.pdf", PdfDocumentOpenMode.Import); try { // Check if the PDF has at least 1 page if (pdf.PageCount > 0) { // Copy the first page from the original PDF var pdfPage1 = new PdfDocument(); pdfPage1.AddPage(pdf.Pages[0]); pdfPage1.Save("Split1.pdf"); } else { Console.WriteLine("The PDF does not contain any pages."); } // Check if the PDF has at least 3 pages if (pdf.PageCount > 2) { // Copy pages 2 & 3 from the original PDF var pdfPage2_3 = new PdfDocument(); pdfPage2_3.AddPage(pdf.Pages[1]); pdfPage2_3.AddPage(pdf.Pages[2]); pdfPage2_3.Save("Split2.pdf"); } else if (pdf.PageCount == 2) { Console.WriteLine("The PDF contains only two pages. Only the first two pages will be processed."); // Copy page 2 from the original PDF var pdfPage2 = new PdfDocument(); pdfPage2.AddPage(pdf.Pages[1]); pdfPage2.Save("Split2.pdf"); } else { Console.WriteLine("The PDF contains less than two pages. No pages will be split into Split2.pdf."); } } catch (Exception ex) { // Handle exceptions such as file not found or access denied Console.WriteLine("An error occurred: " + ex.Message); }
Imports System Imports PdfSharp.Pdf Imports PdfSharp.Pdf.IO ' This code assumes you are using a library such as PdfSharp to manipulate PDF files. ' Ensure you have added the necessary library references in your project. ' Open the original PDF file in read-only mode Private pdf = PdfReader.Open("sample.pdf", PdfDocumentOpenMode.Import) Try	' Check if the PDF has at least 1 page	If pdf.PageCount > 0 Then	' Copy the first page from the original PDF	Dim pdfPage1 = New PdfDocument()	pdfPage1.AddPage(pdf.Pages(0))	pdfPage1.Save("Split1.pdf")	Else	Console.WriteLine("The PDF does not contain any pages.")	End If	' Check if the PDF has at least 3 pages	If pdf.PageCount > 2 Then	' Copy pages 2 & 3 from the original PDF	Dim pdfPage2_3 = New PdfDocument()	pdfPage2_3.AddPage(pdf.Pages(1))	pdfPage2_3.AddPage(pdf.Pages(2))	pdfPage2_3.Save("Split2.pdf")	ElseIf pdf.PageCount = 2 Then	Console.WriteLine("The PDF contains only two pages. Only the first two pages will be processed.")	' Copy page 2 from the original PDF	Dim pdfPage2 = New PdfDocument()	pdfPage2.AddPage(pdf.Pages(1))	pdfPage2.Save("Split2.pdf")	Else	Console.WriteLine("The PDF contains less than two pages. No pages will be split into Split2.pdf.")	End If Catch ex As Exception	' Handle exceptions such as file not found or access denied	Console.WriteLine("An error occurred: " & ex.Message) End Try
$vbLabelText   $csharpLabel

Edit Document Properties

Add and Use PDF Metadata

You can easily use IronPDF to browse and edit PDF metadata:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-6.cs
// This code snippet demonstrates how to open an encrypted PDF, edit its metadata, // adjust security settings, and save it using the IronPDF library. // Note: Ensure you have the IronPDF library installed and referenced in your project. // Open an Encrypted File, or alternatively create a new PDF from HTML. var pdf = PdfDocument.FromFile("encrypted.pdf", "password"); // Edit the file metadata pdf.MetaData.Author = "Satoshi Nakamoto"; // Set the author of the PDF. pdf.MetaData.Keywords = "SEO, Friendly"; // Assign keywords for SEO purposes. pdf.MetaData.ModifiedDate = System.DateTime.Now; // Update the date to the current date and time. // Edit file security settings // The following code makes a PDF read-only and will disallow copy & paste // and printing by applying specific permissions. pdf.SecuritySettings.RemovePasswordsAndEncryption(); // Remove existing passwords and encryption. pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key"); // Make the PDF read-only with a specified key. pdf.SecuritySettings.AllowUserAnnotations = false; // Disallow the user to make annotations on the PDF. pdf.SecuritySettings.AllowUserCopyPasteContent = false; // Prevent the user from copying and pasting content. pdf.SecuritySettings.AllowUserFormData = false; // Disallow form data submission. pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights; // Allow full printing rights. // Change or set the document encryption password pdf.SecuritySettings.OwnerPassword = "top-secret"; // Password to edit the PDF. pdf.SecuritySettings.UserPassword = "shareable"; // Password to open the PDF. // Save the modified PDF pdf.SaveAs("secured.pdf"); // Save the PDF with new security settings.
Imports System ' This code snippet demonstrates how to open an encrypted PDF, edit its metadata, ' adjust security settings, and save it using the IronPDF library. ' Note: Ensure you have the IronPDF library installed and referenced in your project. ' Open an Encrypted File, or alternatively create a new PDF from HTML. Dim pdf = PdfDocument.FromFile("encrypted.pdf", "password") ' Edit the file metadata pdf.MetaData.Author = "Satoshi Nakamoto" ' Set the author of the PDF. pdf.MetaData.Keywords = "SEO, Friendly" ' Assign keywords for SEO purposes. pdf.MetaData.ModifiedDate = DateTime.Now ' Update the date to the current date and time. ' Edit file security settings ' The following code makes a PDF read-only and will disallow copy & paste ' and printing by applying specific permissions. pdf.SecuritySettings.RemovePasswordsAndEncryption() ' Remove existing passwords and encryption. pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key") ' Make the PDF read-only with a specified key. pdf.SecuritySettings.AllowUserAnnotations = False ' Disallow the user to make annotations on the PDF. pdf.SecuritySettings.AllowUserCopyPasteContent = False ' Prevent the user from copying and pasting content. pdf.SecuritySettings.AllowUserFormData = False ' Disallow form data submission. pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights ' Allow full printing rights. ' Change or set the document encryption password pdf.SecuritySettings.OwnerPassword = "top-secret" ' Password to edit the PDF. pdf.SecuritySettings.UserPassword = "shareable" ' Password to open the PDF. ' Save the modified PDF pdf.SaveAs("secured.pdf") ' Save the PDF with new security settings.
$vbLabelText   $csharpLabel

Digital Signatures

IronPDF has options to digitally sign new or existing PDF files using .pfx and .p12 X509Certificate2 digital certificates. Once a PDF file is signed, it cannot be modified without validating the certificate. This ensures fidelity.

// Example of signing PDF digitally. using IronPdf; using System.Security.Cryptography.X509Certificates; var pdf = PdfDocument.FromFile("example.pdf"); var certificate = new X509Certificate2("certificate.pfx", "password"); pdf.SignWithDigitalCertificate(certificate); pdf.SaveAs("signed.pdf");
// Example of signing PDF digitally. using IronPdf; using System.Security.Cryptography.X509Certificates; var pdf = PdfDocument.FromFile("example.pdf"); var certificate = new X509Certificate2("certificate.pfx", "password"); pdf.SignWithDigitalCertificate(certificate); pdf.SaveAs("signed.pdf");
' Example of signing PDF digitally. Imports IronPdf Imports System.Security.Cryptography.X509Certificates Private pdf = PdfDocument.FromFile("example.pdf") Private certificate = New X509Certificate2("certificate.pfx", "password") pdf.SignWithDigitalCertificate(certificate) pdf.SaveAs("signed.pdf")
$vbLabelText   $csharpLabel

PDF Attachments

IronPDF fully supports adding and removing attachments to and from your PDF documents.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-9.cs
// Import necessary namespaces using System; using IronPdf; // This code demonstrates how to render an HTML file to a PDF document, // add an attachment to the PDF, and then remove the attachment before saving the PDF. // Create a new instance of ChromePdfRenderer to render PDFs with Chrome's rendering engine var renderer = new ChromePdfRenderer(); // Render the HTML content from "my-content.html" to a PDF document // The RenderHtmlAsPdf method can accept HTML content as string or a file path to the HTML content var myPdf = renderer.RenderHtmlAsPdf(System.IO.File.ReadAllText("my-content.html")); // Create a byte array to store example attachment data // Replace with actual data if necessary. This is a placeholder. byte[] exampleAttachment = new byte[] { /* insert byte data here */ }; // Add a new attachment to the PDF document // 'attachment_1' is the name of the attachment var attachment1 = myPdf.Attachments.AddAttachment("attachment_1", exampleAttachment); // Remove the previously added attachment from the PDF document if necessary // This is optional if you need to remove the attachment for any reason myPdf.Attachments.RemoveAttachment(attachment1); // Save the rendered PDF document as "my-content.pdf" myPdf.SaveAs("my-content.pdf");
' Import necessary namespaces Imports System Imports IronPdf ' This code demonstrates how to render an HTML file to a PDF document, ' add an attachment to the PDF, and then remove the attachment before saving the PDF. ' Create a new instance of ChromePdfRenderer to render PDFs with Chrome's rendering engine Private renderer = New ChromePdfRenderer() ' Render the HTML content from "my-content.html" to a PDF document ' The RenderHtmlAsPdf method can accept HTML content as string or a file path to the HTML content Private myPdf = renderer.RenderHtmlAsPdf(System.IO.File.ReadAllText("my-content.html")) ' Create a byte array to store example attachment data ' Replace with actual data if necessary. This is a placeholder. Private exampleAttachment() As Byte = {} ' Add a new attachment to the PDF document ' 'attachment_1' is the name of the attachment Private attachment1 = myPdf.Attachments.AddAttachment("attachment_1", exampleAttachment) ' Remove the previously added attachment from the PDF document if necessary ' This is optional if you need to remove the attachment for any reason myPdf.Attachments.RemoveAttachment(attachment1) ' Save the rendered PDF document as "my-content.pdf" myPdf.SaveAs("my-content.pdf")
$vbLabelText   $csharpLabel

Compress PDFs

IronPDF supports compression of PDFs. One way a PDF file size can be reduced is by reducing the size of embedded images within the PdfDocument. In IronPDF, we can call the CompressImages method.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-10.cs
using System; using System.IO; // The PdfDocument class is created to manage PDF documents, specifically to compress images within a PDF // and save it to a new location. Ensure that a compatible PDF library is referenced in the project. // Implementation of the PdfDocument class with functionalities for handling PDF documents. public class PdfDocument { private string _filePath; // Constructor to initialize the PdfDocument with the given file path. public PdfDocument(string filePath) { // Validates that the provided file path points to an existing file. if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) { throw new ArgumentException("File does not exist.", nameof(filePath)); } _filePath = filePath; } // Method to compress images within the PDF. The quality parameter dictates the compression level (1-100). public void CompressImages(int quality) { // Validates the quality parameter to ensure it is between 1 and 100. if (quality < 1 || quality > 100) throw new ArgumentOutOfRangeException(nameof(quality), "Quality must be between 1 and 100."); // Placeholder for image compression logic. Console.WriteLine($"Compressing images with quality {quality}%..."); // Image compression logic should be implemented here using a suitable PDF library. } // Method to save the processed document to a new path. public void SaveAs(string newFilePath) { // Validates that the new file path is not null or empty. if (string.IsNullOrEmpty(newFilePath)) { throw new ArgumentNullException(nameof(newFilePath), "New file path cannot be null or empty."); } // Placeholder for the actual save logic. Console.WriteLine($"Saving compressed PDF to {newFilePath}..."); // Logic to save the processed PDF document to the specified file path should be implemented here. } } // Example usage of the PdfDocument class. var pdf = new PdfDocument("document.pdf"); // Compress images in the document to 60% of the original quality. // Quality parameter ranges from 1 (lowest quality) to 100 (highest quality). pdf.CompressImages(60); // Save the document as a new file named "document_compressed.pdf". pdf.SaveAs("document_compressed.pdf");
Imports System Imports System.IO ' The PdfDocument class is created to manage PDF documents, specifically to compress images within a PDF ' and save it to a new location. Ensure that a compatible PDF library is referenced in the project. ' Implementation of the PdfDocument class with functionalities for handling PDF documents. Public Class PdfDocument	Private _filePath As String	' Constructor to initialize the PdfDocument with the given file path.	Public Sub New(ByVal filePath As String)	' Validates that the provided file path points to an existing file.	If String.IsNullOrEmpty(filePath) OrElse Not File.Exists(filePath) Then	Throw New ArgumentException("File does not exist.", NameOf(filePath))	End If	_filePath = filePath	End Sub	' Method to compress images within the PDF. The quality parameter dictates the compression level (1-100).	Public Sub CompressImages(ByVal quality As Integer)	' Validates the quality parameter to ensure it is between 1 and 100.	If quality < 1 OrElse quality > 100 Then	Throw New ArgumentOutOfRangeException(NameOf(quality), "Quality must be between 1 and 100.")	End If	' Placeholder for image compression logic.	Console.WriteLine($"Compressing images with quality {quality}%...")	' Image compression logic should be implemented here using a suitable PDF library.	End Sub	' Method to save the processed document to a new path.	Public Sub SaveAs(ByVal newFilePath As String)	' Validates that the new file path is not null or empty.	If String.IsNullOrEmpty(newFilePath) Then	Throw New ArgumentNullException(NameOf(newFilePath), "New file path cannot be null or empty.")	End If	' Placeholder for the actual save logic.	Console.WriteLine($"Saving compressed PDF to {newFilePath}...")	' Logic to save the processed PDF document to the specified file path should be implemented here.	End Sub End Class ' Example usage of the PdfDocument class. Private pdf = New PdfDocument("document.pdf") ' Compress images in the document to 60% of the original quality. ' Quality parameter ranges from 1 (lowest quality) to 100 (highest quality). pdf.CompressImages(60) ' Save the document as a new file named "document_compressed.pdf". pdf.SaveAs("document_compressed.pdf")
$vbLabelText   $csharpLabel

There is a second optional parameter that can scale down the image resolution according to its visible size in the PDF document. Note that this may cause distortion with some image configurations.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-11.cs

Editing PDF Content

Add Headers and Footers

You can easily add headers and footers to your PDF. IronPDF has two different kinds of "HeadersFooters" which are TextHeaderFooter and HtmlHeaderFooter.

HTML Header and Footer will use the rendered version of your HTML as a Header or Footer on your PDF document for a pixel-perfect layout.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-12.cs
// Create an instance of ChromePdfRenderer to render PDF documents. var renderer = new ChromePdfRenderer(); // Configure footer settings using HTML to style the text. // Available mergeable fields for footer formatting include: // {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title} renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter { // Maximum height for the footer in millimeters. MaxHeight = 15, // HTML fragment to define the footer's appearance. It uses mergeable fields to display current page and total pages. HtmlFragment = "<center><i>{page} of {total-pages}</i></center>", // Option to draw a dividing line between the content and the footer. DrawDividerLine = true }; // Configure header settings using an image asset. // BaseUrl property is utilized to set a relative path to the image assets. renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter { // Maximum height for the header in millimeters. MaxHeight = 20, // HTML fragment to define the header's appearance. Here, an image is used in the header. HtmlFragment = "<img src='logo.png'>", // Base URL to locate the image assets. BaseUrl = new Uri(@"C:\assets\images").AbsoluteUri // Ensure usage of System.Uri };
' Create an instance of ChromePdfRenderer to render PDF documents. Dim renderer = New ChromePdfRenderer() ' Configure footer settings using HTML to style the text. ' Available mergeable fields for footer formatting include: ' {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title} renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With {	.MaxHeight = 15,	.HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",	.DrawDividerLine = True } ' Configure header settings using an image asset. ' BaseUrl property is utilized to set a relative path to the image assets. renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {	.MaxHeight = 20,	.HtmlFragment = "<img src='logo.png'>",	.BaseUrl = (New Uri("C:\assets\images")).AbsoluteUri }
$vbLabelText   $csharpLabel

The basic header and footer is the TextHeaderFooter.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-13.cs
// Import necessary namespaces using IronPdf; using IronSoftware.Drawing; // Instantiate a new ChromePdfRenderer object var renderer = new ChromePdfRenderer { // Configure rendering options RenderingOptions = new RenderingOptions { // Start page numbering from 1. Change to 2 if a cover-page will be appended FirstPageNumber = 1, // Configure header settings for each page TextHeader = new TextHeader { // Draw a divider line under the header DrawDividerLine = true, // Placeholder for the URL in the center of the header CenterText = "{url}", // Set the font to Helvetica Font = FontTypes.Helvetica, // Set the font size to 12 FontSize = 12 }, // Configure footer settings for each page TextFooter = new TextFooter { // Draw a divider line above the footer DrawDividerLine = true, // Set the font to Arial Font = FontTypes.Arial, // Set the font size to 10 FontSize = 10, // Placeholder for date and time on the left side of footer LeftText = "{date} {time}", // Placeholder for page information on the right side of footer RightText = "{page} of {total-pages}" } } };
' Import necessary namespaces Imports IronPdf Imports IronSoftware.Drawing ' Instantiate a new ChromePdfRenderer object Private renderer = New ChromePdfRenderer With {	.RenderingOptions = New RenderingOptions With {	.FirstPageNumber = 1, .TextHeader = New TextHeader With {	.DrawDividerLine = True,	.CenterText = "{url}",	.Font = FontTypes.Helvetica,	.FontSize = 12	},	.TextFooter = New TextFooter With {	.DrawDividerLine = True,	.Font = FontTypes.Arial,	.FontSize = 10,	.LeftText = "{date} {time}",	.RightText = "{page} of {total-pages}"	}	} }
$vbLabelText   $csharpLabel

Find and Replace Text in a PDF

Make placeholders in your PDFs and replace them programmatically, or simply replace all instances of a text phrase using ReplaceTextOnPage.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-14.cs
// Import the necessary namespaces for PDF operations. using System; // Replace SomePdfLibrary with the actual library that provides PdfDocument. // This could be something like PdfSharp, iTextSharp, or any other library you're using. using SomePdfLibrary; // Load an existing PDF document from a file. // Make sure the file path is correct and the file exists. var pdf = PdfDocument.FromFile("sample.pdf"); // Parameters for text replacement. int pageIndex = 1; // Index of the page where text replacement should occur. Note that pageIndex is typically 0-based. string oldText = ".NET 6"; // Text in the PDF that you want to replace. string newText = ".NET 7"; // New text to appear instead of the old text. // Replace the specified oldText with newText on the specified pageIndex. // Ensure the PdfDocument object provides a method ReplaceTextOnPage, supported by the used library. pdf.ReplaceTextOnPage(pageIndex, oldText, newText); // Example of replacing a placeholder in the PDF page with a desired value. // '[DATE]' is a placeholder in the PDF which is replaced with the specified date. pdf.ReplaceTextOnPage(pageIndex, "[DATE]", "01/01/2000"); // Save the modified PDF to a new file. // Provide a new filename to avoid overwriting the original document. pdf.SaveAs("new_sample.pdf"); // Note: Ensure that the appropriate PDF library is referenced to utilize PdfDocument and its methods. // This script assumes that the PdfDocument class has methods like FromFile, ReplaceTextOnPage, and SaveAs.
' Import the necessary namespaces for PDF operations. Imports System ' Replace SomePdfLibrary with the actual library that provides PdfDocument. ' This could be something like PdfSharp, iTextSharp, or any other library you're using. Imports SomePdfLibrary ' Load an existing PDF document from a file. ' Make sure the file path is correct and the file exists. Private pdf = PdfDocument.FromFile("sample.pdf") ' Parameters for text replacement. Private pageIndex As Integer = 1 ' Index of the page where text replacement should occur. Note that pageIndex is typically 0-based. Private oldText As String = ".NET 6" ' Text in the PDF that you want to replace. Private newText As String = ".NET 7" ' New text to appear instead of the old text. ' Replace the specified oldText with newText on the specified pageIndex. ' Ensure the PdfDocument object provides a method ReplaceTextOnPage, supported by the used library. pdf.ReplaceTextOnPage(pageIndex, oldText, newText) ' Example of replacing a placeholder in the PDF page with a desired value. ' '[DATE]' is a placeholder in the PDF which is replaced with the specified date. pdf.ReplaceTextOnPage(pageIndex, "[DATE]", "01/01/2000") ' Save the modified PDF to a new file. ' Provide a new filename to avoid overwriting the original document. pdf.SaveAs("new_sample.pdf") ' Note: Ensure that the appropriate PDF library is referenced to utilize PdfDocument and its methods. ' This script assumes that the PdfDocument class has methods like FromFile, ReplaceTextOnPage, and SaveAs.
$vbLabelText   $csharpLabel

Outlines and Bookmarks

An outline or "bookmark" adds a way to navigate to key pages of a PDF. IronPDF will automatically import existing bookmarks from PDF documents and allow more to be added, edited, and nested.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-15.cs
// Import necessary namespaces for PDF manipulation using System; using System.Collections.Generic; // Simulated PdfDocument class to demonstrate PDF manipulation. // In a real-world scenario, this class should interface with an actual PDF library. public class PdfDocument { // Static method to load a PDF document from a file. public static PdfDocument FromFile(string filePath) { // Load an existing PDF document from a file. // Actual logic to open and read the PDF document would be implemented here. return new PdfDocument(); } // Accessor for handling the document's bookmarks. public BookmarksCollection Bookmarks { get; } = new BookmarksCollection(); // Method to save the current state of the PDF document to a file. public void SaveAs(string filePath) { // Actual logic to save the PDF document to a specified file path would go here. } } // Class representing a PDF bookmark. public class Bookmark { // Title of the bookmark. public string Title { get; set; } // Page number where the bookmark points. public int PageNumber { get; set; } // Collection to hold any nested (child) bookmarks. public BookmarksCollection Children { get; } = new BookmarksCollection(); } // Collection class to manage a list of bookmarks, inherits from List<Bookmark>. public class BookmarksCollection : List<Bookmark> { // Method to add a bookmark at the end of the collection. public Bookmark AddBookMarkAtEnd(string title, int pageNumber) { var bookmark = new Bookmark { Title = title, PageNumber = pageNumber }; this.Add(bookmark); return bookmark; } // Method to add a bookmark at the start of the collection. public Bookmark AddBookMarkAtStart(string title, int pageNumber) { var bookmark = new Bookmark { Title = title, PageNumber = pageNumber }; this.Insert(0, bookmark); return bookmark; } } // Example usage of the PDF manipulation functionality // Load an existing PDF or create a new one by simulating loading from a file. PdfDocument pdf = PdfDocument.FromFile("existing.pdf"); // Add bookmarks at the end of the main bookmark list. pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2); pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3); // Store a new bookmark in a variable to add nested bookmarks. var summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17); // Add a sub-bookmark within the summary bookmark. var conclusionBookmark = summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18); // Add another bookmark to the end of the highest-level bookmark list. pdf.Bookmarks.AddBookMarkAtEnd("References", 20); // Save the changes to the PDF file. pdf.SaveAs("existing.pdf");
' Import necessary namespaces for PDF manipulation Imports System Imports System.Collections.Generic ' Simulated PdfDocument class to demonstrate PDF manipulation. ' In a real-world scenario, this class should interface with an actual PDF library. Public Class PdfDocument	' Static method to load a PDF document from a file.	Public Shared Function FromFile(ByVal filePath As String) As PdfDocument	' Load an existing PDF document from a file.	' Actual logic to open and read the PDF document would be implemented here.	Return New PdfDocument()	End Function	' Accessor for handling the document's bookmarks.	Public ReadOnly Property Bookmarks() As New BookmarksCollection()	' Method to save the current state of the PDF document to a file.	Public Sub SaveAs(ByVal filePath As String)	' Actual logic to save the PDF document to a specified file path would go here.	End Sub End Class ' Class representing a PDF bookmark. Public Class Bookmark	' Title of the bookmark.	Public Property Title() As String	' Page number where the bookmark points.	Public Property PageNumber() As Integer	' Collection to hold any nested (child) bookmarks.	Public ReadOnly Property Children() As New BookmarksCollection() End Class ' Collection class to manage a list of bookmarks, inherits from List<Bookmark>. Public Class BookmarksCollection	Inherits List(Of Bookmark)	' Method to add a bookmark at the end of the collection.	Public Function AddBookMarkAtEnd(ByVal title As String, ByVal pageNumber As Integer) As Bookmark	Dim bookmark As New Bookmark With {	.Title = title,	.PageNumber = pageNumber	}	Me.Add(bookmark)	Return bookmark	End Function	' Method to add a bookmark at the start of the collection.	Public Function AddBookMarkAtStart(ByVal title As String, ByVal pageNumber As Integer) As Bookmark	Dim bookmark As New Bookmark With {	.Title = title,	.PageNumber = pageNumber	}	Me.Insert(0, bookmark)	Return bookmark	End Function End Class ' Example usage of the PDF manipulation functionality ' Load an existing PDF or create a new one by simulating loading from a file. Private pdf As PdfDocument = PdfDocument.FromFile("existing.pdf") ' Add bookmarks at the end of the main bookmark list. pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2) pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3) ' Store a new bookmark in a variable to add nested bookmarks. Dim summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17) ' Add a sub-bookmark within the summary bookmark. Dim conclusionBookmark = summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18) ' Add another bookmark to the end of the highest-level bookmark list. pdf.Bookmarks.AddBookMarkAtEnd("References", 20) ' Save the changes to the PDF file. pdf.SaveAs("existing.pdf")
$vbLabelText   $csharpLabel

Add and Edit Annotations

IronPDF has a plethora of customization options on annotations for PDFs.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-16.cs
// Load an existing PDF document from a file using IronPdf var pdf = IronPdf.PdfDocument.FromFile("existing.pdf"); // Create a PDF text annotation (a type of "sticky note") targeted for the first page (index 0) var textAnnotation = new IronPdf.Annotations.TextAnnotation(PageIndex: 0) { Title = "This is the major title", // Set the title of the annotation Contents = "This is the long 'sticky note' comment content...", // Set the detailed content Subject = "This is a subtitle", // Set a subject for additional context Opacity = 0.9, // Set the opacity of the annotation (0.0 to 1.0) Printable = false, // Determine whether the annotation is printable Hidden = false, // Set whether the annotation is initially hidden OpenByDefault = true, // Indicate if the annotation window opens by default ReadOnly = false, // Allow modifications to the annotation Rotatable = true // Allow the annotation to be rotated }; // Add the annotation to the PDF, linking it to the specified page (PageIndex) and location pdf.Annotations.Add(textAnnotation); // Save the document to preserve changes with the new annotation(s) back to the original file pdf.SaveAs("existing.pdf");
' Load an existing PDF document from a file using IronPdf Dim pdf = IronPdf.PdfDocument.FromFile("existing.pdf") ' Create a PDF text annotation (a type of "sticky note") targeted for the first page (index 0) Dim textAnnotation = New IronPdf.Annotations.TextAnnotation(PageIndex:= 0) With {	.Title = "This is the major title",	.Contents = "This is the long 'sticky note' comment content...",	.Subject = "This is a subtitle",	.Opacity = 0.9,	.Printable = False,	.Hidden = False,	.OpenByDefault = True,	.ReadOnly = False,	.Rotatable = True } ' Add the annotation to the PDF, linking it to the specified page (PageIndex) and location pdf.Annotations.Add(textAnnotation) ' Save the document to preserve changes with the new annotation(s) back to the original file pdf.SaveAs("existing.pdf")
$vbLabelText   $csharpLabel

Add Backgrounds and Foregrounds

With IronPDF, you can easily merge 2 PDF files, using one as a background or foreground:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-17.cs
/// This code uses the IronPdf library to render a PDF from a URL, add background and foreground PDFs, and save it to a specified path. /// Ensure you have a reference to IronPdf in your project and the necessary using directives /// /// Example of using IronPdf, a library for generating PDFs in C# /// Before compiling, ensure you have installed IronPdf via NuGet Package Manager: /// PM> Install-Package IronPdf using IronPdf; // IronPdf namespace for PDF functionality // Create an instance of the ChromePdfRenderer, a part of the IronPdf library var renderer = new ChromePdfRenderer(); // Render the specified URL as a PDF document // The URL is rendered and stored in a PdfDocument object var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf"); // Add a background PDF. The PDF file specified will be used as a background layer for the rendered PDF. // The path should point to an existing PDF file on your disk that you want to use as a background. pdf.AddBackgroundPdf(@"MyBackground.pdf"); // Add a foreground overlay PDF to the specified page (index 0 here) of the rendered PDF. // The path should point to an existing PDF file that will overlay on top of the rendered PDF. // Index 0 refers to the first page of the PDF. pdf.AddForegroundOverlayPdfToPage(0, @"MyForeground.pdf"); // Save the complete PDF to the desired file path // Specify the full path where you want the resulting PDF to be saved pdf.SaveAs(@"C:\Path\To\Complete.pdf");
''' This code uses the IronPdf library to render a PDF from a URL, add background and foreground PDFs, and save it to a specified path. ''' Ensure you have a reference to IronPdf in your project and the necessary using directives ''' ''' Example of using IronPdf, a library for generating PDFs in C# ''' Before compiling, ensure you have installed IronPdf via NuGet Package Manager: ''' PM> Install-Package IronPdf Imports IronPdf ' IronPdf namespace for PDF functionality ' Create an instance of the ChromePdfRenderer, a part of the IronPdf library Private renderer = New ChromePdfRenderer() ' Render the specified URL as a PDF document ' The URL is rendered and stored in a PdfDocument object Private pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf") ' Add a background PDF. The PDF file specified will be used as a background layer for the rendered PDF. ' The path should point to an existing PDF file on your disk that you want to use as a background. pdf.AddBackgroundPdf("MyBackground.pdf") ' Add a foreground overlay PDF to the specified page (index 0 here) of the rendered PDF. ' The path should point to an existing PDF file that will overlay on top of the rendered PDF. ' Index 0 refers to the first page of the PDF. pdf.AddForegroundOverlayPdfToPage(0, "MyForeground.pdf") ' Save the complete PDF to the desired file path ' Specify the full path where you want the resulting PDF to be saved pdf.SaveAs("C:\Path\To\Complete.pdf")
$vbLabelText   $csharpLabel

Stamping and Watermarking

The ability to do stamping and watermarking are fundamental features of any PDF editor.

Stamping and Watermarking

Stamper Abstract Class

The Stamper abstract class is used as a parameter for all of IronPDF's stamping methods.

There are many classes for each use-case:

To apply any of these, use one of our ApplyStamp() methods. See: the Apply Stamp section of this tutorial.

Stamper Class Properties

abstract class Stamper | └─── int : Opacity └─── int : Rotation | └─── double : Scale | └─── Length : HorizontalOffset └─── Length : VerticalOffset | └─── Length : MinWidth └─── Length : MaxWidth | └─── Length : MinHeight └─── Length : MaxHeight | └─── string : Hyperlink | └─── bool : IsStampBehindContent (default : false) | └─── HorizontalAlignment : HorizontalAlignment │ │ Left │ │ Center (default) │ │ Right │ └─── VerticalAlignment : VerticalAlignment │ Top │ Middle (default) │ Bottom

Stamping Examples

Below we showcase every one of Stamper's subclasses with a code example.

Stamp Text onto a PDF

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-18.cs
// Assuming types like ChromePdfRenderer, TextStamper, and VerticalAlignment are part of a library // such as IronPdf (though the exact library is not specified here). Ensure necessary namespaces // are accessible depending on the actual library in use. using IronPdf; // Replace with the correct namespace if it's different // Create a new PdfRenderer object, assumed to be ChromePdfRenderer based on original code. var renderer = new ChromePdfRenderer(); // Render an HTML string as a PDF document. The rendered PDF is stored in the variable 'pdf'. var pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>"); // Create the first TextStamper, defining how the stamp will appear on the PDF. TextStamper stamper1 = new TextStamper { // The text to be displayed in the stamp. Text = "Hello World! Stamp One Here!", // Font attributes for the stamp. FontFamily = "Bungee Spice", UseGoogleFont = true, FontSize = 100, IsBold = true, IsItalic = true, // Position the stamp at the top of the document. VerticalAlignment = VerticalAlignment.Top }; // Create the second TextStamper with different attributes. TextStamper stamper2 = new TextStamper { // The text to be displayed in the stamp. Text = "Hello World! Stamp Two Here!", // Font attributes for the stamp. FontFamily = "Bungee Spice", UseGoogleFont = true, FontSize = 30, // Position the stamp at the bottom of the document. VerticalAlignment = VerticalAlignment.Bottom }; // Create an array of stampers to apply multiple stamps to the PDF. TextStamper[] stampersToApply = { stamper1, stamper2 }; // Apply the array of text stamps to the PDF. This stamps all the pages of the document. pdf.ApplyStamp(stampersToApply); // Optionally, apply an additional stamp individually. // Note: This adds another instance of stamper2; possibly redundant if using ApplyMultipleStamps. pdf.ApplyStamp(stamper2);
' Assuming types like ChromePdfRenderer, TextStamper, and VerticalAlignment are part of a library ' such as IronPdf (though the exact library is not specified here). Ensure necessary namespaces ' are accessible depending on the actual library in use. Imports IronPdf ' Replace with the correct namespace if it's different ' Create a new PdfRenderer object, assumed to be ChromePdfRenderer based on original code. Private renderer = New ChromePdfRenderer() ' Render an HTML string as a PDF document. The rendered PDF is stored in the variable 'pdf'. Private pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>") ' Create the first TextStamper, defining how the stamp will appear on the PDF. Private stamper1 As New TextStamper With {	.Text = "Hello World! Stamp One Here!",	.FontFamily = "Bungee Spice",	.UseGoogleFont = True,	.FontSize = 100,	.IsBold = True,	.IsItalic = True,	.VerticalAlignment = VerticalAlignment.Top } ' Create the second TextStamper with different attributes. Private stamper2 As New TextStamper With {	.Text = "Hello World! Stamp Two Here!",	.FontFamily = "Bungee Spice",	.UseGoogleFont = True,	.FontSize = 30,	.VerticalAlignment = VerticalAlignment.Bottom } ' Create an array of stampers to apply multiple stamps to the PDF. Private stampersToApply() As TextStamper = { stamper1, stamper2 } ' Apply the array of text stamps to the PDF. This stamps all the pages of the document. pdf.ApplyStamp(stampersToApply) ' Optionally, apply an additional stamp individually. ' Note: This adds another instance of stamper2; possibly redundant if using ApplyMultipleStamps. pdf.ApplyStamp(stamper2)
$vbLabelText   $csharpLabel

Stamp an Image onto a PDF

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-19.cs
// Import statements for necessary namespaces using System; using System.IO; // Mock implementations for demonstration purposes. // This code assumes the existence of classes and methods to handle PDF and image operations. // Represents a PDF document. public class PdfDocument { private string filePath; // Constructor: Initializes the PdfDocument with a specified file path. public PdfDocument(string path) { filePath = path; // Additional logic to open and process the PDF document can be added here. } // Method to apply a stamp to specific pages of the PDF document. // pageIndices parameter is optional and stamps all pages if not provided. public void ApplyStamp(ImageStamper imageStamper, int[] pageIndices = null) { // Check if pageIndices is null, meaning stamp all pages. if (pageIndices == null) { Console.WriteLine($"Stamping all pages of PDF {filePath} with image {imageStamper.ImagePath}."); } else { // Stamp only specified page indices. Console.WriteLine($"Stamping pages {string.Join(", ", pageIndices)} of PDF {filePath} with image {imageStamper.ImagePath}."); } } } // Represents an image stamper to be used for stamping PDFs. public class ImageStamper { public string ImagePath { get; } // Constructor: Initializes the ImageStamper with a specified image file path. public ImageStamper(string path) { ImagePath = path; // Additional logic to load and process the image can be added here. } } // Create a new PdfDocument object by specifying the path to the PDF file. var pdf = new PdfDocument("/attachments/2022_Q1_sales.pdf"); // Create a new ImageStamper object with the path to the image file to be used as a stamp. ImageStamper logoImageStamper = new ImageStamper("/assets/logo.png"); // Apply the stamp to every page of the PDF document. pdf.ApplyStamp(logoImageStamper); // Apply the stamp only to the first page (page index 0) of the PDF document. pdf.ApplyStamp(logoImageStamper, new[] { 0 }); // Apply the stamp to specific pages given by an array of page indices. pdf.ApplyStamp(logoImageStamper, new[] { 0, 3, 11 });
' Import statements for necessary namespaces Imports System Imports System.IO ' Mock implementations for demonstration purposes. ' This code assumes the existence of classes and methods to handle PDF and image operations. ' Represents a PDF document. Public Class PdfDocument	Private filePath As String	' Constructor: Initializes the PdfDocument with a specified file path.	Public Sub New(ByVal path As String)	filePath = path	' Additional logic to open and process the PDF document can be added here.	End Sub	' Method to apply a stamp to specific pages of the PDF document.	' pageIndices parameter is optional and stamps all pages if not provided.	Public Sub ApplyStamp(ByVal imageStamper As ImageStamper, Optional ByVal pageIndices() As Integer = Nothing)	' Check if pageIndices is null, meaning stamp all pages.	If pageIndices Is Nothing Then	Console.WriteLine($"Stamping all pages of PDF {filePath} with image {imageStamper.ImagePath}.")	Else	' Stamp only specified page indices.	Console.WriteLine($"Stamping pages {String.Join(", ", pageIndices)} of PDF {filePath} with image {imageStamper.ImagePath}.")	End If	End Sub End Class ' Represents an image stamper to be used for stamping PDFs. Public Class ImageStamper	Public ReadOnly Property ImagePath() As String	' Constructor: Initializes the ImageStamper with a specified image file path.	Public Sub New(ByVal path As String)	ImagePath = path	' Additional logic to load and process the image can be added here.	End Sub End Class ' Create a new PdfDocument object by specifying the path to the PDF file. Private pdf = New PdfDocument("/attachments/2022_Q1_sales.pdf") ' Create a new ImageStamper object with the path to the image file to be used as a stamp. Private logoImageStamper As New ImageStamper("/assets/logo.png") ' Apply the stamp to every page of the PDF document. pdf.ApplyStamp(logoImageStamper) ' Apply the stamp only to the first page (page index 0) of the PDF document. pdf.ApplyStamp(logoImageStamper, { 0 }) ' Apply the stamp to specific pages given by an array of page indices. pdf.ApplyStamp(logoImageStamper, { 0, 3, 11 })
$vbLabelText   $csharpLabel

Stamp HTML onto a PDF

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-20.cs
// Import the necessary namespaces. using IronPdf; // Assuming you're using IronPdf for PDF rendering and manipulation. using IronPdf.Rendering.Stamping; // IronPdf namespace for stamping functionality. using IronPdf.Rendering; // IronPdf namespace for rendering functionality. // Create a new instance of ChromePdfRenderer. var renderer = new ChromePdfRenderer(); // Render a simple HTML string as a PDF document. var pdf = renderer.RenderHtmlAsPdf("<p>Hello World, example HTML body.</p>"); // Create an HtmlStamper object to apply a stamp to the PDF. // The stamp contains HTML that represents the content to be stamped on the PDF. HtmlStamper stamper = new HtmlStamper("<p>Example HTML Stamped</p><div style='width:250pt;height:250pt;background-color:red;'></div>") { // Set the horizontal offset of the stamp to -3 inches. HorizontalOffset = new Length(-3, MeasurementUnit.Inch), // Align the stamp to the bottom of the PDF. VerticalAlignment = VerticalAlignment.Bottom }; // Apply the stamp to the rendered PDF. pdf.ApplyStamp(stamper);
' Import the necessary namespaces. Imports IronPdf ' Assuming you're using IronPdf for PDF rendering and manipulation. Imports IronPdf.Rendering.Stamping ' IronPdf namespace for stamping functionality. Imports IronPdf.Rendering ' IronPdf namespace for rendering functionality. ' Create a new instance of ChromePdfRenderer. Private renderer = New ChromePdfRenderer() ' Render a simple HTML string as a PDF document. Private pdf = renderer.RenderHtmlAsPdf("<p>Hello World, example HTML body.</p>") ' Create an HtmlStamper object to apply a stamp to the PDF. ' The stamp contains HTML that represents the content to be stamped on the PDF. Dim stamper As New HtmlStamper("<p>Example HTML Stamped</p><div style='width:250pt;height:250pt;background-color:red;'></div>") If True Then	' Set the horizontal offset of the stamp to -3 inches. 'INSTANT VB WARNING: An assignment within expression was extracted from the following statement: 'ORIGINAL LINE: HorizontalOffset = new Length(-3, MeasurementUnit.Inch), VerticalAlignment = VerticalAlignment.Bottom	New Length(-3, MeasurementUnit.Inch), VerticalAlignment = VerticalAlignment.Bottom	HorizontalOffset = New Length(-3, MeasurementUnit.Inch), VerticalAlignment End If ' Apply the stamp to the rendered PDF. pdf.ApplyStamp(stamper)
$vbLabelText   $csharpLabel

Stamp a Barcode onto a PDF

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-21.cs
// Import necessary namespaces for PDF and barcode handling using IronPdf; // Assuming IronPdf library provides PDF functionalities using IronPdf.Forms; // Assuming IronPdf.Forms library provides different barcode functionalities // Create a BarcodeStamper instance with the desired text and the Code39 encoding type BarcodeStamper bcStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39); // Set the horizontal alignment of the barcode to the left side of the page bcStamp.HorizontalAlignment = HorizontalAlignment.Left; // Set the vertical alignment of the barcode to the bottom of the page bcStamp.VerticalAlignment = VerticalAlignment.Bottom; // Load a PDF document from the specified file path "example.pdf" PdfDocument pdf = PdfDocument.FromFile("example.pdf"); // Apply the barcode stamp onto the PDF document with the settings specified in the BarcodeStamper instance // Ensure you have read permissions on the file and that it exists pdf.ApplyStamp(bcStamp); // Save the stamped document to a new file or overwrite the existing one // Uncomment the line below if you wish to save the modified PDF to the file system // pdf.SaveAs("stamped_example.pdf"); // Uncomment to save the changes if needed
' Import necessary namespaces for PDF and barcode handling Imports IronPdf ' Assuming IronPdf library provides PDF functionalities Imports IronPdf.Forms ' Assuming IronPdf.Forms library provides different barcode functionalities ' Create a BarcodeStamper instance with the desired text and the Code39 encoding type Private bcStamp As New BarcodeStamper("IronPDF", BarcodeEncoding.Code39) ' Set the horizontal alignment of the barcode to the left side of the page bcStamp.HorizontalAlignment = HorizontalAlignment.Left ' Set the vertical alignment of the barcode to the bottom of the page bcStamp.VerticalAlignment = VerticalAlignment.Bottom ' Load a PDF document from the specified file path "example.pdf" Dim pdf As PdfDocument = PdfDocument.FromFile("example.pdf") ' Apply the barcode stamp onto the PDF document with the settings specified in the BarcodeStamper instance ' Ensure you have read permissions on the file and that it exists pdf.ApplyStamp(bcStamp) ' Save the stamped document to a new file or overwrite the existing one ' Uncomment the line below if you wish to save the modified PDF to the file system ' pdf.SaveAs("stamped_example.pdf"); // Uncomment to save the changes if needed
$vbLabelText   $csharpLabel

Stamp a QR Code onto a PDF

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-22.cs
using IronPdf; // Ensure that the IronPdf namespace is included // This code snippet creates and applies a QR code stamp to a PDF document. // Create a new BarcodeStamper object with the desired barcode content and type BarcodeStamper qrStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode); // Set the dimensions of the QR code stamp qrStamp.Height = 50; // Height of the QR code in pixels qrStamp.Width = 50; // Width of the QR code in pixels // Configure the alignment of the QR code within each page of the document qrStamp.HorizontalAlignment = HorizontalAlignment.Left; // Align the QR code to the left qrStamp.VerticalAlignment = VerticalAlignment.Bottom; // Align the QR code to the bottom // Load an existing PDF document from a file PdfDocument pdf = PdfDocument.FromFile("example.pdf"); // Apply the QR code stamp to each page of the loaded PDF document pdf.ApplyStamp(qrStamp); // To save the stamped PDF document, specify a file path and uncomment the line below // pdf.SaveAs("stamped_example.pdf"); // Save the stamped PDF document 
Imports IronPdf ' Ensure that the IronPdf namespace is included ' This code snippet creates and applies a QR code stamp to a PDF document. ' Create a new BarcodeStamper object with the desired barcode content and type Private qrStamp As New BarcodeStamper("IronPDF", BarcodeEncoding.QRCode) ' Set the dimensions of the QR code stamp qrStamp.Height = 50 ' Height of the QR code in pixels qrStamp.Width = 50 ' Width of the QR code in pixels ' Configure the alignment of the QR code within each page of the document qrStamp.HorizontalAlignment = HorizontalAlignment.Left ' Align the QR code to the left qrStamp.VerticalAlignment = VerticalAlignment.Bottom ' Align the QR code to the bottom ' Load an existing PDF document from a file Dim pdf As PdfDocument = PdfDocument.FromFile("example.pdf") ' Apply the QR code stamp to each page of the loaded PDF document pdf.ApplyStamp(qrStamp) ' To save the stamped PDF document, specify a file path and uncomment the line below ' pdf.SaveAs("stamped_example.pdf"); // Save the stamped PDF document
$vbLabelText   $csharpLabel

Add a Watermark to a PDF

Watermark is a type of stamp for every page that can easily be applied using the ApplyWatermark method:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-23.cs
// Create a PdfDocument object representing the PDF file located at the specified file path. // The PdfDocument class should contain the necessary methods to manipulate PDF files. var pdf = new PdfDocument("/attachments/design.pdf"); // Define HTML content to be used as a watermark. // In this case, the markup includes an example title within an <h1> element. string html = "<h1>Example Title</h1>"; // Define the initial rotation angle of the watermark in degrees. // A rotation of 0 degrees means the watermark will not be rotated. int rotation = 0; // Define the opacity level of the watermark. // The value is given as a percentage, ranging from 0 (fully transparent) to 100 (fully opaque). int watermarkOpacity = 30; // Apply the watermark to the PDF document using the ApplyWatermark method. // This method should be part of the PdfDocument class and take HTML content, rotation, and opacity as arguments. pdf.ApplyWatermark(html, rotation, watermarkOpacity); 
' Create a PdfDocument object representing the PDF file located at the specified file path. ' The PdfDocument class should contain the necessary methods to manipulate PDF files. Dim pdf = New PdfDocument("/attachments/design.pdf") ' Define HTML content to be used as a watermark. ' In this case, the markup includes an example title within an <h1> element. Dim html As String = "<h1>Example Title</h1>" ' Define the initial rotation angle of the watermark in degrees. ' A rotation of 0 degrees means the watermark will not be rotated. Dim rotation As Integer = 0 ' Define the opacity level of the watermark. ' The value is given as a percentage, ranging from 0 (fully transparent) to 100 (fully opaque). Dim watermarkOpacity As Integer = 30 ' Apply the watermark to the PDF document using the ApplyWatermark method. ' This method should be part of the PdfDocument class and take HTML content, rotation, and opacity as arguments. pdf.ApplyWatermark(html, rotation, watermarkOpacity)
$vbLabelText   $csharpLabel

Apply Stamp onto a PDF

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-24.cs
using System.Threading.Tasks; public class PdfDocument { private string filePath; // Constructor to initialize PdfDocument with a file path public PdfDocument(string filePath) { this.filePath = filePath; } // Method to apply a single stamp to one or multiple pages public void ApplyStamp(object stamper, int[] pages = null) { if (pages == null) { // Apply the stamp to all pages } else { // Apply the stamp to specified pages } } // Method to apply multiple stamps to one or multiple pages public void ApplyMultipleStamps(object[] stampArray, int[] pages = null) { if (pages == null) { // Apply stamps to all pages } else { // Apply stamps to specified pages } } // Asynchronous method to apply a single stamp to a specific page public async Task ApplyStampAsync(object stamper, int page) { // Apply stamp asynchronously await Task.CompletedTask; } // Asynchronous method to apply multiple stamps to all pages public async Task ApplyMultipleStampsAsync(object[] stampArray) { // Apply multiple stamps asynchronously await Task.CompletedTask; } // Method to apply a watermark with specific parameters public void ApplyWatermark(string htmlContent, int rotation, int opacity) { // Apply the watermark to the PDF } } // Usage example of the PdfDocument methods: // Create a new PdfDocument instance with the given file path var pdf = new PdfDocument("/assets/example.pdf"); // Placeholder object for the single stamper object myStamper = new object(); // Placeholder array for multiple stamps object[] stampArray = new object[] { }; // Apply one stamp to all pages pdf.ApplyStamp(myStamper); // Apply one stamp to a specific page (page indices often start from 0) pdf.ApplyStamp(myStamper, new[] { 0 }); // Apply one stamp to specific pages pdf.ApplyStamp(myStamper, new[] { 0, 3, 5 }); // Apply a stamp array to all pages pdf.ApplyMultipleStamps(stampArray); // Apply a stamp array to a specific page pdf.ApplyMultipleStamps(stampArray, new[] { 0 }); // Apply a stamp array to specific pages pdf.ApplyMultipleStamps(stampArray, new[] { 0, 3, 5 }); // Use asynchronous methods to apply stamps await pdf.ApplyStampAsync(myStamper, 4); await pdf.ApplyMultipleStampsAsync(stampArray); // Additional Watermark apply method string html = "<h1>Example Title</h1>"; // Ensure proper HTML syntax int rotation = 0; // Rotation angle for the watermark int watermarkOpacity = 30; // Opacity level for the watermark pdf.ApplyWatermark(html, rotation, watermarkOpacity);
Imports System.Threading.Tasks Public Class PdfDocument	Private filePath As String	' Constructor to initialize PdfDocument with a file path	Public Sub New(ByVal filePath As String)	Me.filePath = filePath	End Sub	' Method to apply a single stamp to one or multiple pages	Public Sub ApplyStamp(ByVal stamper As Object, Optional ByVal pages() As Integer = Nothing)	If pages Is Nothing Then	' Apply the stamp to all pages	Else	' Apply the stamp to specified pages	End If	End Sub	' Method to apply multiple stamps to one or multiple pages	Public Sub ApplyMultipleStamps(ByVal stampArray() As Object, Optional ByVal pages() As Integer = Nothing)	If pages Is Nothing Then	' Apply stamps to all pages	Else	' Apply stamps to specified pages	End If	End Sub	' Asynchronous method to apply a single stamp to a specific page	Public Async Function ApplyStampAsync(ByVal stamper As Object, ByVal page As Integer) As Task	' Apply stamp asynchronously	Await Task.CompletedTask	End Function	' Asynchronous method to apply multiple stamps to all pages	Public Async Function ApplyMultipleStampsAsync(ByVal stampArray() As Object) As Task	' Apply multiple stamps asynchronously	Await Task.CompletedTask	End Function	' Method to apply a watermark with specific parameters	Public Sub ApplyWatermark(ByVal htmlContent As String, ByVal rotation As Integer, ByVal opacity As Integer)	' Apply the watermark to the PDF	End Sub End Class ' Usage example of the PdfDocument methods: ' Create a new PdfDocument instance with the given file path Private pdf = New PdfDocument("/assets/example.pdf") ' Placeholder object for the single stamper Private myStamper As New Object() ' Placeholder array for multiple stamps Private stampArray() As Object = {} ' Apply one stamp to all pages pdf.ApplyStamp(myStamper) ' Apply one stamp to a specific page (page indices often start from 0) pdf.ApplyStamp(myStamper, { 0 }) ' Apply one stamp to specific pages pdf.ApplyStamp(myStamper, { 0, 3, 5 }) ' Apply a stamp array to all pages pdf.ApplyMultipleStamps(stampArray) ' Apply a stamp array to a specific page pdf.ApplyMultipleStamps(stampArray, { 0 }) ' Apply a stamp array to specific pages pdf.ApplyMultipleStamps(stampArray, { 0, 3, 5 }) ' Use asynchronous methods to apply stamps Await pdf.ApplyStampAsync(myStamper, 4) Await pdf.ApplyMultipleStampsAsync(stampArray) ' Additional Watermark apply method Dim html As String = "<h1>Example Title</h1>" ' Ensure proper HTML syntax Dim rotation As Integer = 0 ' Rotation angle for the watermark Dim watermarkOpacity As Integer = 30 ' Opacity level for the watermark pdf.ApplyWatermark(html, rotation, watermarkOpacity)
$vbLabelText   $csharpLabel

Using the Length Class for Measurements

Length Class Properties

class Length | └─── double : Value (default : 0) | └─── MeasurementUnit : Unit | Inch | Millimeter | Centimeter | Percentage (default) | Pixel | Points

Creating a Length

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-25.cs
// Define the MeasurementUnit Enum with possible units of measurement. public enum MeasurementUnit { Inch, Pixel, Percent } // The Length struct represents a measurement value with an associated unit. public struct Length { // The value of the measurement. public double Value { get; } // The unit of the measurement. public MeasurementUnit Unit { get; } // Constructor for the Length struct. // If the unit is not provided, it defaults to Percent. public Length(double value = 0, MeasurementUnit unit = MeasurementUnit.Percent) { Value = value; Unit = unit; } // Override the ToString method to provide a string representation of the Length instance. public override string ToString() { return $"{Value} {Unit}"; } } // Example usage of the Length struct with various units. Length length1 = new Length(5, MeasurementUnit.Inch); // 5 inches Length length2 = new Length(25, MeasurementUnit.Pixel); // 25 pixels Length length3 = new Length(); // 0 percent (default value and unit) Length length4 = new Length(20); // 20 percent (default unit) // Displaying the created Length instances. Console.WriteLine(length1); // Outputs: 5 Inch Console.WriteLine(length2); // Outputs: 25 Pixel Console.WriteLine(length3); // Outputs: 0 Percent Console.WriteLine(length4); // Outputs: 20 Percent
' Define the MeasurementUnit Enum with possible units of measurement. Public Enum MeasurementUnit	Inch	Pixel	Percent End Enum ' The Length struct represents a measurement value with an associated unit. Public Structure Length	' The value of the measurement.	Public ReadOnly Property Value() As Double	' The unit of the measurement.	Public ReadOnly Property Unit() As MeasurementUnit	' Constructor for the Length struct.	' If the unit is not provided, it defaults to Percent.	Public Sub New(Optional ByVal value As Double = 0, Optional ByVal unit As MeasurementUnit = MeasurementUnit.Percent)	Me.Value = value	Me.Unit = unit	End Sub	' Override the ToString method to provide a string representation of the Length instance.	Public Overrides Function ToString() As String	Return $"{Value} {Unit}"	End Function End Structure ' Example usage of the Length struct with various units. Private length1 As New Length(5, MeasurementUnit.Inch) ' 5 inches Private length2 As New Length(25, MeasurementUnit.Pixel) ' 25 pixels Private length3 As New Length() ' 0 percent (default value and unit) Private length4 As New Length(20) ' 20 percent (default unit) ' Displaying the created Length instances. Console.WriteLine(length1) ' Outputs: 5 Inch Console.WriteLine(length2) ' Outputs: 25 Pixel Console.WriteLine(length3) ' Outputs: 0 Percent Console.WriteLine(length4) ' Outputs: 20 Percent
$vbLabelText   $csharpLabel

Using Length as a Parameter

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-26.cs
using System; // Define a class to represent measurement lengths public class Length { // Properties to hold the value and unit of the length public double Value { get; set; } public MeasurementUnit Unit { get; set; } // Constructor to initialize the length with a specific value and unit public Length(double value, MeasurementUnit unit) { Value = value; Unit = unit; } // Override ToString to provide a meaningful string representation of the length public override string ToString() { return $"{Value} {Unit}"; } } // Define an enumeration for measurement units public enum MeasurementUnit { // Supported units of measurement Inch, Percentage } // Define a class representing an HTML stamper public class HtmlStamper { // Properties to specify offset values for stamping public Length VerticalOffset { get; set; } public Length HorizontalOffset { get; set; } // This could be further expanded to include additional properties and methods } // Main entry point for the program public class Program { public static void Main() { // Initialize a new instance of HtmlStamper HtmlStamper logoStamper = new HtmlStamper { // Set the vertical offset as a percentage VerticalOffset = new Length(15, MeasurementUnit.Percentage), // Set the horizontal offset in inches HorizontalOffset = new Length(1, MeasurementUnit.Inch) // Additional properties can be set here... }; // Optionally, display the 'logoStamper' offset details to console Console.WriteLine($"Vertical Offset: {logoStamper.VerticalOffset}"); Console.WriteLine($"Horizontal Offset: {logoStamper.HorizontalOffset}"); } }
Imports System ' Define a class to represent measurement lengths Public Class Length	' Properties to hold the value and unit of the length	Public Property Value() As Double	Public Property Unit() As MeasurementUnit	' Constructor to initialize the length with a specific value and unit	Public Sub New(ByVal value As Double, ByVal unit As MeasurementUnit)	Me.Value = value	Me.Unit = unit	End Sub	' Override ToString to provide a meaningful string representation of the length	Public Overrides Function ToString() As String	Return $"{Value} {Unit}"	End Function End Class ' Define an enumeration for measurement units Public Enum MeasurementUnit	' Supported units of measurement	Inch	Percentage End Enum ' Define a class representing an HTML stamper Public Class HtmlStamper	' Properties to specify offset values for stamping	Public Property VerticalOffset() As Length	Public Property HorizontalOffset() As Length	' This could be further expanded to include additional properties and methods End Class ' Main entry point for the program Public Class Program	Public Shared Sub Main()	' Initialize a new instance of HtmlStamper	Dim logoStamper As New HtmlStamper With {	.VerticalOffset = New Length(15, MeasurementUnit.Percentage),	.HorizontalOffset = New Length(1, MeasurementUnit.Inch)	}	' Optionally, display the 'logoStamper' offset details to console	Console.WriteLine($"Vertical Offset: {logoStamper.VerticalOffset}")	Console.WriteLine($"Horizontal Offset: {logoStamper.HorizontalOffset}")	End Sub End Class
$vbLabelText   $csharpLabel

Using Forms in PDFs

Create and Edit Forms

Use IronPDF to create a PDF with embedded form fields:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-27.cs
using System; // Assuming necessary namespaces for PDF rendering and form handling are included // Ensure that the required libraries are referenced in your project // Step 1: Create a PDF with editable forms from HTML using form and input tags // Define the HTML string with input fields for form creation const string formHtml = @" <html> <body> <h2>Editable PDF Form</h2> <form> First name: <br> <input type='text' name='firstname' value=''> <br> Last name: <br> <input type='text' name='lastname' value=''> </form> </body> </html>"; try { // Instantiate a PDF renderer, which supports HTML rendering var renderer = new ChromePdfRenderer(); // Enable the option to create PDF forms from HTML form elements renderer.RenderingOptions.CreatePdfFormsFromHtml = true; // Render the HTML as a PDF and save it to a file renderer.RenderHtmlAsPdf(formHtml).SaveAs("BasicForm.pdf"); } catch (Exception ex) { Console.WriteLine("An error occurred while creating the PDF: " + ex.Message); } // Step 2: Reading and Writing PDF form values try { // Load the PDF document that was previously created var formDocument = PdfDocument.FromFile("BasicForm.pdf"); // Retrieve the form field corresponding to the "firstname" input var firstNameField = formDocument.Form.FindFormField("firstname"); if (firstNameField != null) { // Output the initial value of the "firstname" field Console.WriteLine("First Name Field Value: " + firstNameField.Value); } else { Console.WriteLine("First Name field not found."); } // Retrieve the form field corresponding to the "lastname" input var lastNameField = formDocument.Form.FindFormField("lastname"); if (lastNameField != null) { // Output the initial value of the "lastname" field Console.WriteLine("Last Name Field Value: " + lastNameField.Value); } else { Console.WriteLine("Last Name field not found."); } } catch (Exception ex) { Console.WriteLine("An error occurred while accessing the PDF form fields: " + ex.Message); }
Imports System ' Assuming necessary namespaces for PDF rendering and form handling are included ' Ensure that the required libraries are referenced in your project ' Step 1: Create a PDF with editable forms from HTML using form and input tags ' Define the HTML string with input fields for form creation Private Const formHtml As String = " <html> <body> <h2>Editable PDF Form</h2> <form> First name: <br> <input type='text' name='firstname' value=''> <br> Last name: <br> <input type='text' name='lastname' value=''> </form> </body> </html>" Try	' Instantiate a PDF renderer, which supports HTML rendering	Dim renderer = New ChromePdfRenderer()	' Enable the option to create PDF forms from HTML form elements	renderer.RenderingOptions.CreatePdfFormsFromHtml = True	' Render the HTML as a PDF and save it to a file	renderer.RenderHtmlAsPdf(formHtml).SaveAs("BasicForm.pdf") Catch ex As Exception	Console.WriteLine("An error occurred while creating the PDF: " & ex.Message) End Try ' Step 2: Reading and Writing PDF form values Try	' Load the PDF document that was previously created	Dim formDocument = PdfDocument.FromFile("BasicForm.pdf")	' Retrieve the form field corresponding to the "firstname" input	Dim firstNameField = formDocument.Form.FindFormField("firstname")	If firstNameField IsNot Nothing Then	' Output the initial value of the "firstname" field	Console.WriteLine("First Name Field Value: " & firstNameField.Value)	Else	Console.WriteLine("First Name field not found.")	End If	' Retrieve the form field corresponding to the "lastname" input	Dim lastNameField = formDocument.Form.FindFormField("lastname")	If lastNameField IsNot Nothing Then	' Output the initial value of the "lastname" field	Console.WriteLine("Last Name Field Value: " & lastNameField.Value)	Else	Console.WriteLine("Last Name field not found.")	End If Catch ex As Exception	Console.WriteLine("An error occurred while accessing the PDF form fields: " & ex.Message) End Try
$vbLabelText   $csharpLabel

Fill Existing Forms

Using IronPDF you can easily access all existing form fields in a PDF and fill them for a resave:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-28.cs
// Load a PDF document from a file. var formDocument = PdfDocument.FromFile("BasicForm.pdf"); // Set and read the value of the "firstname" field. var firstNameField = formDocument.Form.FindFormField("firstname"); if (firstNameField != null) { firstNameField.Value = "Minnie"; // Assign a value to the field. Console.WriteLine("FirstNameField value: {0}", firstNameField.Value); // Output the field's value. } else { Console.WriteLine("Error: 'firstname' field not found in the PDF."); } // Set and read the value of the "lastname" field. var lastNameField = formDocument.Form.FindFormField("lastname"); if (lastNameField != null) { lastNameField.Value = "Mouse"; // Assign a value to the field. Console.WriteLine("LastNameField value: {0}", lastNameField.Value); // Output the field's value. } else { Console.WriteLine("Error: 'lastname' field not found in the PDF."); } // Save the modified PDF as a new file. try { formDocument.SaveAs("FilledForm.pdf"); Console.WriteLine("Document saved successfully as 'FilledForm.pdf'."); } catch (Exception ex) { Console.WriteLine("Error in saving document: {0}", ex.Message); }
' Load a PDF document from a file. Dim formDocument = PdfDocument.FromFile("BasicForm.pdf") ' Set and read the value of the "firstname" field. Dim firstNameField = formDocument.Form.FindFormField("firstname") If firstNameField IsNot Nothing Then	firstNameField.Value = "Minnie" ' Assign a value to the field.	Console.WriteLine("FirstNameField value: {0}", firstNameField.Value) ' Output the field's value. Else	Console.WriteLine("Error: 'firstname' field not found in the PDF.") End If ' Set and read the value of the "lastname" field. Dim lastNameField = formDocument.Form.FindFormField("lastname") If lastNameField IsNot Nothing Then	lastNameField.Value = "Mouse" ' Assign a value to the field.	Console.WriteLine("LastNameField value: {0}", lastNameField.Value) ' Output the field's value. Else	Console.WriteLine("Error: 'lastname' field not found in the PDF.") End If ' Save the modified PDF as a new file. Try	formDocument.SaveAs("FilledForm.pdf")	Console.WriteLine("Document saved successfully as 'FilledForm.pdf'.") Catch ex As Exception	Console.WriteLine("Error in saving document: {0}", ex.Message) End Try
$vbLabelText   $csharpLabel

Conclusion

The list of examples above demonstrates that IronPDF has key features that work out-of-the-box when it comes to editing PDFs.

If you would like to make a feature request or have any general questions about IronPDF or licensing, please contact our support team. We will be more than happy to assist you.

Frequently Asked Questions

What is a library that simplifies PDF editing functions in C#?

IronPDF is a library that simplifies PDF editing functions in C#, offering features like adding signatures, HTML footers, watermarks, annotations, and more.

How can I add pages to an existing PDF?

You can add pages to an existing PDF using IronPDF by loading a PDF document, invoking the AddPage method, and saving the modified PDF.

How do I merge multiple PDFs into a single document?

To merge PDFs, load each document using PdfDocument.FromFile, use the Merge method to combine them, and save the resulting document as a new file.

Can a library be used to add digital signatures to PDF documents?

Yes, IronPDF supports adding digital signatures to PDFs using X509Certificate2 digital certificates, which ensures document fidelity.

How do I add headers and footers to a PDF?

Headers and footers can be added using the HtmlHeaderFooter or TextHeaderFooter classes in IronPDF. You can specify HTML content or text and set properties like height.

Is it possible to compress PDF files?

Yes, IronPDF allows you to compress PDFs by reducing the size of embedded images using the CompressImages method.

How can I stamp a watermark on a PDF?

To add a watermark, use the ApplyWatermark method in IronPDF with a TextStamper object configured with the desired text and properties like opacity and rotation.

What methods are available for adding annotations to PDFs?

IronPDF provides options to add text annotations and other customizations using annotation objects added to specific pages.

Can a library handle PDF form creation and filling?

Yes, IronPDF can create PDFs with form fields and fill existing form fields programmatically.

How do I replace text in a PDF?

Use the ReplaceTextOnPage method in IronPDF to find and replace text within a specific page of a PDF document.

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.