Articles in this section
Category / Section

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

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

Steps to convert HTML to PDF in a 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 the 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 the 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 the 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 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;
    }
  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 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));
    }
    

 

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

Note:

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!

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