Convert HTML to PDF file in ASP.NET Core
3 Jul 20243 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 Core application.
To quickly get started with converting HTML to PDF in ASP.NET Core using the HTML-to-PDF Library. Please, check this video:
Steps to convert HTML to PDF in ASP.NET Core application
Step 1: Create a new C# ASP.NET Core Web Application project.
Step 2: In configuration windows, name your project and select Next.
Step 3: Install Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package as reference to your .NET Standard applications from NuGet.org.
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: A default controller with name HomeController.cs gets added on creation of ASP.NET Core MVC project. Include the following namespaces in that HomeController.cs file.
using Syncfusion.Pdf;
using Syncfusion.HtmlConverter;
using System.IO;
Step 5: Add a new button in index.cshtml as shown below.
@{Html.BeginForm("ExportToPDF", "Home", FormMethod.Post);
{
<div>
<input type="submit" value="Convert HTML to 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.
//Initialize HTML to PDF converter.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
//Set Blink viewport size.
blinkConverterSettings.ViewPortSize = new Syncfusion.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 and close the document.
document.Save(stream);
document.Close();
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.
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 Core.