Convert HTML to PDF in ASP.NET MVC

In short:

HTML Renderer for PDF using PdfSharp

    public static Byte[] PdfSharpConvert(String html)
    {
        Byte[] res = null;
        using (MemoryStream ms = new MemoryStream())
        {
            var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
            pdf.Save(ms);
            res = ms.ToArray();
        }
        return res;
    }

More Detailed Answer


There is special nuget package RazorPDF. It simple works. RazorPDF site


The C# code below can be used in a MVC application to convert the current view to PDF and produce a PDF in a buffer that can be saved on server or sent to browser for download. The code is using evopdf library for .net to perform the HTML to PDF conversion:

[HttpPost]
public ActionResult ConvertCurrentPageToPdf(FormCollection collection)
{
    object model = null;
    ViewDataDictionary viewData = new ViewDataDictionary(model);

    // The string writer where to render the HTML code of the view
    StringWriter stringWriter = new StringWriter();

    // Render the Index view in a HTML string
    ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, "Index", null);
    ViewContext viewContext = new ViewContext(
            ControllerContext,
            viewResult.View,
            viewData,
            new TempDataDictionary(),
            stringWriter
            );
    viewResult.View.Render(viewContext, stringWriter);

    // Get the view HTML string
    string htmlToConvert = stringWriter.ToString();

    // Get the base URL
    String currentPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
    String baseUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Convert_Current_Page/ConvertCurrentPageToPdf".Length);

    // Create a HTML to PDF converter object with default settings
    HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

    // Convert the HTML string to a PDF document in a memory buffer
    byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlToConvert, baseUrl);

    // Send the PDF file to browser
    FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
    fileResult.FileDownloadName = "Convert_Current_Page.pdf";

    return fileResult;
}

You can use the Free Html To Pdf Converter from SelectPdf (http://selectpdf.com/community-edition/).

Code for MVC looks like this:

[HttpPost]
public ActionResult Convert(FormCollection collection)
{
    // read parameters from the webpage
    string url = collection["TxtUrl"];

    string pdf_page_size = collection["DdlPageSize"];
    PdfPageSize pageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pdf_page_size, true);

    string pdf_orientation = collection["DdlPageOrientation"];
    PdfPageOrientation pdfOrientation = (PdfPageOrientation)Enum.Parse(
        typeof(PdfPageOrientation), pdf_orientation, true);

    int webPageWidth = 1024;
    try
    {
        webPageWidth = System.Convert.ToInt32(collection["TxtWidth"]);
    }
    catch { }

    int webPageHeight = 0;
    try
    {
        webPageHeight = System.Convert.ToInt32(collection["TxtHeight"]);
    }
    catch { }

    // instantiate a html to pdf converter object
    HtmlToPdf converter = new HtmlToPdf();

    // set converter options
    converter.Options.PdfPageSize = pageSize;
    converter.Options.PdfPageOrientation = pdfOrientation;
    converter.Options.WebPageWidth = webPageWidth;
    converter.Options.WebPageHeight = webPageHeight;

    // create a new pdf document converting an url
    PdfDocument doc = converter.ConvertUrl(url);

    // save pdf document
    byte[] pdf = doc.Save();

    // close pdf document
    doc.Close();

    // return resulted pdf document
    FileResult fileResult = new FileContentResult(pdf, "application/pdf");
    fileResult.FileDownloadName = "Document.pdf";
    return fileResult;
}

VB.NET MVC version of the code can be found here: http://selectpdf.com/convert-from-html-to-pdf-in-asp-net-mvc-csharp-and-vb-net/