Generating a PDF Document Using C#, .NET, and iText 7

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

By Chandra Kudumula

Introduction

This article is about generating PDF documents using C#, .NET, and the iText library. I had a requirement to generate an invoice as a PDF document for one of the projects I worked on. In my research, I came to know about iText. iText is a library for creating and manipulating PDF files in .NET and Java. If you are struggling with C#, consider checking out the TechRepublic Academy.

Prerequisites

Setting Up the Project

Step 1: Create the Console App Using Visual Studio

In Visual Studio, go to File -> New -> Project.

On the “New Project window”, select the Console App(.NET Framework) and give the project a name, as shown in Figure 1.

Selecting the Console App(.NET Framework)
Figure 1: Selecting the Console App(.NET Framework)

Step 2: Install iText 7 Using “Manage NuGet Packages…”

Right-click the project name and select “Manage NuGet Packages…”. You can see this in Figure 2.

Selecting NuGet Packages
Figure 2: Selecting NuGet Packages

Select “Browse” and, in the search box, type itext7 and select itext7 from the searched results and install (see Figure 3).

Selecting itext7
Figure 3: Selecting itext7

Following are the helpful classes and methods to generate the PDF document:

  • PdfWriter: To pass the file name and write content to the document.
  • PdfDocument: In-memory representation of the PDF document. It will open a PDF document in writing mode.
  • Document: Creates a document from in-memory PdfDocument.
  • Paragraph: Creates a paragraph, initialized with some text.
  • SetFontSize: Sets the font size of the text.
  • SetTextAlignment: Sets the text alignment, such as Left, Right, Center, and so forth.

I will add a Header, SubHeader, Line Separator, Image, Table, Hyperlink, and finally page numbers to the PDF document.

A. Adding a Header

Add a header to the PDF document. Header Content is center aligned to the document and I set the font size to 20. We can achieve this by creating a paragraph object. Following is the code snippet to create a paragraph object and add it to the document object. Finally, we need to close the document object by calling the Close() method.

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

namespace GeneratePdfDemo
{
   class Program
   {
      static void Main(string[] args)
      {
         // Must have write permissions to the path folder
         PdfWriter writer = new PdfWriter("C:\\demo.pdf");
         PdfDocument pdf = new PdfDocument(writer);
         Document document = new Document(pdf);
         Paragraph header = new paragraph("HEADER")
            .SetTextAlignment(TextAlignment.CENTER)
            .SetFontSize(20);

         document.Add(header);
         document.Close();
      }
   }
}

Run the program and go to the path specified in PdfWriter and open the PDF document. Figure 4 is the image of a PDF document with header text.

Showing the header text
Figure 4: Showing the header text

B. Creating a Sub Header

Create a Sub Header with text alignment center and set the font size to 15. Add this Sub Header to the document object, as shown in Figure 5.

Paragraph subheader = new Paragraph("SUB HEADER")
   .SetTextAlignment(TextAlignment.CENTER)
   .SetFontSize(15);
document.Add(subheader);

Creating the Sub Header
Figure 5: Creating the Sub Header

C. Adding a Horizontal Separator Line

Add a horizontal line using Line Separator. This is shown in Figure 6.

         // Line separator
         LineSeparator ls = new LineSeparator(new SolidLine());
         document.Add(ls);

Creating the separator line
Figure 6: Creating the separator line

D. Adding an Image

Add an Image to the PDF document by using an Image instance (see Figure 7).

         // Add image
         Image img = new Image(ImageDataFactory
            .Create(@"..\..\image.jpg"))
            .SetTextAlignment(TextAlignment.CENTER);
         document.Add(img);

Adding an image
Figure 7: Adding an image

E. Creating a Table

Create a Table and add it to the document, as shown in Figure 8.

         // Table
            Table table = new Table(2, false);
               Cell cell11 = new Cell(1, 1)
                  .SetBackgroundColor(ColorConstants.GRAY)
                  .SetTextAlignment(TextAlignment.CENTER)
                  .Add(new Paragraph("State"));
               Cell cell12 = new Cell(1, 1)
                  .SetBackgroundColor(ColorConstants.GRAY)
                  .SetTextAlignment(TextAlignment.CENTER)
                  .Add(new Paragraph("Capital"));

               Cell cell21 = new Cell(1, 1)
                  .SetTextAlignment(TextAlignment.CENTER)
                  .Add(new Paragraph("New York"));
               Cell cell22 = new Cell(1, 1)
                  .SetTextAlignment(TextAlignment.CENTER)
                  .Add(new Paragraph("Albany"));

               Cell cell31 = new Cell(1, 1)
                  .SetTextAlignment(TextAlignment.CENTER)
                  .Add(new Paragraph("New Jersey"));
               Cell cell32 = new Cell(1, 1)
                  .SetTextAlignment(TextAlignment.CENTER)
                  .Add(new Paragraph("Trenton"));

               Cell cell41 = new Cell(1, 1)
                  .SetTextAlignment(TextAlignment.CENTER)
                  .Add(new Paragraph("California"));
               Cell cell42 = new Cell(1, 1)
                  .SetTextAlignment(TextAlignment.CENTER)
                  .Add(new Paragraph("Sacramento"));

               table.AddCell(cell11);
               table.AddCell(cell12);
               table.AddCell(cell21);
               table.AddCell(cell22);
               table.AddCell(cell31);
               table.AddCell(cell32);
               table.AddCell(cell41);
               table.AddCell(cell42);
               document.Add(table);

