How to Edit PDFs in C#

Introduction

Iron Software has simplified various PDF editing functions into easy-to-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 seamless deployment to any supported environment or platform.

IronPDF boasts numerous features for editing PDFs. In this tutorial article, we will walk through some of the major ones, providing 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

Start using IronPDF in your project today with a free trial.

First Step:
green arrow pointer
NuGet Install with NuGet

PM >  Install-Package IronPdf

Check out IronPDF on NuGet for quick installation. With over 10 million downloads, it’s transforming PDF development with C#. You can also download the DLL or Windows installer.

Edit Document Structure

Access PDF DOM Object

Manipulating and accessing the PDF objects is quick and straightforward. IronPDF simplifies how developers interact with DOM Objects by making them familiar with how to manipulate a web page's DOM—allowing developers to access and manipulate various elements, such as text, programmatically.

:path=/static-assets/pdf/content-code-examples/how-to/access-pdf-dom-object.cs
using IronPdf;
using System.Linq;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Create a PDF from a URL
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");

// Access DOM Objects
var objects = pdf.Pages.First().ObjectModel;
Imports IronPdf
Imports System.Linq

' Instantiate Renderer
Private renderer As New ChromePdfRenderer()

' Create a PDF from a URL
Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")

' Access DOM Objects
Private objects = pdf.Pages.First().ObjectModel
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Save & Export Documents

To save and export documents, IronPDF allows users to quickly save the edited document PdfDocument.SaveAs to the disk while also allowing exports to other formats, such as Binary Data and Memory Streams.

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Load PDFs from Memory

IronPDF perfectly integrates with existing C# .NET applications; we can load and create PDF files from MemoryStreams through the MemoryStream object.

:path=/static-assets/pdf/content-code-examples/how-to/pdf-memory-stream-from-stream.cs
using IronPdf;
using System.IO;

// Read PDF file as stream
var fileByte = File.ReadAllBytes("sample.pdf");

// Instantiate PDF object from stream
PdfDocument pdf = new PdfDocument(fileByte);
Imports IronPdf
Imports System.IO

' Read PDF file as stream
Private fileByte = File.ReadAllBytes("sample.pdf")

' Instantiate PDF object from stream
Private pdf As New PdfDocument(fileByte)
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Export PDFs to Memory

Similarly, we can also export PDFs to MemoryStream in C# .NET through the MemoryStream object.

:path=/static-assets/pdf/content-code-examples/how-to/pdf-to-memory-stream-to-stream.cs
using IronPdf;
using System.IO;

var renderer = new ChromePdfRenderer();

// Convert the URL into PDF
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");

// Export PDF as Stream
MemoryStream pdfAsStream = pdf.Stream;

// Export PDF as Byte Array
byte[] pdfAsByte = pdf.BinaryData;
Imports IronPdf
Imports System.IO

Private renderer = New ChromePdfRenderer()

' Convert the URL into PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")

' Export PDF as Stream
Private pdfAsStream As MemoryStream = pdf.Stream

' Export PDF as Byte Array
Private pdfAsByte() As Byte = pdf.BinaryData
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Edit Document Text

Parse PDFs in C

Extracting text from a PDF is quick and easy with IronPDF. Just use the ExtractAllText method to pull all the text from every page, allowing you to access and utilize your document's content effortlessly. This powerful feature enhances productivity and streamlines your workflow!

:path=/static-assets/pdf/content-code-examples/how-to/csharp-parse-pdf-parse-pdf.cs
using IronPdf;

// Select the desired PDF File
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Extract all text from an pdf
string allText = pdf.ExtractAllText();

// Extract all text from page 1
string page1Text = pdf.ExtractTextFromPage(0);
Imports IronPdf

' Select the desired PDF File
Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Extract all text from an pdf
Private allText As String = pdf.ExtractAllText()

' Extract all text from page 1
Private page1Text As String = pdf.ExtractTextFromPage(0)
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Extract Text & Images

With IronPDF, you’re not just limited to extracting text—it's also incredibly easy to pull images out of your PDFs! With the ExtractAllImages feature, you can swiftly capture all the visuals you need.

:path=/static-assets/pdf/content-code-examples/how-to/extract-text-and-images-extract-image.cs
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Extract images
var images = pdf.ExtractAllImages();

for(int i = 0; i < images.Count; i++)
{
    // Export the extracted images
    images[i].SaveAs($"images/image{i}.png");
}
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Extract images
Private images = pdf.ExtractAllImages()

