Click here to Skip to main content
15,878,814 members
Articles / Programming Languages / C# 4.0

ITextSharp Helper Class

Rate me:
Please Sign up or sign in to vote.
4.88/5 (31 votes)
9 Jul 2010CPOL5 min read 203.3K   13.8K   118   18
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.

C#
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.

C#
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.

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

Step 5. Change the Main to use the class:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Sapphire / ImprovingComputers
United States United States
I am currently doing Thunderhead work for Bank of America. My previous posts have been with Louisiana Dept. of Revenue, Thunderhead, Louisiana Dept. of Public Safety, Trane, FirstUSA, Fleet Bank, GeeWax Turker, DuPont, and the US Navy.

Comments and Discussions

 
Questionkirill Pin
Member 1006112718-Feb-14 0:51
Member 1006112718-Feb-14 0:51 
QuestionError: could not find the xobject name %s Pin
vickram sharma30-Sep-13 7:43
vickram sharma30-Sep-13 7:43 
GeneralMy vote of 4 Pin
Gerard Castelló Viader8-Jan-13 4:04
Gerard Castelló Viader8-Jan-13 4:04 
QuestionPDF OPEN AFTER CREATION Pin
DJAppleboy13-Aug-12 5:14
DJAppleboy13-Aug-12 5:14 
GeneralMy vote of 4 Pin
Farhan Ghumra16-Jul-12 21:37
professionalFarhan Ghumra16-Jul-12 21:37 
QuestionUsing iTextSharp. Error-"The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters." Pin
maajanes24-Apr-12 2:57
maajanes24-Apr-12 2:57 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey9-Feb-12 0:56
professionalManoj Kumar Choubey9-Feb-12 0:56 
QuestionCould you point me to some resource to leverage this class from within an MFC application? Pin
Member 34553985-Dec-11 7:05
Member 34553985-Dec-11 7:05 
GeneralMy vote of 4 Pin
Billy S Davis13-Sep-11 4:26
Billy S Davis13-Sep-11 4:26 
GeneralProblem with alignment Pin
jeyaraj38.mit10-Apr-11 8:09
jeyaraj38.mit10-Apr-11 8:09 
GeneralGood article Pin
syam9624-Apr-11 19:09
syam9624-Apr-11 19:09 
GeneralMy vote of 2 Pin
Syed J Hashmi25-Nov-10 22:53
Syed J Hashmi25-Nov-10 22:53 
General.net 3.5 Version Pin
Jahangir Shahzad23-Aug-10 17:21
Jahangir Shahzad23-Aug-10 17:21 
GeneralJust what I was looking for, However I get a bug on compilation Pin
parker40069-Jul-10 5:13
parker40069-Jul-10 5:13 
GeneralOne question... Pin
Thomas A11-Jun-10 1:00
Thomas A11-Jun-10 1:00 
GeneralRe: One question... Pin
Scott McFadden22-Jun-10 5:53
Scott McFadden22-Jun-10 5:53 
GeneralExcellent Work! My vote of 5 (because 10 is not an option) Pin
SteveMets14-May-10 8:15
professionalSteveMets14-May-10 8:15 
GeneralFormating Pin
Not Active13-May-10 14:19
mentorNot Active13-May-10 14:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.