)
We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to convert MVC View to PDF using C# and VB.NET

Platform: ASP.NET MVC |
Control: PDF |
Published Date: January 20, 2016 |
Last Revised Date: April 29, 2019

The Syncfusion HTML to PDF converter is a .NET library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. The result preserves all graphics, images, texts, fonts, and the layout of the original HTML document or webpage. Using this library, you can convert the MVC view to PDF in C# and VB.NET.

Steps to convert the MVC view to PDF programmatically:

  1. Create a new ASP.NET MVC application project.

Create a new MVC project.

  1. Install the Syncfusion.HtmlToPdfConverter.QtWebKit.AspNet.Mvc5 NuGet package as a reference to your MVC application from NuGet.org.

Install the HTML to PDF converter packages

  1. Copy the QtBinaries folder from the HtmlToPdfConverter NuGet package installed location to Bin folder of the project. You can place the QtBinaries other than bin folder, then it is mandatory to set the QtBinaries folder path to the WebKitPath in WebKitConverterSettings explicitly.

Copy the QtBinaries from NuGet package folder

Paste the QtBinaries into the bin folder

  1. Add new button in Index.cshtml for converting HTML to PDF.
    @{ Html.BeginForm("ConvertToPDF", "Home", FormMethod.Post);
    {
    <h2><input type="submit" value="Convert To PDF"></h2>
    }
    }
    
  1. Include the following namespaces in HomeController.cs file.
    // [C# code]
    using Syncfusion.HtmlConverter;
    using Syncfusion.Pdf;
    using System.IO;
    using System.Text;
    using System.Text.RegularExpressions;
    
  1. Include the following code snippet in the HomeController.cs to convert the MVC view to PDF.
    public ActionResult ConvertToPDF()
    {
    //Getting Index view page as HTML
    ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, "Index", "");
    string html = GetHtmlFromView(ControllerContext, viewResult, "Index", "");
    string baseUrl = string.Empty;
     
    //Convert the HTML string to PDF using WebKit
    HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.WebKit);
     
    WebKitConverterSettings settings = new WebKitConverterSettings();
                
    //Assign WebKit settings to HTML converter
    htmlConverter.ConverterSettings = settings;
     
    //Convert HTML string to PDF
    PdfDocument document = htmlConverter.Convert(html, baseUrl);
     
    MemoryStream stream = new MemoryStream();
     
    //Save and close the PDF document 
    document.Save(stream);
    document.Close(true);
     
    return File(stream.ToArray(), "application/pdf", "ViewAsPdf.pdf");
    }
     
     
    private string GetHtmlFromView(ControllerContext context, ViewEngineResult viewResult, string viewName, object model)
    {
    context.Controller.ViewData.Model = model;
    using (StringWriter sw = new StringWriter())
    {
    //View not found, throw an exception with searched locations
    if (viewResult.View == null)
    {
    var locations = new StringBuilder();
    locations.AppendLine();
     
    foreach (string location in viewResult.SearchedLocations)
    {
    locations.AppendLine(location);
    }
     
    throw new InvalidOperationException(string.Format("The view '{0}' or its master was not found, searched locations: {1}", viewName, locations));
    }
     
    ViewContext viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw);
    viewResult.View.Render(viewContext, sw);
     
    string html = sw.GetStringBuilder().ToString();
     
    //Add the BaseURL for the resources used in the MVC view
    string baseUrl = string.Format("{0}://{1}", HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority);
    html = Regex.Replace(html, "<head>", string.Format("<head><base href=\"{0}\" />", baseUrl), RegexOptions.IgnoreCase);
    return html;
    }
    }
    

You can download the working sample from MVC_ViewToPDF.Zip.

By executing the above sample, you will get the PDF document as follows.

Output in browser

Output in PDF document

Take a moment to peruse the documentation, where you will find other options like HTML string to PDF, HTML to Image, Partial webpage to PDF, and HTML to PDF conversion using WebKit Rendering with code examples.

Click here to explore the rich set of Syncfusion Essential PDF features.

To test the accuracy of HTML to PDF conversion in .NET using C#, try our online demo.

2X faster development

The ultimate ASP.NET MVC UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon