Working with iTextSharp

In the conclusion to our series on working with code libraries, you will learn how to create PDFs with iTextSharp. This article is excerpted from chapter four of the book Windows Developer Power Tools, written by James Avery and Jim Holmes (O'Reilly; ISBN: 0596527543). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 28
August 30, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

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.


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.


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.


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:

  1. Create and work with tables
  2. Create headers and footers
  3. Create chapters and sections
  4. 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/).

iTextSharp in a Nutshell

Using iTextSharp, you can integrate the highly popular PDF document format into your
applications very easily, with no additional cost. iTextSharp is an excellent alternative to the high-priced PDF libraries and provides the same, if not more, features as most of those packages.

4.13 For More Information

Code libraries give you bits and pieces of highly useful functionality. This book does the same thing for you:

  • C# Cookbook, Second Edition, by Jay Hilyard and Stephen Teilhet (O’Reilly)

More resources for the libraries covered in this book can be found via the following links:

Articles
    “Using log4net,”by Nauman Leghari
   (http://www.ondotnet.com/pub/a/dotnet/
   2003/06/16/log4net.html
)

Blogs

  1. The SharpDevelop team blog (http://laputa.sharpdevelop.net)—the team responsible for SharpZipLib is also responsible for SharpDevelop.
  • Just Do I.T. (http://ddossot.blogspot.com)—Davis Dosset is the creator of NxBRE.
  • CarlosAg Blog (http://blogs.msdn.com/CarlosAg/)—Carlos Aguilar Mares is the creator of ExcelXMLWriter (as well as the WebChart control discussed in Chapter 1).  
blog comments powered by Disqus
BRAINDUMP ARTICLES

- Microsoft Windows 8 Committed to Cloud Compu...
- Independent Developers Favor Windows Phone 7
- Dell Introduces VMware-based Cloud
- Microsoft and Skype Agree to Acquisition Deal
- Transfer Contacts in Microsoft Outlook
- Zune`s Next Steps
- Safari Books Online Review
- Does Microsoft Get Touch Screens Now?
- Microsoft`s Record Quarterly Earnings Not En...
- Basic Operations and Registers in Assembly
- Assembly Coding within Visual C/C++ IDE
- New Microsoft Office Coming with a Twist
- Microsoft`s FUSE Labs Unveils Spindex Social...
- HP Slate with Windows 7: Dead or Alive?
- Windows Phone 7 Mobile OS to Rival Android a...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 9 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials