Converting Razor views into Pdf

By Dawid on (tags: convert, generate, pdf, razor, categories: tools, code)

This post talks about how you can convert Razor views into PDF. There is couple of NuGet packages which we can use to achieve that. I will try to describe couple of them.

iTextSharp

This library allows us to create documents in Portable Document Format (PDF). Some of the features:
- generate documents and reports based on either provided HTML or by manually adding PDF elements such as text, paragraphs, tables and many more
- PDF manipulation: stamping watermarks, merging and splitting PDF files
- PDF form filling
- server dynamic generated or manipulated PDF documents to a web browser
Library can be easily used in ASP.NET MVC in couple of ways. Bellow you will find couple of examples how we can use library.

Using XMLWorkerHelper to convert HTML to the PDF:
   1: MemoryStream stream = new MemoryStream();
   2: using (Document document = new Document())
   3: {
   4:     //html - we can provide here any HTML, for example one rendered from Razor view
   5:     StringReader htmlReader = new StringReader(html);
   6:     PdfWriter writer = PdfWriter.GetInstance(document, stream);
   7:     writer.PageEvent = new PageEventHelper();
   8:     document.SetPageSize(PageSize.A4);
   9:     document.Open();
  10:     XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlReader);
  11:     document.Close();
  12: }
  13: return stream.GetBuffer();

Manual creation of PDF elements:

   1: //creating instance of pdf document
   2: MemoryStream memoryStream = new MemoryStream();
   3: Document doc = new Document(new iTextSharp.text.Rectangle(Utilities.MillimetersToPoints(1000), Utilities.MillimetersToPoints(1000)));
   4: PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
   5: doc.Open();
   6:  
   7: //creating base font which will be used in the document
   8: BaseFont font = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false);
   9:  
  10: PdfContentByte cb = writer.DirectContent;
  11: cb.BeginText();
  12: cb.SetFontAndSize(font, 12);
  13: cb.ShowText("This is an example text");
  14: cb.EndText();
  15:  
  16: writer.CloseStream = false;
  17: doc.Close();
  18: memoryStream.Position = 0;
  19:  
  20: //byte array with PDF content
  21: byte[] result = memoryStream.ToArray();

Example usage in ASP.NET MVC:

   1: public ActionResult GeneratePdf()
   2: {
   3:     //generate PDF document
   4:     byte[] pdfBytes = GeneratePdf();
   5:     //return generated document
   6:     return File(pdfBytes, "application/pdf", "example_document.pdf");
   7: }

More details about iTextSharp can be found here: http://itextpdf.com/ and here: https://github.com/itext/itextsharp

HiQPdf

The HiQPdf Library for .NET offers you a modern, simple, fast, flexible and powerful tool to create complex and stylish PDF documents in your applications with just a few lines of code.
Using the high quality HTML to PDF conversion engine you can easily design a document in HTML with CSS3, JavaScript, SVG or Canvas and then convert it to PDF preserving the exact content and style.
Some of most important features according to their website:
- fast and precise HTML to PDF Conversion Technology
- support for all modern HTML5, CSS3, SVG and Canvas features
- support for Web Fonts and Web Open Font Format (WOFF)
- convert HTML to PDF, to transparent PNG or to SVG vector image
- create, edit, merge and split PDFs, fill and submit PDF forms
- absolutely no external dependencies, direct copy deployment

Basics usage is quite simple:

   1: // create the HTML to PDF converter
   2: HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
   3:  
   4: // convert a HTML code to a PDF buffer in memory
   5: // the buffer can be saved to a file, a stream or a HTTP response
   6: byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory("<b>Hello World</b>", null);

EVO HTML to PDF Converter for .NET

