iText Knowledge Base

In our previous post, we talked about iTextPdf API for working with PDF files using C#/VB.NET in .NET applications. The API lets you create, edit and manipulate PDF documents without going into any internal file format details of PDF file format. Using iTextPdf is easy to work with and with just a few lines of code, you can start creating, reading, and manipulating PDF files.

In this article, we will talk about using iTextPdf in .NET application to create, read, and save PDF files programmatically in our C# application. So, let’s get started and have a look at how we can create a PDF in C#.

iTextPdf Installation

You can install iTextPdf API either from NuGet or from iText Artifactory Server. Before you can create your C# application for using the iTextPdf API, you need to install it from either of these sources. You can refer to the instructions article for installing iTextPdf API for setting up your console application for this purpose.

Overview of Main iTextPdf API Classes

Some of the main iTextPdf classes are as follows.

PdfDocument

Every PDF document created with iTextPdf is initiated using an object of the PdfDocument class.

PdfWriter

PdfWriter class is responsible for writing the PDF content to a destination, such as a file or a stream. It provides the functionality to create a PDF document and specify the output destination. Some key features and responsibilities of PdfWriter class are as follows.

Destination ConfigurationThe PdfWriter constructor allows you to specify the output destination for the PDF content. It can accept parameters like a file path, a Stream object, or an instance of IOutputStreamCounter. This determines where the PDF content will be written.
PDF Document CreationWhen you create a new instance of PdfWriter, it automatically creates a new PdfDocument object associated with it. The PdfDocument represents the logical structure of a PDF file and provides methods to manipulate its content.
PDF Compression and Version ControlThe PdfWriter class allows you to configure various aspects of the PDF file, such as compression settings and PDF version compatibility.
Writing PDF ContentOnce you have a PdfWriter instance, you can use it to write content to the associated PdfDocument. You can add pages, create annotations, add text, images, and other graphical elements to the PDF document using the provided methods.
Closing the WriterAfter you finish writing the PDF content, it’s important to close the PdfWriter to ensure the document is finalized and any necessary resources are released.

Paragraph

The Paragraph class represents a paragraph of text in a PDF document. It is used to add textual content to a PDF document. Here are some key features and responsibilities of the Paragraph class:

Text ContentThe primary purpose of the Paragraph class is to hold and display textual content within a PDF document. You can pass a string or any other text representation to the Paragraph constructor to initialize its content.
Text FormattingThe Paragraph class allows you to apply various formatting options to the text, such as font size, font family, text color, bold, italic, underline, and more. You can use methods like SetFontSize(), SetFont(), SetBold(), SetItalic(), SetUnderline(), etc., to specify the desired formatting.
Alignment and IndentationThe Paragraph class provides methods to set the alignment of the text within the paragraph. You can align the text to the left, right, or center, or justify it. Additionally, you can apply indentation to control the left and right margins of the paragraph.
Inline ElementsApart from plain text, you can also add inline elements within a Paragraph. For example, you can include phrases or words with different formatting styles, add hyperlinks, insert images, or include other elements supported by iText.
NestingYou can nest multiple paragraphs within each other or combine them with other iText elements like tables, lists, or chunks to create complex document structures.
Integration with DocumentThe Paragraph instances can be added to the Document object using the Add() method. This allows you to include paragraphs in your PDF document at the desired location.

How to Create a PDF File in C#?

Now that we have a good idea about iTextPdf and its main classes, let’s proceed to create a PDF document in C# using iTextPdf API. This can be done with just a few steps as below.

  1. Create a New Project in Visual Studio.
  2. Install the iTextPdf C# Library using the NuGet Package Manager.
  3. Create instances of PdfDocument and PdfWriter classes
  4. Create instances of Document and Paragraph classes
  5. Close the document using Document.Close() method

C# Code Snippet to Generate PDF File

The following C# code can be used to generate a PDF file.

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;

class Program
{
    static void Main()
    {
        // Specify the output file path
        string outputPath = "example.pdf";
        // Create a new PDF document
        PdfWriter writer = new PdfWriter(outputPath);
        PdfDocument pdf = new PdfDocument(writer);
        // Create a document instance
        Document document = new Document(pdf);
        // Add content to the document
        document.Add(new Paragraph("Hello, World!"));
        // Close the document
        document.Close();
        Console.WriteLine("PDF created successfully.");
    }
}

How to Update a PDF File in C#?

Updating/Editing a PDF file in C# can easily be done using iTextPdf.

  1. Open the existing PDF document using a PdfReader object.
  2. Create a PdfWriter object with a new or modified output destination (such as a file or a stream).
  3. Create a PdfDocument object using both the PdfReader and PdfWriter objects.
  4. Access the existing pages and content of the document using the PdfDocument instance.
  5. Make the necessary modifications to the document, such as adding or removing content, updating text, modifying annotations, etc.
  6. Close the PdfDocument, which automatically closes the associated PdfReader and PdfWriter as well, and saves the changes to the output destination.

C# Code Snippet to Update PDF File

The following C# code can be used to update a PDF file.

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;

class Program
{
    static void Main()
    {
        string filePath = "existing.pdf";
        string outputPath = "updated.pdf";
        // Open the existing PDF document
        PdfReader reader = new PdfReader(filePath);
        // Create a new PDF document with modified output destination
        PdfWriter writer = new PdfWriter(outputPath);
        // Create a PdfDocument object with both the reader and writer
        PdfDocument pdfDoc = new PdfDocument(reader, writer);
        // Access the first page of the document
        PdfPage firstPage = pdfDoc.GetPage(1);
        // Create a document instance for the page
        Document document = new Document(pdfDoc, firstPage);
        // Add a new paragraph to the document
        document.Add(new Paragraph("This is a new paragraph added to the existing PDF."));
        // Close the document, which saves the changes
        document.Close();
        // Close the reader
        reader.Close();
        Console.WriteLine("PDF updated successfully.");
    }
}

Conclusion

In this article, we explored the iTextPdf API for .NET to learn about creating and manipulating PDF files from within our .NET application. The API is open-source and is hosted on GitHub repository as iText-dotnet. In our upcoming blogs, we’ll further explore this API to work with different components of a PDF document such as tables, images, annotations, redacted pdf, and many others. So stay tuned.