Articles in this section
Category / Section

How to convert HTML to PDF in Blazor using C#?

3 mins read

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 an HTML to PDF in Blazor framework using C#.

Steps to convert HTML to PDF in Blazor application

  1. Create a new C# Blazor application project. Select Blazor App from the template and click the Next button.

Create a new Blazor application project

  1. Now, the project configuration window appears. Click Create button to create a new project with the default project configuration.

Configure new project

  1. Choose Blazor Server App from the dashboard and click Create button to create a new Blazor server application.

Create a new Blazor application

  1. Install the  Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package as a reference to your Blazor application from nuget.org.

NuGet package reference

  1. Create a new class file named ExportService under Data folder and include the following namespaces in the file.

 

Create a new class file

  1. Add the following namespace in ExportService class.

C#

using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using System.IO;

 

  1. Use the following code sample to convert HTML to PDF document.
    //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;
    }
    

 

  1. 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>();
    }
    

 

  1. Inject ExportService in-to FetchData.razor using the following code.
    @inject ExportToFileService exportService
    @inject Microsoft.JSInterop.IJSRuntime JS
    @using  System.IO;
    

 

  1. Create a button in the FetchData.razor using the following code.
    <button class="btn btn-primary" @onclick="@ExportToPdf">Export to PDF</button>
    

 

  1.   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());
            }
        }
    }
    
  1. Create a class file with FileUtil name 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));
    }
    

 

  1. 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.

Output window

Click the Export to PDF button, and you will get the PDF document with the following output.

Resultant PDF document from HTML to PDF conversion

A complete work sample for converting an HTML to PDF in the Blazor framework can be downloaded from BlazorHTMLToPDF.Zip.

Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document 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.

Note:

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please  to leave a comment
Access denied
Access denied