EVO HTML to PDF Converter library for .NET can be easily integrated into any type of .NET application, either ASP.NET web sites, Windows Forms and WPF applications or Windows Azure Cloud services to convert URLs, HTML strings and streams, SVG vector graphics to a PDF document or to an image. You can use the converter as a general purpose tool for converting web pages and HTML code to PDF documents and images or you can use it as a nice tool to instantly create nicely formatted and easily maintainable PDF reports directly from existing HTML reports.
The converter offers full support for HTML tags, CSS styles, SVG vector graphics, page breaks control with CSS styles, automatically repeated HTML table header on each PDF page, live URLs and internal links in PDF, automatically generated bookmarks, HTML in the headers and footers, Unicode and right to left text,  PDF merge, split and edit.
We can easily integrate this library into our ASP.NET MVC web application like that:

   1: public ActionResult GeneratePdf(string viewName)
   2: {
   3:     string htmlToConvert = GetViewHtml(viewName);
   4:     string baseUrl = GetBaseUrl(viewName);
   5:  
   6:     HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
   7:  
   8:     htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
   9:     htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
  10:  
  11:     byte[] pdfBytes = htmlToPdfConverter.ConvertHtml(htmlToConvert, baseUrl);
  12:  
  13:     return File(pdfBytes, "application/pdf", string.Format("{0}.pdf", viewName));
  14: }

And here is nice way how we can render Razor view into HTML which we can convert later on:

   1: protected string GetViewHtml(string viewName)
   2: {
   3:     StringWriter stringWriter = new StringWriter();
   4:     ViewDataDictionary viewData = new ViewDataDictionary();
   5:     ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);
   6:     ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, viewData, new TempDataDictionary(), stringWriter);
   7:     viewResult.View.Render(viewContext, stringWriter);
   8:     return stringWriter.ToString();
   9: }

There seems to be one problem with that library – poor support. I’ve found couple of entries where we can read that support organisation it’s the best and thy aren’t giving any feedback on reported bugs.
More information and full list of featues can be found here: http://www.evopdf.com/html-to-pdf-converter.aspx

Select.PDF Library for .NET

Select.Pdf for .NET is a professional PDF library that can be used for creating, writing, editing, handling and reading PDF files without any external dependencies within .NET applications. Using this .NET PDF library, you can implement rich capabilities to create PDF files from scratch or process existing PDF documents entirely through C#/VB.NET without installing Adobe Acrobat.
Many rich features can be supported by the .NET PDF API, such as security setting (including digital signatures), PDF merge/split, text, html and image drawing into PDF and many more. Besides, Select.Pdf for .NET component can be used to easily convert HTML to PDF with C#/VB.NET in high quality.
Some examples:

   1: HtmlToPdf converter = new HtmlToPdf();
   2: PdfDocument doc = converter.ConvertHtmlString(html, baseUrl);
   3: MemoryStream stream = new MemoryStream();
   4: doc.Save(stream);
   5: doc.Close();
   6: byte[] pdfBytes = stream.ToArray();

More information here: http://selectpdf.com/pdf-library-for-net/

Licencing

There is couple more of libraries which we can use to convert Razor views into PDF. I won’t describe each of them because usage of those libraries is very similar. What can I say is few words about licencing:
- EVO HTML to PDF Converter for .NET – here we can use quite interesting Company License which can be used by an unlimited number of developers, in an unlimited number of applications that can be deployed on any number of computers.
- HiQPdf – something similar here called Enterprise Licence. It allows any number of developers to develop any number of applications using our software. There are no run time or deployment costs and the license never expires. The license price includes the software upgrades and Enterprise Technical Support for the first year.
- Select.PDF – there is quite similar licence called Enterprise OEM License but it’s a little bit more expensive. What is interesting here that there is an option to use free Community Edition. The free html to pdf converter offers most of the features the professional sdk offers, the only notable limitation is that it can only generate PDF documents up to 5 pages long.

Summary

If you are looking for good library which can be used by unlimited number of developers to develop any number of applications then I would suggest HiGPdf. Very fast library and function complete. Cheaper then EVO and Select.PDF libraries.