SIGN UP MEMBER LOGIN:    
ARTICLE

Basic PDF Creation Using iTextSharp - Part III

Posted by Micke Blomquist Articles | How do I March 10, 2011
In this article series I use a web application to show how to easily create a valid PDF document with just a few lines of code, using the tool iTextSharp which is a free .NET component downloadable from http://sourceforge.net/projects/itextsharp/
Reader Level:
Download Files:
 

Part III - Wrap up. Using what we learned to create a PDF invoice from an XML file

This is the third part of the article series describing PDF creation using iTextSharp. In the first and second part we looked at how to create a PDF, how to assign meta information and how we write some text into the documents. We also looked a bit at how to place text using exact positioning using the content byte and some simple image and graphics handling.

Let's end this series with a small example creating a simple invoice from an xml file using all of the knowledge gathered from these three parts. You'll be surprised at how easy it is! Just keep the focus on how you place stuff on the document, that's the tricky part!

Okay, there are thousands of ways to present an invoice. I've chosen to do a head, row and total kind of layout. So, there will be a table holding the header information with the addresses and order references, a rows table with items, prices and quantity's and a grand total table holding the totals, the fees and the VAT information. There is also a table with the payee information, such as office details, contact information and such. I guess it is a kind of classic invoice layout.  

We need some data for the example, so I've created a data class reading an xml file with four tables: invoice_header, invoice_rows, invoice_total and invoice_payeeinfo

I've wrapped it in a separate class to make it is easy to create overloaded methods supplying the data from other sources than the xml file, for example a database. The class has a file path parameter in its constructor pointing to the file you want to use. The class exposes four methods:

public DataTable GetInvoiceHeader()

public DataTable GetInvoiceRows()

public DataTable GetInvoiceTotal()

public DataTable GetInvoicePayeeInfo()

 

To create an instance of the class, just supply the file path to an XML file having the four tables.

// Read the sample XML file using the contructor, giving the file path

Invoice invoice = new Invoice(Server.MapPath("invoices") + "\\invoice_123456.xml");

// Create references for each of the on-row tables to make it easier to access the values in the table
// using syntax like this: drHead["invoiceId"].ToString()

DataRow drHead = invoice.GetInvoiceHeader().Rows[0];

DataRow drTotal = invoice.GetInvoiceTotal().Rows[0];

DataRow drPayee = invoice.GetInvoicePayeeInfo().Rows[0];

 

The complete procedure for creating the invoice is in the downloadable solution but I will point out some highlights that need an explanation.

Simplify writing to the content byte
When writing a lot of text, create a method for doing this; that will decrease the amount of code you have to write. I created a simple method taking some parameters, but you can extend it to use more.

// This is the method writing text to the content byte

private void writeText(PdfContentByte cb, string Text, int X, int Y, BaseFont font, int Size)

{

   cb.SetFontAndSize(font, Size);

   cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Text, X, Y, 0);

}

I use this method in code simply by calling it like this:

writeText(cb, "Invoice line totals", left_margin, top_margin, f_cb, 10);

Templates

You can create templates of text or images that you can reuse when creating PDFs. I created a simple footer in the example solution which makes it easy to add page footer to each and every page created. Use the method AddTemplate like this:

// Add a footer template to the document

cb.AddTemplate(PdfFooter(cb, drPayee), 30, 1);

 

The PdfFooter method does the work for us:

// Create the template and assign height

PdfTemplate tmpFooter = cb.CreateTemplate(580, 70);

 

This creates a template reference to which we can add text and other stuff to, just like you add text to the document itself.

// Begin writing the footer

tmpFooter.BeginText();

// Set the font and size

tmpFooter.SetFontAndSize(f_cn, 8);

// Write out details from the payee tabletmpFooter.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Text!!!", 0, 53, 0);
tmpFooter.EndText();

pdf_example_footer.jpg

Here is a sample piece of the invoice footer created in the sample solution.

 

Page breaks
You need to control the page breaks yourself when writing text using the content byte, but it is a simple straight forward process so, don't worry. The easiest way of doing it is assigning a local variable and set it to the last writable position on the page (NOTE: The page coordinates goes from the bottom to the top) and then check the current writing position against that variable, deciding if we need to do a page break or not. Let's look at how we do it while looping thru the invoice lines in the example solution.

foreach (DataRow drItem in invoice.GetInvoiceRows().Rows)

{
   writeText(cb, "blah", left_margin, top_margin, f_cn, 10);
   top_margin -= 12;
   // Simpleage break function, check position

   if(top_margin <= lastwriteposition)
   {
      // Okay, we need to switch page, end writing text
      cb.EndText();

      // Make the page break

      document.NewPage();

      // Start writing again on the new page

      cb.BeginText();

      // Assign the new write location on page two!

      // Here you might want to implement a new row header creation

      top_margin = 780;
   }
}

Okay, that's it. Run the sample code in the downloadable solution, change it so it suits your needs and enjoy PDF creation with iTextSharp!

pdf_example_invoice.jpg


Part I, Part II

Login to add your contents and source code to this article
share this article :
post comment
 

This article is very useful for me as I am newbie to iTextSharp for PDF creation. I have successfully accommodated the Footer DataTable (GetInvoicePayeeInfo) in my project. However, when there are many pages because of large data, How do you include the Footer on every Odd pages ? Thanks and best regards!

Posted by Tati Oko Dec 17, 2011

Thank you very much for this nice article. It helps me alot.

Posted by Dang Trang Nov 16, 2011

Hi isg, I looked at some ways to do this with iTextSharp but the result wasn't satisfying. First, there are problems with inline styles, page breaks and input elements like buttons and textboxes wheren't included. You also need to make sure that you have fully qualified links for images as it doesn't support realative paths. If you just need the text output and images are handled as described above, it might work, but if you need something that actually looks like the original page you need to do use some other tool out there or create the PDF from scratch, placing text and elements your self, like described in the article. You could check the following link out, http://hspinfo.wordpress.com/tag/convert-html-to-pdf-using-itextsharp/, it describes how to do it with a gridview control, but it might give you what you want or ideas of how to move further. Good luck and thanks for the feedback on the article! /Micke

Posted by Micke Blomquist Mar 14, 2011

Thanks for your article. Can you help me, how to make PDF of .aspx page. Regards

Posted by isg bgl Mar 12, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Team Foundation Server Hosting
Become a Sponsor