After the umpteenth request for an example of how to generate PDF using MySQL and iTextSharp, I have finally create a tiny sample project that shows how to do just that.

You can download it here: Complete MySQL and iTextSharp Project (C#).

This is just a sample / how-to. The code provides no error checking, nor does it provide any optimizations. It simply generates a PDF from a MySQL data source.

Some notes: This project follows the model which we use on a GoDaddy hosted site. Because of this, the MySQL command that we use is a “Text” command and not a stored procedure. If we were on almost any other host, we could (and should) use stored procedures to minimize attacks, especially SQL injection.

As for the iTextSharp code, we create some tables for display using the “long way”. I create and populate a Table object at a very granular level. A much more elegant way to generate the PDF would be to generate some HTML (suitable for a display/ preview) and then parse that same HTML for use as the content of the PDF.

However, difference in version 4.x and 5.x of iTextSharp have changed HTML parsing. Whereas, the code I present here, will work in 4.x and (hopefully) 5.x.

Again, this is just a simple example project. I’m sure that your particular application may have some differences that prevent this code from working as-is. But no warranty/guarantee is expressed or implied. So if this doesn’t work for you, or if you end up wiping your hard drive, it’s your fault!

I hope that you find this useful.

2 Replies to “Complete MySQL and iTextSharp Example”

Leave a Reply

Your email address will not be published. Required fields are marked *