Blog post

How to edit a PDF programmatically with C#

Hulya Masharipov Hulya Masharipov
Illustration: How to edit a PDF programmatically with C#

In this blog post, we’ll demonstrate how to edit a PDF document programmatically using C#, focusing on the practical aspects of editing PDFs. After reading it, you’ll know how to add annotations, add new pages, and change the pages of a PDF.

Introduction to PDF editing in C#

PDF editing is a crucial feature in many C# applications, allowing users to modify and customize PDF documents according to their needs. With the rise of digital documentation, PDF editing has become an essential aspect of various industries, including finance, healthcare, and education. Whether it’s adding annotations, merging documents, or extracting specific pages, the ability to edit PDF files programmatically can significantly enhance the functionality of your application.

Choosing the right PDF library is paramount to achieving efficient and effective PDF editing. A robust PDF library not only simplifies the process of manipulating PDFs, but it also ensures compatibility with various file formats and provides a comprehensive set of features. The following sections will delve deeper into selecting the best PDF library for your needs and explore advanced features and security measures to consider when working with PDF documents in C#.

Choosing a PDF library for C#

When it comes to editing PDF documents in C#, selecting the right PDF library is crucial. A good PDF library should offer a comprehensive set of features, including PDF creation, editing, conversion, and manipulation. It should also be user-friendly, efficient, and compatible with various file formats. One such library that stands out is Nutrient, a powerful PDF library offering a wide range of features.

Nutrient .NET SDK

[Nutrient .NET SDK][] is a feature-rich PDF library that enables developers to view, edit, and annotate PDFs with ease. It supports various file formats and includes advanced capabilities like digital signatures, form filling, and optical character recognition (OCR). Nutrient also provides robust tools for document collaboration, ensuring a seamless user experience across different platforms. Additionally, it’s highly customizable, making it an excellent choice for complex PDF editing tasks.

Nutrient can be a perfect fit for applications requiring a high level of customization and functionality in handling PDF documents.

Setting up Nutrient .NET SDK

To get started with Nutrient .NET SDK in your C# project, follow the steps outlined below.

Installing GdPicture.NET SDK

  1. Download the latest release of GdPicture.NET from here.

  2. Once downloaded, run the installation wizard to guide you through the process.

  3. We recommend installing the toolkit at a destination like C:\GdPicture.NET\ for easy access.

Adding GdPicture.NET to your application

  1. Open Visual Studio and create a new C# project (or use an existing one).

  2. Go to Project > Manage NuGet Packages.

  3. In the Package source field, select nuget.org.

  4. Search for GdPicture in the Browse tab and install GdPicture.API (recommended for .NET 6.0 or newer).

  5. Once installed, import the GdPicture.NET namespace by adding the following to your C# files:

using GdPicture14;

Loading PDF files with GdPicture.NET

One of the standout features of GdPicture.NET is its flexible file loading. Whether you’re accessing PDFs from a local machine, a byte array, a URL, or even from a memory stream, GdPicture.NET makes it straightforward.

Loading a PDF from local storage

To load a PDF file from your local storage, initialize a new instance of GdPicturePDF and specify the file path:

using GdPicturePDF gdpicturePDF2 = new GdPicturePDF();
// Load a PDF document from the specified path without loading it to memory.
gdpicturePDF2.LoadFromFile(@"C:\temp\source.pdf");

using GdPicturePDF gdpicturePDF1 = new GdPicturePDF();
// Load a PDF document from the specified path into memory.
gdpicturePDF1.LoadFromFile(@"C:\temp\source.pdf", true);

With this, you’ve successfully loaded the PDF, and it’s ready for manipulation, viewing, or annotation.

Working with password-protected PDFs

If your PDF is password-protected, GdPicture.NET can handle both user passwords (for viewing) and owner passwords (for editing or printing). Here’s how to open a password-encrypted PDF document:

using GdPicturePDF gdpicturePDF = new GdPicturePDF();
// Load a password-protected PDF document.
gdpicturePDF.LoadFromFile(@"C:\temp\source.pdf");
// Check if the file is encrypted.
if (gdpicturePDF.IsEncrypted())
{
    // Set the correct password for the PDF document.
    gdpicturePDF.SetPassword("user");
    // Check if the file is still encrypted.
    Console.WriteLine(gdpicturePDF.IsEncrypted());
}

Annotating PDF files in C#

Annotations add another layer of interactivity and functionality to PDFs. With GdPicture.NET, you can create, edit, and manage various types of annotations, such as:

  • Text annotations — Comments or notes in text boxes

  • Highlighting and underlining — Emphasize key text

  • Shapes — Add rectangles, circles, and custom shapes

  • Links — Redirect to other pages, files, or external URLs

Steps to create an annotation in a PDF using C#

