Wednesday, October 20, 2010

Introduction to PDF File Creation in C# Using iTextSharp

There are numerous commercial and open source components that enable .NET developers to create PDF files.  I will be providing a brief introduction to using iTextSharp to create a PDF file using C#.  iTextSharp is an open source .NET library based on the iText Java library.  This post will provide some sample code using iTextSharp to create a PDF containing text entered using a Windows forms application.

Here is a screenshot of the user interface.


















For the purpose of this sample I have added all of the program's logic to the "Create PDF" button.  Here is a walkthrough of the relevant code. You must download the iTextSharp DLL or compile it from the source code and add a reference before you will be able to use the iTextSharp namespace in your project.

Here is the C# code that does the work of creating a basic PDF file.  A complete Visual Studio solution containing a Windows Forms application is available to download as well.  The link is at the end of this post.



//name of file to create, since directory is not specified it will be created in the same directory as the program executable file
string fileName = "hello.pdf";

//create file object
System.IO.FileStream destinationFile = new System.IO.FileStream(fileName, System.IO.FileMode.Create);

//create a new pdf document
iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document();

//associate document with file object
iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, destinationFile);

//must call open method before writing file content
pdfDocument.Open();

//loop through the lines input on the form
foreach (string source in this.sourceText.Lines)
{
    //create a block of text with the content of the line followed by a newline 
    iTextSharp.text.Phrase lineOfText = new iTextSharp.text.Phrase(source + "\n");

    //add block of text to PDF document
    pdfDocument.Add(lineOfText);
}

//close document object when we're done adding content
pdfDocument.Close();

//open pdf file in default PDF application
System.Diagnostics.Process.Start(fileName);


As you can see the code required to produce a basic PDF file is not too complicated.  

References

The iTextSharp library can be found at SourceForge:

The API documentation can be found at the link below.  Note that the documentation is for the Java version, but is useful to programmers using iTextSharp for .NET as well since the .NET library's API is based on the Java version.

The author of iText has published a book on the subject.  The book is based on the Java version of the library. 

You can download the Visual Studio project  file for the example at:



No comments:

Post a Comment