HTML to PDF in ASP.NET MVC using ABCpdf

At Kalon, we care about everything from the LINQ queries to the animation of the final pixels to the relationships we build with our customers. Hopefully our blog will be a collection of stories about our journey -- what matters to us, the mistakes we make, and the fun we have along the way. Every once in a while we'll sprinkle in some technical posts to try to help developers who run across some of the same challenges we have.

Over the years I have come across the same problem numerous times. A customer wants to generate a report or email an invoice and often they want the ability to export it to PDF. Most of the time I'm already generating a view of that data on the screen and I'd love to take that same HTML and CSS and make it into a PDF.

I've tried a number of libraries, but pretty much stuck with ABCpdf for how dead simple it is to use and how many things I can do with it. I've done everything from generating PDF invoices to combining PDFs to overlaying watermarks to composing JPG images.  You have to purchase a license, but there is a 30 day free trial and the headache it saves is well worth it to me.

Here is a quick example of how I'm using it in an ASP.NET MVC project render the same view I'm showing on the screen to an exported PDF.

First, the MVC Action to display the report or export the same report to PDF.

This method renders your same Razor view to an HTML string. One nice thing about this method is it accepts a layout in the masterName parameter so you can use one layout for viewing online and one for exporting or printing.

Finally, this is all you need to use ABCpdf to save html as a PDF. 

So, that is how I use ABCpdf to export HTML pages to PDFs. You can download the free trial of ABCpdf here and give it a go. You can also see all the sample code on GitHub in this gist Hopefully this has made your life as a developer a little easier.