Create a PDF File with Blazor Tutorial

Introduction

The Portable Document Format, or PDF, is a file format created by Adobe. When displaying papers that need the text and graphics to be formatted, PDFs are a helpful format to utilize. The creation of documents and invoices are just two examples of the crucial roles that PDF files play in contemporary society. Thanks to the PDF libraries that are now offered on the market, PDF production has become almost natural. It is crucial to weigh the benefits and features of each PDF library before choosing one to utilize for your project in order to make the best choice.

IronPDF supports Blazor applications. In this article, we are going to IronPDF to generate a PDF report inside of a Blazor application.

1. IronPDF Features

Developers can quickly create, read, and process a PDF document with the help of the robust IronPDF .NET PDF library. IronPDF has a built-in Chrome engine and offers a wealth of practical and potent capabilities. These include the ability to convert HTML5, JavaScript, CSS, and images to PDF, the ability to add unique headers and footers to PDF documents, and the ability to produce PDFs precisely as they appear in a web browser. IronPDF supports various web technologies, including HTML, ASPX, Razor View, and MVC frameworks.

IronPDF's key attributes are as follows:

  • IronPDF gives us control over the creation and modification of PDF files within .NET C# applications
  • IronPDF can generate PDF files of web pages from their URLs using a specific User-Agent, Proxy, Header, and Cookie configurations.
  • IronPDF can generate PDF files for web pages located behind login forms using form variables
  • IronPDF can extract and/or remove photos from preexisitng PDF files
  • IronPDF can add text, photos, bookmarks, watermarks, and other elements to PDF documents
  • IronPDF makes it easy to merge and split pages of one or more PDF documents.
  • IronPDF can process web page assets such as JavaScript, CSs, and media files and render them into PDF documents just as they would appear in a browser.
  • IronPDF supports all .NET Frameworks, including .NET Core, .NET Standard, etc.

2. What is Blazor?

Blazor is an experimental web application framework that makes it feasible to create client-side web applications in C# and HTML using Web Assembly.

Web Assembly apps are sent to the browser in a binary instruction format that is able to operate at close-to-native speed. This has created new potential for languages like C# to run inside the browser.

Creating a New Project in Visual Studio

To begin, open the Microsoft Visual Studio application and select “New Project” from the File menu. Then, select “Blazor Server App”.

Create PDFs in Blazor using IronPDF, Figure 1: Creating a New Project in Visual Studio

Enter a project name and select a file path. Then, click the Create button.

Create PDFs in Blazor using IronPDF, Figure 2: Choosing the name and location of the new Blazor Application

Select the desired .NET Framework (we will use .NET 6.0 in this tutorial), as shown in the screenshot below:

Create PDFs in Blazor using IronPDF, Figure 3: Creating a New Project in Visual Studio with the .NET 6.0 Framework

Microsoft Visual Studio will now generate the structure for our Blazor application.

Next, we will add the IronPDF library to our new project.

3. Install the IronPDF Library

The IronPDF Library can be downloaded and installed in four ways:

  • Using Visual Studio’s NuGet package manager
  • Using Visual Studio’s Command-Line
  • Downloading directly from the NuGet website
  • Downloading directly from the IronPDF website

3.1 Using Visual Studio’s NuGet Package Manager

Visual Studio provides the NuGet Package Manager to assist in installing libraries directly into projects. The screenshot below shows how to open the NuGet Package Manager.

Create PDFs in Blazor using IronPDF, Figure 4: Accessing Visual Studio's NuGet Package Manager

Use the search field under the Browse tab to search for "IronPDF", as shown in the screenshot below:

Create PDFs in Blazor using IronPDF, Figure 5: Searching for the IronPDF library in the NuGet Package Manager GUI

In the image above we see the list of the related search results. Select the required options in order to install the package into your project.

3.2 Using Visual Studio Command-Line

In Visual Studio, go to Tools > NuGet Package Manager -> Package manager console

Enter the following line into the package manager console tab:

Install-Package IronPdf

The package will now be downloaded and be installed in the current project.

