Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ITextSharp Helper Class

0.00/5 (No votes)
9 Jul 2010 1  
The ITextSharp helper class provides a simple way of generating PDF documents using ITextSharp 5.*

Introduction

ITextSharp is a library used to create PDF documents. It provides all of the primitive functions necessary to create a PDF document. However, since all of the methods are based on primitive operations, it is easy to confuse the look and feel of a document without enforcing certain standards. This helper class provides two key benefits. First, it simplifies the creation of PDF documents. Second, it helps enforce standards in terms of the look and feel of a document.

This class simplifies the creation process by providing a solid foundation to build your documents on. A lot of the research has been done here and is contained in a ready to use, inheritable class. The code you need to implement dynamic page footers, tables, paragraphs, and images is contained in the class.

The class also helps enforce the standards necessary to provide a uniform look and feel for your PDF document. Since ITextSharp uses primitive operations to build a document, every paragraph and table cell requires a significant amount of decoration to be displayed in the desired format. These calls help by providing standard paragraph, table cells, and phrase factory methods that will help ensure your document always has the same spacing between paragraphs, same font, and other factors that help build a professional looking document.

Background

One of the features exemplified in the helper class is the footer support. In ITextSharp 5.0, developers removed a header-footer class that provided headers and footers. The same functionality can be obtained using OnPageEnd and OnPageStart; however, it is not as easy to implement as the pre-version 5.0 solution.

Using the Code

The heart of this solution is the ITextLetterBase class. This class is designed to be inherited by a working class that will generate the letter. This class would be an excellent candidate for any framework in a shop that uses ITextSharp.

Methods

NewParagraph()

Provides a standard paragraph style.

NewParagraph(string text)

Provides a standard paragraph style populated with text.

NewBoldParagraph()

Used to create a bold, or title paragraph.

NewBoldParagraph(string text)

Used to create a bold or title paragraph populated with text.

ParaLine(string Text)

Used to create a phrase (that can be added to a paragraph) using the standard font.

REBlock(Paragraph para)

Used to generate a small table containing RE: information.

The first cell contains “RE:” and the second cell may contain a paragraph containing several lines. Use Environment.NewLine to insert line breaks.

AddAddressFooter()

Returns an address footer template. This is right justified, on the bottom of the page. It uses the property FooterLines (a list) to populate the footer content.

AddPageFooter(int PageNumber)

Returns a footer template with “Page x”.

HeaderLogo()

Returns an Itextsharp image. This is pulled from Resource1.resx and will need to be customized for your application.

CellDataNoBorder(string text)

This creates a table cell without a border and populated with text.

CellDataNoBorder(Paragraph text)

This creates a table cell without a border and populated with a paragraph.

CellData(string text)

Creates a standard cell, black border, and populated with text.

CellHeader(string text)

Creates a standard cell, black border, gray background, bold text, populated with text.

DateLine(string LetterDate)

Creates a right justified paragraph with “LetterDate” (this may be a date or anything else).

DateLine()

Creates a right justified paragraph with today’s short date.

SalutationLine()

Creates a paragraph for the salutation line. E.g.: “Dear John:”. This uses the Salutation property.

Closing()

This creates several paragraphs for a standard letter closing.

It uses the following properties: ClosingFinalLine, ClosingSalutation, FromPerson, FromTitle.

GenerateLetterBase()

This generates the standard objects necessary to create a PDF document. The most important object is called l1. This is the document object that all of the paragraphs and other objects will be added to.

OnEndPage(PdfWriter writer, Document document)

EVENT

This is fired at the end of a page. This is how page footers are added.

OnStartPage(PdfWriter writer, Document document)

EVENT

This is fired at the start of a page. If you add a header, you would add it here.

OnParagraph(PdfWriter writer, Document document, float paragraphPosition)

EVENT

This would be fired at the start of a new paragraph.

CTOR

This sets up the stream and document. It is also where I have added the footer lines list content.

buildFonts()

Creates the font definitions used in the class. If you want to add font styles or change the existing font style, you should change this method.

Properties and Objects

MemoryStream PDFStream

This contains the output of the PDF class.

byte[] DocumentBytes

This contains the byte array of the output. This is suitable to write to a file or send back through an ASP.NET response stream.

string Salutation

The Dear Person Line content.

string FromPerson

The name of the person sending the letter.

string FromTitle

The title of the person sending the letter.

List<string> FooterLines

The footer lines as a list. Each entry will be one line.

string ClosingFinalLine

This is the last sentence/paragraph on the letters closing.

string ClosingSalutation

“Sincerely” or “Regards” etc…

Document l1

Object – the PDF document object.

How to Use this Code

Step 1. For the purposes of this demonstration, I will create a console application. Be sure to include references to ITextsharp and System.Drawing.

Step 2. Create a new class to build the document. For example, Letter1. This class needs to inherit the ITextLetterBase class.

public class Letter1 : ITextLetterBase
{
    public Letter1()
    {}
}

Step 3. Add the GenerateLetter method. This is the method that will contain the instructions on creating the letter. The first call in this method should be to GenerateLetterBase(). Then, add the objects and paragraphs you need to create the letter.

public void GenerateLetter()
{  
    // Create ITextSharp Objects
    GenerateLetterBase();
 
    l1.Add(HeaderLogo());
 
    l1.Add(WriteAddress(new AddressType("John Q. Public",
            string.Empty, "Suite 401", "123 Rose Street",
            "Pasadena", "CA", "11111")));
 
    l1.Add(DateLine());
 
    l1.Add(REBlock(new Paragraph("A New Beginning")));
    l1.Add(SalutationLine());
 
    Paragraph p = NewParagraph();
 
    p.Add(ParaLine("Greetings!  This letter was created using the" +
           "ITextLetterBase class.  It makes creating PDF's relatively” +
           "simple and provides automatic footer operations. "));
 
    l1.Add(p);
    l1.Add(NewParagraph("This class was created to help standardize " +
     "the look and feel of a pdf generated by a .Net " +
     "applications.   Before this helper class existed, the " +
     "developer would have to apply styles separately to each “ +
     "paragraph. ));
    Phrase ph = new Phrase("I really hope you find the class and " +
           " this ", fontGeneralText);
    Phrase ph2 = new Phrase("example ",fontBoldText );
    Phrase ph3 = new Phrase("to be useful.", fontGeneralText);
    Paragraph p2 = NewParagraph();
    p2.Add(ph);
    p2.Add(ph2);
    p2.Add(ph3);
    l1.Add(p2);
 
    Closing();

Step 4. Once you have added the content, you need to close the document.

  l1.Close();    // closes the pdf document
      DocumentBytes = PDFStream.GetBuffer();    // creates a byte array.
}

Step 5. Change the Main to use the class:

static void Main(string[] args)
{
    Letter1 mydoc = new Letter1();
    mydoc.GenerateLetter();
    FileStream f = new FileStream("fileout.pdf", FileMode.Create);
    f.Write(mydoc.DocumentBytes, 0, mydoc.DocumentBytes.Length);
 
    f.Close();
}

In this example, I am writing the contents of DocumentBytes to a file called fileout.pdf.

Points of Interest

Remember to change the base class properties to reflect your organizational needs.

This class should be expanded as you see the need for more standardized classes.

Headers and footers are always more complicated because you cannot write to the document element directly. For example, you could not do “l1.add(footer)” at the page end because it would conflict with the usable page area. Instead, we write a “template” directly to the PDF at a specified location. This may also create a challenge if your footer or header is too large. It will overlap the body area of the document. To avoid this, you need to adjust the body margins of the document object.

History

  • May 2010 – First release
  • July 2010 - Updated source code

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here