To create an annotation in a PDF, you’ll need to set up a few configuration details, such as defining the origin, measurement units, and text properties. Here’s how to do it:

  1. Initialize GdPicturePDF — Start by creating a GdPicturePDF object.

  2. Load the PDF — Use the LoadFromFile method to load your existing PDF file.

  3. Set the coordinate system — Define the coordinate system’s origin using the SetOrigin method with the PDFOrigin enumeration.

  4. Set the measurement unit — Specify dimensions and positioning with the SetMeasurementUnit method using the PdfMeasurementUnit enumeration.

  5. Select the page — Choose the page where the annotation will appear using the SelectPage method.

  6. Set the font type — Customize the font for text annotations (optional, but useful if adding text).

  7. Add the annotation — Choose from several annotation methods, such as AddFreeTextAnnotation, AddSquareAnnotation, AddCircleAnnotation, and more.

  8. Save the PDF — Finally, save your modified PDF with SaveToFile.

Here’s a practical example using the steps above to add a free text annotation to a PDF:

using GdPicture14;

GdPicturePDF gdpicturePDF = new GdPicturePDF();

// Load the PDF file.
gdpicturePDF.LoadFromFile(@"C:\temp\source.pdf");

// Set the origin of the coordinate system.
gdpicturePDF.SetOrigin(PdfOrigin.PdfOriginTopLeft);

// Set the measurement unit to centimeters.
gdpicturePDF.SetMeasurementUnit(PdfMeasurementUnit.PdfMeasurementUnitCentimeter);

// Select the first page.
gdpicturePDF.SelectPage(1);

// Define font properties for the annotation text.
float fontSize = 16;
string fontResName = gdpicturePDF.AddStandardFont(PdfStandardFont.PdfStandardFontHelvetica);
string text = "Text annotation example.";

// Get text dimensions.
float textWidth = gdpicturePDF.GetTextWidth(fontResName, fontSize, text);
float textHeight = gdpicturePDF.GetTextHeight(fontResName, fontSize, false);

// Add the free text annotation.
int annotIndex = gdpicturePDF.AddFreeTextAnnotation(
    1,                 // x-coordinate
    2,                 // y-coordinate
    textWidth + 0.5f,  // annotation width
    textHeight + 0.5f, // annotation height
    true,              // border visibility
    "Annotation Example", // title
    "Example",            // subject
    text,                 // content text
    fontResName,          // font resource name
    fontSize,             // font size
    0,                    // font style
    0,                    // text color R
    200,                  // text color G
    100,                  // text color B
    100,                  // background color R
    100,                  // background color G
    100                   // background color B
);

// Save the modified PDF document.
gdpicturePDF.SaveToFile(@"C:\temp\output.pdf");
  • Setting the origin — Setting the origin with PdfOriginTopLeft determines that all annotations will be positioned relative to the top-left corner of the page.

  • Measurement units — Using PdfMeasurementUnitCentimeter makes it easy to specify dimensions in centimeters, which can help when working with print-ready documents.

  • Annotation properties — The AddFreeTextAnnotation method allows customization, including text position, size, color, and font. Here, we set the font to Helvetica and chose RGB color values for both the text and background.

Annotation types in GdPicture.NET

In addition to free text annotations, GdPicture.NET provides a variety of annotation types:

Each of these methods returns an integer, representing the annotation index. This index is useful for future reference if you need to modify or delete the annotation later on.

Saving the document

After creating and configuring your annotations, remember to save the document with SaveToFile. This ensures all annotations are embedded into the PDF and ready for use.

Conclusion

Working with PDFs in C# becomes much more powerful with Nutrient .NET SDK. From loading files of all types to adding dynamic annotations, the SDK simplifies document management for developers. Whether you’re developing an internal tool or a customer-facing application, Nutrient .NET SDK’s rich feature set makes it a top choice for PDF handling in .NET projects.

Nutrient .NET SDK is a powerful PDF library that offers a wide range of advanced features for PDF manipulation. Getting started with it is simple, and what we show here is just a small taste of all the features the SDK contains!

For more details on how to get started with Nutrient .NET SDK, visit the official documentation.

FAQ

Here are a few frequently asked questions about working with PDFs in C#.

How can I add annotations to a PDF in C#? You can add annotations to a PDF in C# using a library like Nutrient, which provides methods for adding text, shapes, and hyperlinks to PDF documents.
What features should I look for in a PDF editing library for C#? Look for features like PDF creation, annotation, text extraction, page manipulation, and support for various file formats.
Is it possible to edit password-protected PDFs in C#? Yes, you can edit password-protected PDFs by providing the correct password for viewing or editing using compatible libraries.
Can I load PDFs from different sources in a C# application? Yes, with libraries like Nutrient, you can load PDFs from local storage, URLs, byte arrays, and streams.
Does Nutrient support adding custom shapes in PDF annotations? Yes, Nutrient allows adding various shapes, including rectangles, circles, and custom annotations.
Author
Hulya Masharipov
Hulya Masharipov Technical Writer

Hulya is a frontend web developer and technical writer at Nutrient who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

Explore related topics

Free trial Ready to get started?
Free trial