For i As Integer = 0 To images.Count - 1
	' Export the extracted images
	images(i).SaveAs($"images/image{i}.png")
Next i
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Redact Texts & Regions

In scenarios where we need to safeguard sensitive information by redacting it, we have a powerful tool at our fingertips: RedactTextonAllPages. With this feature, we can effortlessly identify and conceal every instance of a specific keyword throughout the entire PDF. It’s an efficient way to ensure that confidential details remain protected while still allowing us to share the document with confidence.

:path=/static-assets/pdf/content-code-examples/how-to/redact-text-redact-text.cs
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("novel.pdf");

// Redact 'Alaric' phrase from all pages
pdf.RedactTextOnAllPages("Alaric");

pdf.SaveAs("redacted.pdf");
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("novel.pdf")

' Redact 'Alaric' phrase from all pages
pdf.RedactTextOnAllPages("Alaric")

pdf.SaveAs("redacted.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Replace Text in PDF

To enhance your PDF documents using IronPDF, you can easily replace text throughout the entire file. By utilizing the ReplaceTextonAllPages function, you can provide the oldText that needs to be replaced along with the newText that will serve as its substitute. This method efficiently updates all instances of the oldText across the document, ensuring a consistent and professional appearance.

:path=/static-assets/pdf/content-code-examples/how-to/find-replace-text-all-page.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>");

string oldText = ".NET6";
string newText = ".NET7";

// Replace text on all pages
pdf.ReplaceTextOnAllPages(oldText, newText);

pdf.SaveAs("replaceText.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>")

Private oldText As String = ".NET6"
Private newText As String = ".NET7"

' Replace text on all pages
pdf.ReplaceTextOnAllPages(oldText, newText)

pdf.SaveAs("replaceText.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Enchance PDF Design

Add & Edit Annotations

IronPDF offers extensive customization options for PDF annotations, allowing users to add "sticky note" style comments directly to PDF pages. Through the TextAnnotation class, annotations can be added programmatically, featuring advanced options such as sizing, opacity, icon selection, and editing capabilities.

:path=/static-assets/pdf/content-code-examples/how-to/annotation-add-annotation.cs
using IronPdf;
using IronPdf.Annotations;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Annotation</h1>");

// Create a PDF annotation object on a specified page index
TextAnnotation annotation = new TextAnnotation(0)
{
    Title = "This is the title",
    Contents = "This is the long 'sticky note' comment content...",
    X = 50,
    Y = 700,
};

// Add the annotation
pdf.Annotations.Add(annotation);
pdf.SaveAs("annotation.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Stamp Text & Images

IronPDF provides extensive options for customizing how to stamp text and images onto a PDF. In this example, we'll use the TextStamper class to apply a stamp to the PDF using the ApplyStamp method, as shown below.

:path=/static-assets/pdf/content-code-examples/how-to/stamp-text-image-stamp-text.cs
using IronPdf;
using IronPdf.Editing;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>");

// Create text stamper
TextStamper textStamper = new TextStamper()
{
    Text = "Text Stamper!",
    FontFamily = "Bungee Spice",
    UseGoogleFont = true,
    FontSize = 30,
    IsBold = true,
    IsItalic = true,
    VerticalAlignment = VerticalAlignment.Top,
};

// Stamp the text stamper
pdf.ApplyStamp(textStamper);

pdf.SaveAs("stampText.pdf");
Imports IronPdf
Imports IronPdf.Editing

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>")

' Create text stamper
Private textStamper As New TextStamper() With {
	.Text = "Text Stamper!",
	.FontFamily = "Bungee Spice",
	.UseGoogleFont = True,
	.FontSize = 30,
	.IsBold = True,
	.IsItalic = True,
	.VerticalAlignment = VerticalAlignment.Top
}

' Stamp the text stamper
pdf.ApplyStamp(textStamper)

pdf.SaveAs("stampText.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Custom Watermarks

We can also employ the ApplyWatermark method to seamlessly integrate a watermark into both newly rendered PDFs and existing documents. This functionality enables enhanced brand recognition, ensuring that your materials convey a professional image.

:path=/static-assets/pdf/content-code-examples/how-to/custom-watermark-apply-watermark.cs
using IronPdf;

string watermarkHtml = @"
<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>";

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>");

// Apply watermark
pdf.ApplyWatermark(watermarkHtml);

pdf.SaveAs("watermark.pdf");
Imports IronPdf

Private watermarkHtml As String = "
<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>"

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>")

' Apply watermark
pdf.ApplyWatermark(watermarkHtml)

pdf.SaveAs("watermark.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Backgrounds & Foregorunds

In addition to watermarks and stamps, we can also add a background to customize your PDF using AddBackgroundPdf entirely.

:path=/static-assets/pdf/content-code-examples/how-to/background-foreground-background.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Main HTML content</h1>");

// Render background
PdfDocument background = renderer.RenderHtmlAsPdf("<body style='background-color: cyan;'></body>");

// Add background
pdf.AddBackgroundPdf(background);

pdf.SaveAs("addBackground.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Main HTML content</h1>")

' Render background
Private background As PdfDocument = renderer.RenderHtmlAsPdf("<body style='background-color: cyan;'></body>")

' Add background
pdf.AddBackgroundPdf(background)

pdf.SaveAs("addBackground.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Draw Text & Bitmap

Drawing text on PDFs is intuitive and straightforward; we use DrawText and provide it with the necessary parameters. In this example, we are adding the new phrase Some text with the font Times New Roman.

:path=/static-assets/pdf/content-code-examples/how-to/draw-text-and-bitmap-draw-text.cs
using IronPdf;
using IronSoftware.Drawing;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");

// Draw text on PDF
pdf.DrawText("Some text", FontTypes.TimesNewRoman.Name, FontSize: 12, PageIndex: 0, X: 100, Y: 100, Color.Black, Rotation: 0);

pdf.SaveAs("drawText.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Draw Line & Rectangle

IronPDF also supports drawing lines on the PDF. We first create the start and end points by initializing two PointF classes, then apply them with the DrawLine method, as shown below.

:path=/static-assets/pdf/content-code-examples/how-to/draw-line-and-rectangle-draw-line.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");

// Configure the required parameters
int pageIndex = 0;
var start = new IronSoftware.Drawing.PointF(200,150);
var end = new IronSoftware.Drawing.PointF(1000,150);
int width = 10;
var color = new IronSoftware.Drawing.Color("#000000");

// Draw line on PDF
pdf.DrawLine(pageIndex, start, end, width, color);

pdf.SaveAs("drawLine.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>testing</h1>")

' Configure the required parameters
Private pageIndex As Integer = 0
Private start = New IronSoftware.Drawing.PointF(200,150)
Private [end] = New IronSoftware.Drawing.PointF(1000,150)
Private width As Integer = 10
Private color = New IronSoftware.Drawing.Color("#000000")

' Draw line on PDF
pdf.DrawLine(pageIndex, start, [end], width, color)

pdf.SaveAs("drawLine.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Rotate Text and Pages

To rotate the PDF pages, we can use the SetPageRotation method to rotate specific pages. In the example below, we are only rotating pages 2 to 4, leaving page 1 unchanged to showcase the capabilities.

:path=/static-assets/pdf/content-code-examples/how-to/rotating-text-set-page-rotation.cs
using IronPdf;
using IronPdf.Rendering;
using System.Linq;

// Import PDF
PdfDocument pdf = PdfDocument.FromFile("multi-page.pdf");

// Set rotation for a single page
pdf.SetPageRotation(0, PdfPageRotation.Clockwise90);

// Set rotation for multiple pages
pdf.SetPageRotations(Enumerable.Range(1,3), PdfPageRotation.Clockwise270);

// Set rotation for the entire document
pdf.SetAllPageRotations(PdfPageRotation.Clockwise180);

pdf.SaveAs("rotated.pdf");
Imports IronPdf
Imports IronPdf.Rendering
Imports System.Linq

' Import PDF
Private pdf As PdfDocument = PdfDocument.FromFile("multi-page.pdf")

' Set rotation for a single page
pdf.SetPageRotation(0, PdfPageRotation.Clockwise90)

' Set rotation for multiple pages
pdf.SetPageRotations(Enumerable.Range(1,3), PdfPageRotation.Clockwise270)

' Set rotation for the entire document
pdf.SetAllPageRotations(PdfPageRotation.Clockwise180)

pdf.SaveAs("rotated.pdf")
$vbLabelText   $csharpLabel

For a list of available enums regarding the rotation angle, please refer to here.

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Transform PDF Pages

Aside from rotations, we can also transform the pdf pages by providing a range of parameters. In the example below, we select the first page of the PDF and, using Transform, move the contents of the first page 50 points to the right and down and scale it to 80% of its original size.

:path=/static-assets/pdf/content-code-examples/how-to/transform-pdf-pages-transform-pdf.cs
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("basic.pdf");

pdf.Pages[0].Transform(50, 50, 0.8, 0.8);

pdf.SaveAs("transformPage.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

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.