Create PDFs in Blazor using IronPDF, Figure 6: Installing the IronPDF library using the NuGet Package Manager Console

3.3 Downloading Directly from the NuGet Website

The third way to install the IronPDF library is to download the NuGet package directly from the website.

Navigate to https://www.nuget.org/packages/IronPdf/

  • Click the "Download Package" option from the menu on the right-hand side.
  • Open the downloaded package on your file system. It will be installed automatically.
  • Reload the solution and start using it in your project.

3.4 Downloading Directly from the IronPDF Website

Click this link to download the latest package directly from our website.

After downloading, follow these steps to add the package to your project:

  • Right-click the project from the solution window.
  • Select the option "Reference," and then navigate to the location of the library that you downloaded previously.
  • Click OK to add the library as a reference.

4. Create PDF documents in the Blazor Server App

The Blazor app that we will be creating in this tutorial will use IronPDF to fetch a web page's HTML content by its URL and convert it into a PDF document.

Enter the following source code in the .razor file contained in the project.

@using IronPdf;
public void ExportData()
{
    try
    {
        string fileName = "Demo.pdf";
        var Renderer = new IronPdf.ChromePdfRenderer();
        var pdf = Renderer.RenderUrlAsPdf("https://localhost:7018/fetchdata");
        JSRuntime.InvokeVoidAsync("saveAsFile", fileName, Convert.ToBase64String(pdf.Stream.ToArray()));
    }
    catch (Exception ex)
    {

    }
}
@using IronPdf;
public void ExportData()
{
    try
    {
        string fileName = "Demo.pdf";
        var Renderer = new IronPdf.ChromePdfRenderer();
        var pdf = Renderer.RenderUrlAsPdf("https://localhost:7018/fetchdata");
        JSRuntime.InvokeVoidAsync("saveAsFile", fileName, Convert.ToBase64String(pdf.Stream.ToArray()));
    }
    catch (Exception ex)
    {

    }
}
Private IronPdf As [using]
Public Sub ExportData()
	Try
		Dim fileName As String = "Demo.pdf"
		Dim Renderer = New IronPdf.ChromePdfRenderer()
		Dim pdf = Renderer.RenderUrlAsPdf("https://localhost:7018/fetchdata")
		JSRuntime.InvokeVoidAsync("saveAsFile", fileName, Convert.ToBase64String(pdf.Stream.ToArray()))
	Catch ex As Exception

	End Try
End Sub
VB   C#

The code snippet above uses two methods to generate PDF documents from HTML. The first one is IronPDF's RenderUrlAsPdf method, which downloads the HTML content from a given URL and converts it into a PDF format.

The second method is the static JSRuntime.InvokeVoidAsync method, which triggers a browser's JavaScript engine invoke a JavaScript function within scope of the web page that saves the PDF content to a file on the client's file system.

This JavaScript function is included below:

   <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);
            window.navigator.msSaveOrOpenBlob(blob );
        }
        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>
HTML

The JavaScript function above receives the Base64 data from Blazor and converts it a blob before saving it to the client-side location.

Altennatively, The ChromePdfRenderer.SaveAs method can also be used to save PDf documents to the browser's local storage.

5. Create a PDF Document from an HTML String

The following snippet of code shows how to turn an HTML string into a document.

var Renderer = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>")
var Renderer = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>")
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'var Renderer = New IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>")
VB   C#

The preceding example uses the RenderHtmlAsPdf instance method to transform a string of HTML into PDF content. We can supply any amount of HTML strings to the function. Furthermore, we can use the procedures described previously to save this content on the client's computer.

Create PDFs in Blazor using IronPDF, Figure 7: The Blazor PDF Generation Application created in this tutorial

The screenshot above shows the web application that we developed in this tutorial. Clicking on the Download button will trigger the C# code to produce the PDF content, and a JavaScript function to download the PDF content on the client-side.

Conclusion

In this article, we have developed a Blazor web application that uses the IronPDf PDF library to generate PDF files from web pages.

IronPDF is not open source, however, a 30-day free trial key allows you to use it in production without watermarks.