Convert HTML to PDF in Blazor

The Syncfusion® HTML to PDF converter is a .NET library for converting HTML content or web pages to PDF documents within Blazor applications. This guide details the process for Blazor Server applications.

NOTE

The HTML to PDF converter is supported in Blazor Server applications. For Blazor WebAssembly (WASM), conversion must be handled on a server due to platform limitations.

Steps to convert an HTML to a PDF file in a Blazor application

Prerequisites:

  • Install .NET SDK: Ensure that you have the .NET SDK installed on your system. You can download it from the .NET Downloads page.
  • Install Visual Studio: Download and install Visual Studio Code from the official website.

Step 1: Create a new C# Blazor project. Select the Blazor Web App template. Blazor sample creation

Step 2: Configure the project. Set the Interactive render mode to Server. Blazor server app

Step 3: Install the Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package as a reference to the project. NuGet package installation

NOTE

Starting with v16.2.0.x, if referencing Syncfusion® assemblies from trial setup or from the NuGet feed, add “Syncfusion.Licensing” assembly reference and include a license key in projects. Refer to this link to learn about registering Syncfusion® license key in applications to use the components.

Step 4: Create a new class file named ExportService.cs in the Data folder and add the following namespaces.

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

    Step 5: Add the following code to convert HTML to PDF document in ExportService class using Convert method in HtmlToPdfConverter class.

  • C#
  • public MemoryStream CreatePdf(string url)
    {
        //Initialize HTML to PDF converter.
        HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();    
        //Convert URL to PDF document.
        PdfDocument document = htmlConverter.Convert(url);
        //Create memory stream.
        MemoryStream stream = new MemoryStream();
        //Save the document to memory stream.
        document.Save(stream);
        return stream;
    }

    Step 6: Register your service in the ConfigureServices method available in the Startup.cs class as follows.

  • C#
  • /// <summary>
    /// Register your ExportService 
    /// </summary>
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<WeatherForecastService>();
        services.AddSingleton<ExportService>();
    }

    Step 7: Inject ExportService into FetchData.razor using the following code.

  • C#
  • @inject ExportService exportService
    @inject Microsoft.JSInterop.IJSRuntime JS
    @inject NavigationManager NavigationManager
    @using  System.IO;

    Step 8: Create a button in the FetchData.razor using the following code.

  • C#
  • <button class="btn btn-primary" @onclick="@ExportToPdf">Export to PDF</button>

    Step 9: Add the ExportToPdf method in FetchData.razor page to call the export service.

  • C#
  • @code {
        private string currentUrl;
        /// <summary>
        /// Get the current URL
        /// </summary>
        protected override void OnInitialized()
        {
            currentUrl = NavigationManager.Uri;
        }
    }
    
    @functions
    {
        /// <summary>
        /// Create and download the PDF document
        /// </summary>
        protected async Task ExportToPdf()
        {
            ExportService exportService = new ExportService();
            using (MemoryStream excelStream = exportService.CreatePdf(currentUrl))
            {
                await JS.SaveAs("HTMLToPDF.pdf", excelStream.ToArray());
            }
        }
    }

    Step 10: Create a class file with FileUtil name and add the following code to invoke the JavaScript action to download the file in the browser.

  • C#
  • public static class FileUtil
    {
        public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
         => js.InvokeAsync<object>(
             "saveAsFile",
             filename,
             Convert.ToBase64String(data));
    }

    Step 11: Add the following JavaScript function in the _Host.cshtml available under the Pages folder.

  • C#
  • <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>

    Step 12: Build and run the project by pressing F5 or by selecting Debug > Start Debugging.

    Prerequisites:

    • Install .NET SDK: Ensure that you have the .NET SDK installed on your system. You can download it from the .NET Downloads page.
    • Install Visual Studio Code: Download and install Visual Studio Code from the official website.
    • Install C# Extension for VS Code: Open Visual Studio Code, go to the Extensions view (Ctrl+Shift+X), and search for ‘C#’. Install the official C# extension provided by Microsoft.

    Step 1: Create a new Blazor Server application using the terminal.

    dotnet new blazor -n CreatePdfBlazorApp --interactivity Server
    

    Step 2: Navigate to the project directory.

    cd CreatePdfBlazorApp
    

    Step 3: Use the following command in the terminal to add the Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package.

    dotnet add package Syncfusion.HtmlToPdfConverter.Net.Windows
    

    NOTE

    Starting with v16.2.0.x, if referencing Syncfusion® assemblies from trial setup or from the NuGet feed, add “Syncfusion.Licensing” assembly reference and include a license key in projects. Refer to this link to learn about registering Syncfusion® license key in applications to use the components.

    Step 4: Create a new class file named ExportService.cs under Data folder and include the following namespaces in the file.

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

    Step 5: Add the following code to convert HTML to PDF document in ExportService class using Convert method in HtmlToPdfConverter class.

  • C#
  • public MemoryStream CreatePdf(string url)
    {
        //Initialize HTML to PDF converter.
        HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();    
        //Convert URL to PDF document.
        PdfDocument document = htmlConverter.Convert(url);
        //Create memory stream.
        MemoryStream stream = new MemoryStream();
        //Save the document to memory stream.
        document.Save(stream);
        return stream;
    }

    Step 6: Register your service in the ConfigureServices method available in the Startup.cs class as follows.

  • C#
  • /// <summary>
    /// Register your ExportService 
    /// </summary>
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<WeatherForecastService>();
        services.AddSingleton<ExportService>();
    }

    Step 7: Inject ExportService into FetchData.razor using the following code.

  • C#
  • @inject ExportService exportService
    @inject Microsoft.JSInterop.IJSRuntime JS
    @inject NavigationManager NavigationManager
    @using  System.IO;

    Step 8: Create a button in the FetchData.razor using the following code.

  • C#
  • <button class="btn btn-primary" @onclick="@ExportToPdf">Export to PDF</button>

    Step 9: Add the ExportToPdf method in FetchData.razor page to call the export service.

  • C#
  • @code {
        private string currentUrl;
        /// <summary>
        /// Get the current URL
        /// </summary>
        protected override void OnInitialized()
        {
            currentUrl = NavigationManager.Uri;
        }
    }
    
    @functions
    {
        /// <summary>
        /// Create and download the PDF document
        /// </summary>
        protected async Task ExportToPdf()
        {
            ExportService exportService = new ExportService();
            using (MemoryStream excelStream = exportService.CreatePdf(currentUrl))
            {
                await JS.SaveAs("HTMLToPDF.pdf", excelStream.ToArray());
            }
        }
    }

    Step 10: Create a class file with FileUtil name and add the following code to invoke the JavaScript action to download the file in the browser.

  • C#
  • public static class FileUtil
    {
        public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
         => js.InvokeAsync<object>(
             "saveAsFile",
             filename,
             Convert.ToBase64String(data));
    }

    Step 11: Add the following JavaScript function in the _Host.cshtml available under the Pages folder.

  • C#
  • <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>

    Step 12: Build the project.

    Run the following command in terminal to build the project.

    dotnet build
    

    Step 13: Run the project.

    Run the following command in terminal to build the project.

    dotnet run
    

    Prerequisites:

    • JetBrains Rider.
    • Install .NET 8 SDK or later.

    Step 1. Open JetBrains Rider and create a new Blazor server-side app project.

    • Launch JetBrains Rider.
    • Click new solution on the welcome screen.

    Launch JetBrains Rider

    • In the new Solution dialog, select Project Type as Web.
    • Enter a project name and specify the location.
    • Choose template as Blazor Server App.
    • Select the target framework (e.g., .NET 8.0, .NET 9.0).
    • Click create.

    create a new Blazor server-side app project

    Step 2: Install the NuGet package from NuGet.org.

    • Click the NuGet icon in the Rider toolbar and type Syncfusion.HtmlToPdfConverter.Net.Windows in the search bar.
    • Ensure that “nuget.org” is selected as the package source.
    • Select the latest Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package from the list.
    • Click the + (Add) button to add the package.

    Select the Syncfusion.HtmlToPdfConverter.Net.Windows package

    • Click the Install button to complete the installation.

    Install the package

    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 3: Create a new class file named ExportService.cs under Data folder and include the following namespaces in the file.

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

    Step 4: Add the following code to convert HTML to PDF document in ExportService class using Convert method in HtmlToPdfConverter class.

  • C#
  • public MemoryStream CreatePdf(string url)
    {
        //Initialize HTML to PDF converter.
        HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();    
        //Convert URL to PDF document.
        PdfDocument document = htmlConverter.Convert(url);
        //Create memory stream.
        MemoryStream stream = new MemoryStream();
        //Save the document to memory stream.
        document.Save(stream);
        return stream;
    }

    Step 5: Register your service in the ConfigureServices method available in the Startup.cs class as follows.

  • C#
  • /// <summary>
    /// Register your ExportService 
    /// </summary>
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<WeatherForecastService>();
        services.AddSingleton<ExportService>();
    }

    Step 6: Inject ExportService into FetchData.razor using the following code.

  • C#
  • @inject ExportService exportService
    @inject Microsoft.JSInterop.IJSRuntime JS
    @inject NavigationManager NavigationManager
    @using  System.IO;

    Step 7: Create a button in the FetchData.razor using the following code.

  • C#
  • <button class="btn btn-primary" @onclick="@ExportToPdf">Export to PDF</button>

    Step 8: Add the ExportToPdf method in FetchData.razor page to call the export service.

  • C#
  • @code {
        private string currentUrl;
        /// <summary>
        /// Get the current URL
        /// </summary>
        protected override void OnInitialized()
        {
            currentUrl = NavigationManager.Uri;
        }
    }
    
    @functions
    {
        /// <summary>
        /// Create and download the PDF document
        /// </summary>
        protected async Task ExportToPdf()
        {
            ExportService exportService = new ExportService();
            using (MemoryStream excelStream = exportService.CreatePdf(currentUrl))
            {
                await JS.SaveAs("HTMLToPDF.pdf", excelStream.ToArray());
            }
        }
    }

    Step 9: Create a class file with FileUtil name and add the following code to invoke the JavaScript action to download the file in the browser.

  • C#
  • public static class FileUtil
    {
        public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
         => js.InvokeAsync<object>(
             "saveAsFile",
             filename,
             Convert.ToBase64String(data));
    }

    Step 10: Add the following JavaScript function in the _Host.cshtml available under the Pages folder.

  • C#
  • <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>

    Step 11: Build the project.

    Click the Build button in the toolbar or press Ctrl+Shift+B to build the project.

    Step 12: Run the project.

    Click the Run button (green arrow) in the toolbar or press F5 to run the app.

    Executing the program displays the following output in the browser.
    Browser window

    Click the Export to PDF button will generate a PDF document with the following output.
    HTML to PDF Blazor output

    A complete working sample for converting an HTML to PDF in the Blazor framework can be downloaded from Github.

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

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