Convert HTML to PDF file in ASP.NET MVC

29 Sep 20221 minute to read

The Syncfusion HTML to PDF converter is a .NET library used to convert HTML or web pages to PDF. Using this library can convert HTML to PDF in ASP.NET MVC application.

Steps to convert HTML to PDF document in ASP.NET MVC

Create a new C# ASP.NET Web Application (.NET Framework) project.
convert_HtmltoPdf_ASP.NET_MVC1

Install Syncfusion.HtmlToPdfConverter.AspNet.Mvc5 NuGet package as reference to your .NET applications from NuGet.org.
convert_HtmltoPdf_ASP.NET_MVC2

Include the following namespaces in that HomeController.cs file.

  • C#
  • using Syncfusion.Pdf;
    using Syncfusion.HtmlConverter;

    Add a new button in the Index.cshtml as shown below.

  • C#
  • @{Html.BeginForm("ExportToPDF", "Home", FormMethod.Post);
    {
    <div>
        <input type="submit" value="Convert PDF" style="width:150px;height:27px" />
    </div>
    }
    Html.EndForm();
    }

    Add a new action method ExportToPDF in HomeController.cs and include the below code snippet to convert HTML to PDF.

  • C#
  • // Initialize HTML to PDF converter.
    HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
    
    // Convert URL to PDF.
    PdfDocument document = htmlConverter.Convert("https://www.syncfusion.com");
    
    MemoryStream stream = new MemoryStream();
    
    document.Save(stream);
    
    return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "HTML-to-PDF.pdf");

    A complete working demo can be downloaded from HTMLToPdf.zip

    By executing the program, you will get the PDF document as follows.
    convert_HtmltoPdf_ASP.NET_MVC1