Convert HTML to PDF file in ASP.NET Core

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 Core application.

Steps to convert HTML to PDF in ASP.NET Core application:

Create a new C# ASP.NET Core Web Application project.
convert_HtmltoPdf_ASPNET_CORE1

Install Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package as reference to your .NET Standard applications from NuGet.org.
convert_HtmltoPdf_ASPNET_CORE2

A default controller with name HomeController.cs gets added on creation of ASP.NET MVC project. Include the following namespaces in that HomeController.cs file.

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

    Add an Export To PDF button in 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 file and download it.

  • 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();
    
    //Save and close the document. 
    document.Save(stream);
    
    document.Close(); 
    
    return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "HTML-to-PDF.pdf");

    A complete demo can be downloaded from HTML-to-PDF-Demo.zip

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