Thursday 1 July, 2010

iTextSharp

iText# (iTextSharp) is a port of the iText open source java library for PDF generation written entirely in C# for the .NET platform. Use the iText mailing list to get support.


Creating Simple PDF Files With iTextSharp


Have you ever wondered how to generate PDF documents in .NET? Thankfully, there's a port of the iText library for .NET, called iTextSharp. Moreover, since C# and Java share a number of similarities, iText code in Java can be easily converted into C# in order to work with iTextSharp. In this article, we'll take a look at the iTextSharp library, using it for PDF generation and manipulation in .NET.

The Portable Document Format (PDF) is one of the most popular ways to exchange documents because it allows for a consistent look across multiple platforms and configurations. When a PDF document is created, everything is fixed, including the page size, the font size, the margins, and so forth. The way the document looks on the machine that created it is the way that the document will look on another machine and when it's printed out.

“Statically” creating PDF files is quite simple. Applications, such as OpenOffice.org Writer, give the user the option to export a word processor document as a PDF file. Users can even find utilities that allow them to “print” directly to a PDF file. Features like these are well-known to end users and are useful for creating a PDF based off a document originally created in another format.

But what about dynamic PDF generation? Some programs need to be able to write out PDF files. A number of third-party libraries exist for this purpose. One popular library is iText for Java. The iText library allows for PDF (among other formats, actually, but we're only concerned with PDF) generation and manipulation, and it's open source. In fact, it's available under either the Mozilla Public License, which is the recommended license, or the LGPL—so you're allowed to use it in proprietary applications.

Both iText and iTextSharp can be found on SourceForge:

http://sourceforge.net/projects/itextsharp/

http://sourceforge.net/projects/itext/

Download the iTextSharp DLL, and let's get to work.

The basics of PDF documents

If you're using Visual Studio, create a project using the Console Application template and go ahead and add the DLL as a reference. Then, create a file and add a few using directives to the top:


using System.IO;


using iTextSharp.text;

using iTextSharp.text.pdf;


Before we start working with a PDF document, we must first create one. A document in iTextSharp is represented by the appropriately-named Document object. The easiest way to instantiate a Document object is to use the parameterless constructor:


Document doc = new Document();


This will create a document using the A4 page size. However, a number of other standard page sizes are also available. Many users will be more familiar with the letter page size (8.5” x 11”). Creating a document based off of this size isn't difficult:


Document doc = new Document(PageSize.LETTER);


The above two constructors create documents with margins of 36 points each (72 points make up a single inch). We can change this, though, by passing the size of each margin in the constructor: passing the left margin size, the right margin size, the top margin size, and the bottom margin size, in that order. So, to create a document with margins of one inch, we'd do this:


Document doc = new Document(PageSize.LETTER, 72, 72, 72, 72);


Of course, we need to actually create the document to disk before we can use it. This only takes one short step:


PdfWriter.GetInstance(doc,

new FileStream("filename.pdf", FileMode.Create));


Before being written to, the document needs to be opened:


doc.Open();


And when everything is done, the document needs to be closed:


doc.Close();

Creating Simple PDF Files With iTextSharp - Working with fonts and text

Adding text to the document is quite easy. The most basic unit of text is theChunk, which is simply a “chunk” of text that must have a consistent appearance. Here, we create a simple Chunk:


Chunk boo = new Chunk("Boo!");


Content must be manually added to the page:


doc.Add(boo);


We can stylize the text if we need to. Below, we make the text bold and big:


boo.Font.SetStyle(Font.BOLD);

boo.Font.Size = 72;


As you can see, the Font property, which is of the Font type, represents the text's font. Above, we make it bold and give it a size of 72 points. To set the style, we can either pass an appropriate integer value (these values can be found in Font, like Font.Bold), or we can pass a string to achieve the same effect:


boo.Font.SetStyle("bold");


Fonts can also be created and passed into the constructor when creating a Chunk:


Font small = new Font(Font.TIMES_ROMAN, 5);

Chunk smallText = new Chunk("This is small.", small);


Above, we create a font by specifying the font family (Times Roman) and a size (five points). However, we can specify several more properties in the constructor, such as the font style and the color. Below, we create a red, italicized font:


Font redItalic = new Font(Font.HELVETICA, Font.DEFAULTSIZE,

Font.ITALIC, Color.RED);


Fonts can also be quickly and easily created using the GetFont method of the FontFactory class:


Chunk hey = new Chunk("Hey.", FontFactory.GetFont("Courier", 12, Font.ITALIC));


There's also a Phrase class, which is a bit higher level than the Chunk class, but is created similarly:


Phrase p = new Phrase("This is a phrase.");


Creating Simple PDF Files With iTextSharp - Working with paragraphs



However, Chunk is a bit low-level. More often, you'll be using Paragraph, which represents a paragraph of text. A paragraph has space before it, and it can be indented. Unlike a Chunk, a paragraph's text does not have to be consistent. That is, portions of the text can be underlined, struck through, etc. Here's a basic Paragraph:


Paragraph hello = new Paragraph("Hello. This is a paragraph.");


A Paragraph can be styled just like a Chunk:


hello.Font.sestyle(Font.ITALIC);


However, applying styles to specific sections of text within a Paragraph is a bit trickier. To do this, we must break the Paragraph into Chunk objects and then style each Chunk object. Here, we create a paragraph with multiple styled sections of text:


Paragraph fancy = new Paragraph();


Chunk bold = new Chunk("This ");

bold.Font.SetStyle(Font.BOLD);

fancy.Add(bold);


Chunk italics = new Chunk("is a");

italics.Font.SetStyle(Font.ITALIC);

fancy.Add(italics);


Chunk big = new Chunk("fancy");

big.Font.Size = 20;

big.Font.SetStyle(Font.BOLD);

fancy.Add(big);


Chunk struck = new Chunk("paragraph.");

struck.Font.SetStyle(Font.STRIKETHRU);

fancy.Add(struck);


A paragraph will automatically have some spacing, but it's possible to add more:


Paragraph spaced =

new Paragraph("This has a lot of space around it.");

spaced.SpacingBefore = 72;

spaced.SpacingAfter = 72;

spaced.IndentationLeft = 72;

spaced.IndentationRight = 72;


Indenting the paragraph by setting the IndentationLeft property indents the entire paragraph, though. Often, you'll want to indent only the first line of a paragraph. This can be done by setting the FirstLineIndentproperty:


Paragraph p = new Paragraph();

p.FirstLineIndent = 36;


While paragraphs are left-aligned by default, the alignment can be changed using the Alignment property:


Paragraph p = new Paragraph();

p.Alignment = Element.ALIGN_LEFT;

p.Alignment = Element.ALIGN_CENTER;

p.Alignment = Element.ALIGN_RIGHT;

p.Alignment = Element.ALIGN_JUSTIFIED;


The lines in a paragraph will naturally need some space between them, called a leading. The default leading will often do fine, but sometimes the leading must be modified. This can be done by setting the Leading property:


Paragraph spacy = new Paragraph();

spacy.Leading = 72;


The leading can also be specified in the constructor:


Paragraph spacy2 = new Paragraph(72);

Paragraph spacy3 = new Paragraph(72,

"The leading is an inch.");


The leading can also be calculated by multiplying the font size by a number. This feature can be used, for example, to double space a paragraph:


Paragraph doubleSpaced = new Paragraph();

doubleSpaced.MultipliedLeading = 2;


Creating Simple PDF Files With iTextSharp - A short example


In order to recap everything before we move on, let's create a simple application that generates a very basic PDF document. Nothing fancy is needed here. We'll create a few paragraphs of text and style each of them a bit differently. This application will create a PDF in the file 1.pdf:


using System;

using System.IO;


using iTextSharp.text;

using iTextSharp.text.pdf;


class Example1

{

static void Main(string[] args)

{

// Create and open a document

Document doc = new Document();

PdfWriter.GetInstance(doc,

new FileStream("1.pdf", FileMode.Create));

doc.Open();


// Create a string to use for paragraphs

string text = "This is a paragraph. It is represted" +

" by a Paragraph object in the iTextSharp " +

"library. Here, we're creating paragraphs with " +

"various styles in order to test out iTextSharp." +

" This paragraph will take up multiple lines " +

"and allow for a more complete example.";


// Add a basic paragraph

doc.Add(new Paragraph(text));


// Add a paragraph that's underlined and indented

Paragraph p2 = new Paragraph(text);

p2.IndentationLeft = 36;

p2.Font.SetStyle(Font.UNDERLINE);

doc.Add(p2);


// Add a paragraph that's underlined and in bold

doc.Add(new Paragraph(text,

FontFactory.GetFont("Courier",

Font.DEFAULTSIZE, Font.UNDERLINE | Font.BOLD)));

// Add a really big paragraph

doc.Add(new Paragraph(text,

new Font(Font.HELVETICA, 36)));


// Add a green, centered paragraph

Paragraph p5 = new Paragraph(text,

new Font(Font.TIMES_ROMAN,

Font.DEFAULTSIZE, Font.NORMAL, Color.GREEN));

p5.Alignment = Element.ALIGN_CENTER;

doc.Add(p5);


// Add a double-spaced paragraph with

// an indented first line

Paragraph p6 = new Paragraph(text);

p6.FirstLineIndent = 36;

p6.MultipliedLeading = 2;

doc.Add(p6);


// Add a paragraph with multiple styles

// Each word gets bigger

Paragraph ascending = new Paragraph();

ascending.SpacingBefore = 72;

for (int i = 1; i <= 5; i++)

{

ascending.Add(new Chunk("Hello",

new Font(Font.HELVETICA, i * 5)));

}

doc.Add(ascending);


// Close the document

doc.Close();

}

}

No comments:

Post a Comment