4.12 Creating PDFs with iTextSharp

Adobe’s PDF format is one of the most widely accepted document formats in use today. Most users and clients expect that the software you write will be able to generate and work with PDFs. Unfortunately, however, Adobe does not offer a free SDK that you can download and use; you have to pay to license the API, and a fair amount of work is usually required to get it up and running.

iTextSharp alleviates this problem. iTextSharp is a port of the iText Java PDF library that gives you the ability to add PDF functionality to your applications. Using iTextSharp, you can create and read PDF files without any costs or proprietary software, so you can deliver the functionality your users expect.

iTextSharp at a Glance

Tool

iTextSharp

Version covered

3.1.0

Home page

http://itextsharp.sourceforge.net

Power Tools page

http://www.windevpowertools.com/tools/153

Summary

Full-featured PDF library for creating, reading, and working with Adobe’s PDF document format

License type

LGPL

Online resources

Mailing list

Supported Frameworks

.NET 1.1

Getting Started

Download the iTextSharp assembly from the tool’s home page and reference it in your project (see the Appendix).

Using iTextSharp

To start, you’ll need to add a couple of using statements to your code:

using iTextSharp.text;
using iTextSharp.text.pdf;

Then create a Document object:

Document pdfDocument = new Document( );

Next, create an instance of the PdfWriter and point it to where you want to save this document. In this example I’ll save to a file on the hard drive, but you can save it to any valid IO stream:

PdfWriter.GetInstance(pdfDocument,
                      new FileStream("C:\\WDPT.PDF", FileMode.Create));

Open the document and add some content:

pdfDocument.Open( );
pdfDocument.Add(new Paragraph("Here is a test of creating a PDF"));

Then close it. You don’t need to flush the stream or actually write out the document. Close( ) does it all for you in one call:

pdfDocument.Close( );

The document created can be seen in Figure 4-25.

A simple PDF

Figure 4-25. A simple PDF

Of course, your requirements will rarely be so simple. iTextSharp offers a wide range of features to create more complex PDFs.

In the previous example, we used a paragraph to add text to the document, but you can also use phrases and chunks to create the text you want. A chunk is simply any piece of text with a consistent style; using it, you can specify independent fonts and colors. A phrase is a collection of chunks that includes a leading separator (the amount of vertical space between lines). Chunks and phrases can be added to paragraphs or added directly to documents.

Let’s create a couple of chunks with different fonts:

Chunk c  = new Chunk("Some text in Verdana \n",
                     FontFactory.GetFont("Verdana", 12 ));
Chunk c2 = new Chunk("More text in Tahoma",
                     FontFactory.GetFont("Tahoma", 14));

and then create a paragraph and add those chunks:

Paragraph p = new Paragraph( );
p.Add(c);
p.Add(c2);

You can see the results in Figure 4-26, where both chunks have their respective fonts.

Chunks with fonts

Figure 4-26. Chunks with fonts

iTextSharp also provides support for working with images and embedding those images in your documents. Images can be added through URLs:

Image image = Image.GetInstance(
    "http://www.oreillynet.com/images/oreilly/home_tarsier.jpg");

or from the filesystem:

Image image = Image.GetInstance("home_tarsier.jpg");

PNG, GIF, JPEG, and WMF images can be loaded in this way. You can now add the image to the document or paragraph with the following code:

Document pdfDocument = new Document( );

PdfWriter.GetInstance(pdfDocument,
                      new FileStream("C:\\WDPT.PDF", FileMode.Create));

pdfDocument.Open( );
Image image = Image.GetInstance(
    "http://www.oreillynet.com/images/oreilly/home_tarsier.jpg");
Chunk c = new Chunk("Check out this wicked graphic: \n",
                    FontFactory.GetFont("Verdana", 12 ));

Paragraph p = new Paragraph( );
p.Add(c);
p.Add(image);

pdfDocument.Add(p);
pdfDocument.Close( );

The generated PDF is shown in Figure 4-27.

A PDF with an image

Figure 4-27. A PDF with an image

iTextSharp also includes functions to position and scale images inside your PDFs.

As you can see from these examples, it is easy to create PDFs using iTextSharp. iTextSharp also includes the functionality to:

  • Create and work with tables

  • Create headers and footers

  • Create chapters and sections

  • Create anchors, lists, and annotations

Manipulating PDFs with iTextSharp

On a recent project, I was given the requirement of assembling large policy packets for an insurance client. The client had each piece of the policy either in a static PDF or in a file that would be dynamically converted to PDF. We wanted to get to an end result where the packet would be a single PDF, so it would be easier to store and would require only one print job, so there was no chance of part of it being lost.

The problem was that the packet was different based on each individual policy, so we had to find a way to dynamically combine anywhere from 3 to 20 PDFs into one document. iTextSharp was the solution.

iTextSharp makes it easy to merge multiple PDFs into a single document, using some code posted at http://itextsharp.sourceforge.net/examples/Concat.cs. Simply download the code, and you’ll be able to easily concatenate multiple PDFs into a single PDF. You can compile the code as a Console application and use it as-is, or you can modify it and use it directly in your application.

Additional code for splitting PDFs, creating PDFs with four pages per page sheet to make handouts, and encrypting PDFs is available from http://itextsharp.sourceforge.net.

Getting Support

Support for iTextSharp is limited to a mailing list hosted at the project’s SourceForge site (http://sourceforge.net/projects/itextsharp/).

Get Windows Developer Power Tools now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.