Search This Blog

Export to PDF using iTextSharp: basic tutorial


posted on Tuesday, April 10, 2012

iTextSharp is the .NET version of a Java library called iText. This library provides you with all the tools to create and manipulate PDF documents.

My first encounter with this library was with the Java version but since then I've crossed over to the .NET side and so I have switched to the .NET version. In my opinion, iTextSharp is the best tool for creating and manipulating PDF documents. The possibilities are almost endless. And there's the catch, something very important you have to keep in mind when working with PDF documents is that PDF documents are not designed to be edited! You can create them and edit them, and using iText this can go quite far, but there are limitations.

This will be the first post about iTextSharp, an introduction, and I will try to post some updates later on to show parts of the great functionality.


Make sure to have a look at the official website: http://itextpdf.com/ for more information, documentation, code examples, and much more. iTextSharp has been assigned a sourceforge page which you can find at: http://sourceforge.net/projects/itextsharp/. On that page you can find a compressed file containing both dll-files as source files for iTextSharp.

1. Create a new ASP.NET Empty Web Application project and name it iTextSharpProject.

2. Download and add the dll-files to the bin-folder and add them as references.

3. Add a new WebForm to the project and name it "Default.aspx" and add four Label-controls, one TextBox-control, a Calendar-control and a Button-control to the form. Use one Label to set a title and associate two other labels with the TextBox and the Calendar. I've set these as "Author" and "Date". Use the fourth label to display errors. Add a Click-event to the Button. So you'll have something like this:



4. In the Click-event add the following code within.

Open try-catch tags in which you'll add the code to create the PDF-document. Exceptions will be caught and an error message will be shown to the user.
            try
            {

            }
            catch (Exception)
            {
                lblError.Text = "An error ocurred, the PDF-document could not be created.";
            }

Create a document and a writer instance that uses the document. Here you should set the location for the file and the filename. You could also write the document to a stream.

Open the document, define a font and add a paragraph to the document.When you've added all elements you wanted to add, close the document.

Use (System.Diagnostics.)Process.Start() to open the document.


                // set the file name
                string file = "C:/pdf/MyPdf.pdf";

                // create a pdf document
                Document document = new Document();

                // set the page size, set the orientation
                document.SetPageSize(PageSize.A4.Rotate());

                // create a writer instance - the document will be saved as 'MyPdf.pdf' in the 'pdf'-folder on the C-drive
                PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream(file, FileMode.Create));

                // open the document
                document.Open();

                // define fonts
                Font titleFont = FontFactory.GetFont("Helvetica", 14, Font.BOLD, new iTextSharp.text.BaseColor(0, 179, 212));
                Font textFont = FontFactory.GetFont("Helvetica", 9, Font.NORMAL, BaseColor.BLACK);

                // create a paragraph and add it to the document
                Paragraph title = new Paragraph("This PDF-document was created using iTextSharp!");
                title.Font = titleFont;
                title.IndentationLeft = 50f;
                document.Add(title);

                // close the document
                document.Close();

                // open the pdf document
                Process.Start(file);

Add the input of the controls in the web form to the document. As you can see, you can set indentation, spacing before or after and a lot more!
                // add the author to the document
                if (!String.IsNullOrEmpty(txtAuthor.Text))
                {
                    Paragraph author = new Paragraph("The author of this document is " + txtAuthor.Text);
                    author.Font = textFont;
                    author.IndentationLeft = 70f;
                    author.SpacingBefore = 10f;
                    document.Add(author);
                }

                // add the date to the document
                if (cldrDate.SelectedDate != DateTime.MinValue)
                {
                    Paragraph date = new Paragraph("This document was created on " + cldrDate.SelectedDate.ToShortDateString());
                    date.Font = textFont;
                    date.IndentationLeft = 70f;
                    date.SpacingBefore = 60f;
                    document.Add(date);
                }

5. When you run this and set an author and a date, click the button and watch as an amazing PDF pops up, just as in the image below!



As you figured out by now, this is a very basic tutorial which should help you get started with iTextSharp. I'll keep posting other code segments for iTextSharp so you can see the possibilities of this great library.

To be continued...


Oops! Almost forgot... :) Here you can find the code for this example and the resulting PDF-file!


Could be useful, right?


1 comment: