Convert HTML to PDF file in ASP.NET MVC

7 Aug 20232 minutes to read

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

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

Step 1: Create a new C# ASP.NET Web Application (.NET Framework) project.
Create ASP.NET MVC application

Step 2: In the project configuration windows, name your project and select Create.
Configuration window1
Configuration window2

Step 3: Install Syncfusion.HtmlToPdfConverter.AspNet.Mvc5 NuGet package as reference to your .NET applications from NuGet.org.
NuGet package installation

NOTE

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, you also have to add “Syncfusion.Licensing” assembly reference and include a license key in your projects. Please refer to this link to know about registering Syncfusion license key in your application to use our components.

Step 4: Include the following namespaces in the HomeController.cs file.

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

    Step 5: 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();
     }

    Step 6: Add a new action method named ExportToPDF in HomeController.cs and include the below code example to convert HTML to PDF document using Convert method in HtmlToPdfConverter class. The HTML content will be scaled based on the given ViewPortSize property of BlinkConverterSettings class.

  • C#
  • //Initialize HTML to PDF converter.
    HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
    BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
    //Set Blink viewport size.
    blinkConverterSettings.ViewPortSize = new System.Drawing.Size(1280, 0);
    //Assign Blink converter settings to HTML converter.
    htmlConverter.ConverterSettings = blinkConverterSettings;
    //Convert URL to PDF document.
    PdfDocument document = htmlConverter.Convert("https://www.syncfusion.com");
    //Create memory stream.
    MemoryStream stream = new MemoryStream();
    //Save the document to memory stream.
    document.Save(stream);
    return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "HTML-to-PDF.pdf");

    By executing the program, you will get the PDF document as follows.
    HTML to PDF output document

    A complete working sample can be downloaded from Github.

    Click here to explore the rich set of Syncfusion HTML to PDF converter library features.

    An online sample link to convert HTML to PDF document in ASP.NET MVC.