How to convert HTML to PDF in Blazor PDF Viewer using C#?
The Syncfusion HTML to PDF converter is a .NET library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. The result preserves all graphics, images, text, fonts, and the layout of the original HTML document or webpage. Using this library, you can convert HTML to PDF in the Blazor framework using C#.
Steps to convert HTML to PDF in a Blazor application:
- Create a new C# Blazor application project. Select Blazor App from the template and click the Next button.
- Now, the project configuration window appears. Click the Create button to create a new project with the default project configuration.
- Choose Blazor Server App from the dashboard and click the Create button to create a new Blazor server application.
- Install the Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package as a reference to your Blazor application from nuget.org.
- Create a new class file named ExportService under the Data folder and include the following namespaces in the file.
- Add the following namespace in ExportService class.
C#
using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using System.IO;
- Use the following code sample to convert an HTML document to a PDF.
// Export HTML to PDF document. public MemoryStream CreatePdf() { // Initialize HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(); // Convert URL to PDF document PdfDocument document = htmlConverter.Convert("https://www.google.com"); MemoryStream stream = new MemoryStream(); // Save and close the PDF document document.Save(stream); document.Close(true); return stream; }
- Register your service in the ConfigureServices method available in the Startup.cs class as follows.
public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddSingleton<WeatherForecastService>(); services.AddSingleton<ExportService>(); }
- Inject ExportService in-to FetchData.razor using the following code.
@inject ExportToFileService exportService @inject Microsoft.JSInterop.IJSRuntime JS @using System.IO;
- Create a button in the FetchData.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export to PDF</button>
- Add the ExportToPdf method in FetchData.razor page to call the export service.
@functions { protected async Task ExportToPdf() { using (MemoryStream excelStream = PDFExportService.CreatePdf(forecasts)) { await JS.SaveAs("HTMLToPDF.pdf", excelStream.ToArray()); } } }
- Create a class file named FileUtil and add the following code to invoke the JavaScript action to download the file in the browser.
public static class FileUtil { public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data) => js.InvokeAsync<object>( "saveAsFile", filename, Convert.ToBase64String(data)); }
- Add the following JavaScript function in the Host.cshtml available under the Pages folder.
<script type="text/javascript"> function saveAsFile(filename, bytesBase64) { if (navigator.msSaveBlob) { // Download document in Edge browser var data = window.atob(bytesBase64); var bytes = new Uint8Array(data.length); for (var i = 0; i < data.length; i++) { bytes[i] = data.charCodeAt(i); } var blob = new Blob([bytes.buffer], { type: "application/octet-stream" }); navigator.msSaveBlob(blob, filename); } else { var link = document.createElement('a'); link.download = filename; link.href = "data:application/octet-stream;base64," + bytesBase64; document.body.appendChild(link); // Needed for Firefox link.click(); document.body.removeChild(link); } } </script>
By executing the program, you will get the following output in the browser.
Click the Export to PDF button, and you will get the PDF document with the following output.
A complete work sample for converting HTML to PDF in the Blazor framework can be downloaded from BlazorHTMLToPDF.Zip.
Take a moment to peruse the documentation, where you can find instructions for converting HTML pages to PDF documents along with respective customization options and features.
Refer here to explore the rich set of Syncfusion Essential PDF features.
An online sample link for Converting HTML to PDF.
Starting with v16.2.0.x, if you reference Syncfusion® assemblies from the trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without a trial message.
Conclusion
I hope you enjoyed learning about how to convert HTML to PDF in the Blazor framework using C#.
You can refer to our Flutter PDF feature tour page to learn about its other groundbreaking features and documentation, and how to quickly get started with configuration specifications. You can also explore our Flutter PDF Flutter PDF examples to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to explore our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums or feedback portal. We are always happy to assist you!