How to Convert HTML to PDF using CEF in ASP.NET Core?
Our Syncfusion® HTML-to-PDF converter is a .NET PDF library for converting webpages, SVG MHTML and HTML files to PDF using C#. It uses the popular rendering engine CEF to perform HTML to PDF conversion in Azure App Service (Windows) and Azure Functions (Windows) hosting environments. It is reliable and accurate, preserving all graphics, images, text, fonts, and the layout of the original HTML document or webpage.
We are internally using the CefSharp.OffScreen.NetCore package to perform HTML to PDF conversion with the CEF-based rendering engine. It uses the offscreen browser for conversion. HTML-to-PDF conversion in a Blazor web app using the CEF engine is not directly supported. However, we have a workaround solution that uses ASP.NET Core Web API with a worker service project to achieve the HTML-to-PDF conversion.
Steps to adding HTML-to-PDF conversion using the CEF rendering engine in a Blazor Application using C#
-
Create the Visual Studio project using the worker service template.
-
Install the Syncfusion.HtmlToPdfConverter.Cef.Net.Windows NuGet package as a reference to your console application from Nuget.org.
-
Add the below code snippet in the Worker class.
C#
public async Task<MemoryStream> ConvertUrlToPdfAsync(string url)
{
// Initialize HTML to PDF converter with CEF rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Cef);
// Configure CEF converter settings.
CefConverterSettings settings = new CefConverterSettings();
// Set delay to ensure the page is fully loaded before conversion.
settings.AdditionalDelay = 0;
// Define viewport size to control layout during rendering.
settings.ViewPortSize = new Size(1024, 0);
// Apply CEF converter settings to the HTML converter.
htmlConverter.ConverterSettings = settings;
// Convert the URL to a PDF document.
PdfDocument document = htmlConverter.Convert(url);
// Save the PDF document to a memory stream.
MemoryStream memoryStream = new MemoryStream();
document.Save(memoryStream);
// Close the document to release resources.
document.Close(true);
// Return the PDF document as a memory stream.
return memoryStream;
}
Steps to create the ASP.NET Core Web API project
- Create the ASP.NET Core Web API project.
- Add a reference to the Worker Service in the Web API project.
- Add the Worker Service to the Program.cs file.
C#
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<WorkerService_CEF.Worker>();
- Create a PdfController class and add the following code snippet.
C#
// Define the PdfController as an API controller.
[ApiController]
// Set the route for the controller to match the controller name.
[Route("[controller]")]
public class PdfController : ControllerBase
{
// Declare a private readonly instance of the Worker service.
private readonly Worker _worker;
// Inject the Worker service through the constructor.
public PdfController(Worker worker)
{
_worker = worker;
}
// Define an HTTP GET endpoint for PDF conversion.
[HttpGet("convert")]
public async Task<IActionResult> ConvertUrlToPdf(string url)
{
// Call the Worker service to convert the URL to a PDF and store the result in a memory stream.
MemoryStream pdfStream = await _worker.ConvertUrlToPdfAsync(url);
// Check if the conversion was successful; return a BadRequest if it failed.
if (pdfStream == null)
{
return BadRequest("Failed to convert URL to PDF.");
}
// Return the PDF file with the appropriate content type and filename.
return File(pdfStream.ToArray(), "application/pdf", "output.pdf");
}
}
Steps to Create the Blazor Application
-
Create a new Blazor application.
-
Add the following code to the FetchData.razor file.
C#
<button class="btn btn-primary" @onclick="@ExportToPdf">Export to PDF</button>
@code {
private string currentUrl;
/// <summary>
/// Retrieves the current URL when the component initializes.
/// </summary>
protected override void OnInitialized()
{
// Set the current URL using the Navigation Manager.
currentUrl = NavigationManager.Uri;
}
}
@functions {
private string pdfPath;
/// <summary>
/// Creates and downloads the PDF document from the specified URL.
/// </summary>
protected async Task ExportToPdf()
{
// Check if the current URL is valid before attempting export.
if (!string.IsNullOrEmpty(currentUrl))
{
// Send a GET request to the server endpoint for PDF conversion.
var response = await Http.GetAsync($"https://localhost:7138/Pdf/convert?url={Uri.EscapeDataString(currentUrl)}");
// If the response is successful, download the PDF file.
if (response.IsSuccessStatusCode)
{
// Retrieve the PDF content as a byte array.
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
// Use JavaScript to save the PDF file with a specified name.
await JS.SaveAs("HTMLToPDF.pdf", pdfBytes);
}
}
}
}
Run both the Blazor application and the ASP.NET Core Web API simultaneously, then click the button to convert the current URL into a PDF document.
A complete working sample can be downloaded from HTML-to-PDF-Blazor-CEF-Rendering-Engine.
Conclusion
I hope you enjoyed learning about how to perform HTML-to-PDF conversion in a Blazor application using the CEF rendering engine and C#.
You can refer to HTML to PDF Features section for more information about features in HTML to PDF converter, you can get the details, code examples and demo from this section.
Also, Refer to HTML to PDF Troubleshooting section for troubleshooting HTML to PDF conversion failures and frequently asked questions.