Adding a table
Figure 8: Adding a table

F. Creating a Hyperlink

Create a Hyperlink and add it to the document (see Figure 9).

         // Hyper link
         Link link = new Link("click here",
            PdfAction.CreateURI("https://www.google.com"));
         Paragraph hyperLink = new Paragraph("Please ")
            .Add(link.SetBold().SetUnderline()
            .SetItalic().SetFontColor(ColorConstants.BLUE))
            .Add(" to go www.google.com.");

         document.Add(newline);
         document.Add(hyperLink);

Adding a hyperlink
Figure 9: Adding a hyperlink

G. Adding Page Numbers

Add Page numbers at the top right corner of the page, as shown in Figure 10.

         // Page numbers
         int n = pdf.GetNumberOfPages();
         for (int i = 1; i <= n; i++)
         {
            document.ShowTextAligned(new Paragraph(String
               .Format("page" + i + " of " + n)),
                559, 806, i, TextAlignment.RIGHT,
                VerticalAlignment.TOP, 0);
         }

Adding page numbers
Figure 10: Adding page numbers

Following is the complete code listing.

using iText.IO.Image;
using iText.Kernel.Colors;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using System;

namespace GeneratePdfDemo
{
   class Program
   {
      static void Main(string[] args)
      {
         // Must have write permissions to the path folder
         PdfWriter writer = new PdfWriter("C:\\test\\demo.pdf");
         PdfDocument pdf = new PdfDocument(writer);
         Document document = new Document(pdf);

         // Header
         Paragraph header = new Paragraph("HEADER")
            .SetTextAlignment(TextAlignment.CENTER)
            .SetFontSize(20);

         // New line
         Paragraph newline = new Paragraph(new Text("\n"));

         document.Add(newline);
         document.Add(header);

         // Add sub-header
         Paragraph subheader = new Paragraph("SUB HEADER")
            .SetTextAlignment(TextAlignment.CENTER)
            .SetFontSize(15);
         document.Add(subheader);

         // Line separator
         LineSeparator ls = new LineSeparator(new SolidLine());
         document.Add(ls);

         // Add paragraph1
         Paragraph paragraph1 = new Paragraph("Lorem ipsum " +
            "dolor sit amet, consectetur adipiscing elit, " +
            "sed do eiusmod tempor incididunt ut labore " +
            "et dolore magna aliqua.");
         document.Add(paragraph1);

         // Add image
         Image img = new Image(ImageDataFactory
            .Create(@"..\..\image.jpg"))
            .SetTextAlignment(TextAlignment.CENTER);
         document.Add(img);

         // Table
         Table table = new Table(2, false);
         Cell cell11 = new Cell(1, 1)
            .SetBackgroundColor(ColorConstants.GRAY)
            .SetTextAlignment(TextAlignment.CENTER)
            .Add(new Paragraph("State"));
         Cell cell12 = new Cell(1, 1)
            .SetBackgroundColor(ColorConstants.GRAY)
            .SetTextAlignment(TextAlignment.CENTER)
            .Add(new Paragraph("Capital"));

         Cell cell21 = new Cell(1, 1)
            .SetTextAlignment(TextAlignment.CENTER)
            .Add(new Paragraph("New York"));
         Cell cell22 = new Cell(1, 1)
            .SetTextAlignment(TextAlignment.CENTER)
            .Add(new Paragraph("Albany"));

         Cell cell31 = new Cell(1, 1)
            .SetTextAlignment(TextAlignment.CENTER)
            .Add(new Paragraph("New Jersey"));
         Cell cell32 = new Cell(1, 1)
            .SetTextAlignment(TextAlignment.CENTER)
            .Add(new Paragraph("Trenton"));

         Cell cell41 = new Cell(1, 1)
            .SetTextAlignment(TextAlignment.CENTER)
            .Add(new Paragraph("California"));
         Cell cell42 = new Cell(1, 1)
            .SetTextAlignment(TextAlignment.CENTER)
            .Add(new Paragraph("Sacramento"));

         table.AddCell(cell11);
         table.AddCell(cell12);
         table.AddCell(cell21);
         table.AddCell(cell22);
         table.AddCell(cell31);
         table.AddCell(cell32);
         table.AddCell(cell41);
         table.AddCell(cell42);

         document.Add(newline);
         document.Add(table);

         // Hyper link
         Link link = new Link("click here",
            PdfAction.CreateURI("https://www.google.com"));
         Paragraph hyperLink = new Paragraph("Please ")
            .Add(link.SetBold().SetUnderline()
            .SetItalic().SetFontColor(ColorConstants.BLUE))
            .Add(" to go www.google.com.");

         document.Add(newline);
         document.Add(hyperLink);

         // Page numbers
         int n = pdf.GetNumberOfPages();
         for (int i = 1; i <= n; i++)
         {
            document.ShowTextAligned(new Paragraph(String
               .Format("page" + i + " of " + n)),
               559, 806, i, TextAlignment.RIGHT,
               VerticalAlignment.TOP, 0);
         }

         // Close document
         document.Close();
      }
   }
}

Conclusion

You have seen how to generate the PDF document by using C#, .NET, and the iText library. iText allows lot of customization to PDF documents. I hope this article will help someone who wants to generate PDF documents.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read