Click here to Skip to main content
13,903,660 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


13 bookmarked
Posted 20 Apr 2015
Licenced CPOL

Rudimentary PDF Generation in C# Using iTextSharp

, 20 Apr 2015
Rate this:
Please Sign up or sign in to vote.
In which I demonstrate how to use iTextSharp to generate a PDF file with tables, colors, and links

Baby Steps

The first thing you need to do is download iTextSharp, from here

Alternatively, you can NuGet them by right-clicking your project, selecting "Manage NuGet Packages" and then searching for and installing (may as well install all four, listed below).

At the time of updating this article (March 2016) the latest release was

You then need to add the following DLLs to your Visual Studio project (via References > Add References...):

  • itextsharp
  • itextsharp.pdfa
  • itextsharp.xmlworker
  • itextsharp.xtra

You may not need all of these assemblies for simple usage, but those are what I have and, even if you don't need them all right away, you probably will eventually.

Toddler Wobblings

Now here's the basis for a method that will generate a PDF file:

    using (var ms = new MemoryStream())
        using (var doc = new Document(PageSize.A4, 25, 25, 25, 25))
            //Create a writer that's bound to our PDF abstraction and our stream
            using (var writer = PdfWriter.GetInstance(doc, ms))
                //Open the document for writing

                // The "guts" of the code will go here

            var bytes = ms.ToArray();
            String PDFFileName = String.Format("AlwaysTheTwainShallMeet_{0}.pdf", 
            PDFFileName = PDFFileName.Replace(":", "_");
            var testFile = Path.Combine(Environment.GetFolderPath
			(Environment.SpecialFolder.Desktop), PDFFileName);
            File.WriteAllBytes(testFile, bytes);
            MessageBox.Show(String.Format("{0} written", PDFFileName));
catch (DocumentException dex)
    MessageBox.Show(String.Format("DocumentException: {0}", dex.Message));
    throw (dex);
catch (IOException ioex) // this may be reached if you try to generate a new file 
			// in the same minute as the last one 

created (just try it again if that happens, or change the name of the file to include seconds also)
    MessageBox.Show(String.Format("IOException: {0}", ioex.Message));
    throw (ioex);
catch (Exception ex)
    String exMsg = ex.Message;
    MessageBox.Show(String.Format("General Exception: {0}", ex.Message));

Twainiacs of the Galaxy Unite!

This will compile, but won't do anything (good), as we've added no code to generate anything on the PDF file yet. We will now build up the file, step-by-step, until we have one that looks like this:

Concise Twain Bibliograpthy

First, we want to declare some fonts that we will use. Add these, for instance:

// Custom Fonts 
Font times16BoldCyan = FontFactory.GetFont(FontFactory.TIMES_BOLD, 16, BaseColor.BLUE);
Font courier11BoldYellow = FontFactory.GetFont(FontFactory.COURIER_BOLD, 11, BaseColor.YELLOW);
Font helvetica9 = FontFactory.GetFont(FontFactory.HELVETICA, 9, BaseColor.BLACK);
Font LinkFont = FontFactory.GetFont(FontFactory.HELVETICA, 9, 
	iTextSharp.text.Font.UNDERLINE, BaseColor.BLUE);

Now, we can add the title line by creating a Paragraph, passing it the text and the font we want to use, and then adding it to the doc:

Paragraph twainBibText = new Paragraph("Mark Twain - Concise Book Bibliography", times16BoldCyan);

Go ahead and run it, if you want; you should see that text on the PDF file.

Next, we'll add the verbiage about reading Twain books online. This requires combining two elements (a "Chunk" and an "Anchor") in a Paragraph. That can be done this way:

Chunk chunkTwainCentral = new Chunk("Read selected Twain works online - annotated, 
	with color-coded dialog, ", helvetica9);
Anchor anchorTwainCentral = new Anchor("hyar", LinkFont);
anchorTwainCentral.Reference = "";
Paragraph parTwainCentral = new Paragraph();

And now for another, similar, line that combines a Chunk and an Anchor:

Chunk chunkTwainRes = new Chunk("Download a free novel about Samuel Clemens (Mark Twain) ", helvetica9);
Anchor anchorTwainRes = new Anchor("rot cheer", LinkFont);
anchorTwainRes.Reference = 
Paragraph parTwainRes = new Paragraph();

Now let's add some heading text for the Twain bibliography. A good way to do that is to create a table, and then add cells to that table, like so:

// Table for headings
PdfPTable tblHeadings = new PdfPTable(3);
tblHeadings.WidthPercentage = 80;
tblHeadings.SpacingBefore = 10f;
float[] headingRowWidths = new float[] { 300f, 100f, 600f };
tblHeadings.HorizontalAlignment = Element.ALIGN_LEFT;

Phrase phraseYear = new Phrase("Year of Publication", courier11BoldYellow);
PdfPCell cellYear = GetCellForBorderedTable(phraseYear, Element.ALIGN_CENTER, BaseColor.BLUE);

Phrase phraseblankHeading = new Phrase();
PdfPCell cellBlankSectionHeading = new PdfPCell(phraseblankHeading);
cellBlankSectionHeading.BorderWidth = 0;

Phrase phraseTitle = new Phrase("Title", courier11BoldYellow);
PdfPCell cellTitle = GetCellForBorderedTable(phraseTitle, Element.ALIGN_CENTER, BaseColor.BLUE);

I won't go into detail about what this code does, because either you're like me, and don't really care as long as it works, or you are a "real programmer" and can figure it out by reading it.

Note, that there is also a helper method, namely GetCellForBorderedTable(). That is:

private static PdfPCell GetCellForBorderedTable(Phrase phrase, int align, BaseColor color)
    PdfPCell cell = new PdfPCell(phrase);
    cell.HorizontalAlignment = align;
    cell.PaddingBottom = 2f;
    cell.PaddingTop = 0f;
    cell.BackgroundColor = color;
    cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
    return cell;

Now let's add some more single-row tables, and the values for them. We can do that this way:

// Innocents Abroad
PdfPTable tblIARow = new PdfPTable(3);
tblIARow.WidthPercentage = 80;
tblIARow.SpacingBefore = 4f;
float[] IARowWidths = new float[] { 300f, 100f, 600f };
tblIARow.HorizontalAlignment = Element.ALIGN_LEFT;

Phrase phrase1869 = new Phrase("1869", helvetica9);
PdfPCell cell1869 = GetCellForBorderedTable(phrase1869, Element.ALIGN_CENTER, BaseColor.GREEN);

// Blank cell
Phrase phraseblankIARow = new Phrase();
PdfPCell cellBlankIARow = new PdfPCell(phraseblankIARow);
cellBlankIARow.BorderWidth = 0;

Anchor anchorIA = new Anchor("The Innocents Abroad, or The New Pilgrim's Progress", LinkFont);
anchorIA.Reference = "";
Paragraph parIA = new Paragraph();


Keep adding code like this, and you will eventually have created one like the one showed earlier.

Note: I used a Green background for nonfiction books, and Yellow for fiction. Otherwise, the only difference is in the name of the controls, the label displayed (year and title), and the URL.

Exercise Is Good For You (Just ask Mike Daniels if you don't believe me)

The nigh-obligatory exercise left to the dear and gentle reader: Change the "Twain Central" Chunk/Anchor Paragraph to display the word "color-coded" in various colors. Hint: you're not restricted to the handful of colors that iTextSharp declares; you can create custom colors like this: var lightGreen = new BaseColor(204, 255, 204);


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

B. Clay Shannon
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006:

You may also be interested in...


Comments and Discussions

QuestionColor Everything Pin
lucian.andercou17-Jun-15 10:10
professionallucian.andercou17-Jun-15 10:10 
AnswerRe: Color Everything Pin
B. Clay Shannon17-Jun-15 10:16
professionalB. Clay Shannon17-Jun-15 10:16 
GeneralRe: Color Everything Pin
lucian.andercou17-Jun-15 11:24
professionallucian.andercou17-Jun-15 11:24 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190306.1 | Last Updated 20 Apr 2015
Article Copyright 2015 by B. Clay Shannon
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid