Sunday, 8 May 2011

Using the Razor Engine to create PDFs

I've been using MVC 3 and the Razor syntax for a while now, and a while ago whilst reading how people were using Razor for their email templates I had the idea to use Razor to help create PDF templates.




Now sadly it's been a while since I played around with this but I have only just started getting back on top of things so here's how I've done it.




Components Used


My solution is to write HTML templates using the Razor syntax and then to make use of the Razor View Engine for filling in the dynamic data. Then for the PDF creation to make use of iTextSharp library to generating the PDF documents from the generated HTML.

iTextSharp is a free library that allows you to create PDF's using C#, unfortunatley its API is a bit of a pain to use natively so I have made use of Hugo Bonacci's HtmlToPdfBuilder.cs class to simply my interaction with the library.




The first thing to do is to generate the HTML markup for out PDF. So fire up a new RazorViewEngine and load the view (template) you wish to use. We load the view by using the view engines FindView method. This method requires a ControllerContext so if you are using in an MVC site you can pass the current context, which is how for my protoype I used it, or you need to pass a custom one.



var frontPageData = new RazorViewEngine().FindView(this.ControllerContext, "Newsletter", "", false);

In my example I wanted my Newsletter template, I have decided to not use a master view or caching but in a real application you may want to enable view caching.




Next you need a view context, a view context also needs a controller context, the view you found previously, a viewdatadictionary, a tempdatadictionary and a textwriter. The viewdatadictionary should be used to pass a model to your view or viewdata items, these will then be used within the view to populated your dynamic data items. The textwriter will be the object that the final generated HTML will be written to and this is what we will use to generate the PDF from.



var textwriter = new StringWriter();
var dataDict = new ViewDataDictionary<NewsletterData>()
{
Model = new NewsletterData{ Name = "Mike" }
};
var context = new ViewContext(this.ControllerContext, frontPageData.View, dataDict, new TempDataDictionary(), textwriter);



The final thing we do to get our generated HTML is call the Render method on our view, this render method requires our viewcontext and the text writer.



frontPageData.View.Render(context, textwriter);



Now the HTML is generated we can make use of the HtmlToPdfBuilder class to take our HTML and generate a PDF document. This is as simple as creating a new builder with a provided pagesize, calling add page and then appending our HTML. Hugo's HtmlToPdfBuilder class expects an array of values to use in the HTML, as it expects the HTML to have placeholders in the String.Format fashion {0} {1} etc. We don't need to do this as we have already finalised our HTML, if this was going to be production code I would seriously consider not using the HtmlToPdfBuilder class and instead write one that only uses iTextSharp and the RazorViewEngine, however for this simple prototype it makes things alot simpler.




var myHtmlPdfBuilder = new HtmlToPdfBuilder(PageSize.A4_LANDSCAPE);
//add a new page
myHtmlPdfBuilder.AddPage();
//using the current page take our html data from our view and write it
myHtmlPdfBuilder[0].AppendHtml(data, new object[]{ });




Now the PDF has been generated we can call the RenderPDF method on our HtmlPdfBuilder class to get an array of bytes back that represent the PDF. We can then use this array and write it to disk as a PDF document or to a response stream to have a dynamic PDF page on a website.




It really is that simple, I hope this prototype shows you the power the RazorViewEngine gives you especially when you start combining its output with other third party libraries. You can download my protoype MVC 3 site with this in and have a poke. It includes a simple PDFActionResult along with the above code.




Update


Whilst writing this blog post up I have decided to roll this prototype into a proper component which should simplfy the above and not require the use of Hugo's class. I will blog about this component when it is finished and publish it on CodePlex or something similar.