Blazor pdf generator
Tags: csharp, blazor, webassembly, beginners
Published: 2022-09-22 05:33:39

## **Introduction**

Adobe developed the file format known as Portable Document Format, or PDF. PDFs are a useful format to use when exhibiting papers that require the text and visuals to be formatted. Just two of the critical functions that PDF files provide in modern culture are document generation and invoicing. The PDF libraries that are presently available on the market have made the creation of PDFs nearly automatic. Prior to selecting a PDF library to use for your project, it is critical to evaluate the advantages and characteristics of each one.

In this article, we are going to use the Blazor server-side application to generate a pdf report. Iron pdf support Blazor application,

## **1.IronPDF Features**

With the help of the powerful IronPDF PDF.NET library, developers can easily create, read, and change a PDF document. IronPDF, which is based on the Chrome engine, includes a wide range of useful and powerful features, such as the ability to convert HTML5, JavaScript, CSS, and picture files to PDF, add custom Headers and Footers, and create PDFs that exactly match how they appear in a web browser. IronPDF supports a number of web and net formats, including HTML, ASPX, Razor View, and MVC. The following are IronPDF's main characteristics:

- IronPdf assistance offers us command over the generation of PDF files, allowing us to write.NET C# programmes that can create, read, and edit PDF files.
- Generating PDFs from a website URL link that is configured to accept login utilising HTML login forms employing User-Agents, Proxies, Cookies, HTTP Headers, and Form Variables.
- Deleting images from already-published PDF documents.
- Enhancing a PDF document with text, images, bookmarks, watermarks, and other components.
- Combining and dividing the pages of many PDF documents is made easier by these functionalities.
- The capability of documentizing media-type assets, such as CSS files.
- Various frameworks, including Dot Net Core, Dot Net Standard, etc., are supported by IronPDF.

## **2.What is Blazor?**

Blazor is a brand-new experimental web framework that uses Web Assembly to enable the development of client-side web apps in C#. Yes, browsers natively support C#. Languages like C# now have the opportunity to run client-side in the browser because Web Assembly apps are typically delivered to the browser in an efficient binary instruction format that is able to work natively and performantly at speeds that are close to native. Blazor is a brand-new experimental web framework that uses Web Assembly to enable the development of client-side web apps in C#. Yes, browsers natively support C#. In essence, Web Assembly apps are delivered to the browser in a format of efficient binary instructions that can execute natively and effectively at speeds that are close to native. This has opened up new opportunities for the client-side execution of languages like C# in the browser.

## **2.1 Creating a New Project in Visual Studio**

In this article, we are going to use a Blazor Server application to generate PDF documents. To begin, open the Microsoft Visual Studio application and select “new project” from the file menu, then select “Blazor server app”.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4zsii15nn6v02q9tgyfw.png)
Enter a project name and select a file path. Then, click the Create button. Also, select the desired .NET Framework, as shown in the screenshot below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0c0ta6vj1vdpdtfaxyc.png)

Microsoft Visual Studio will now generate the structure for the selected application. If you have selected the Blazor application it will have the list of .razor files where you can enter the code and build/run the application.

Select the .NET framework version. In this example, we are going to use .NET 6.0

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bht3f9sw4ksci8m6f392.png)

Next, we can add the library to test the code.

## **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 option to install the package directly to the solution. The screenshot below shows how to open the Nuget Package Manager.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rckw52thw4bxtzkfyq6c.png)

It provides a search box to find packages from the NuGet website. In the package manager we can simply search for "IronPDF", as shown in the screenshot below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/byyi7u0cnym3pqd84j6q.png)

In the image above we see the list of the related search results. Please select the required options in order to install the package on your system.

## **3.2 Using Visual Studio Command-Line**

In Visual Studio Tool 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 download and installed in the current project ready to be used.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yz1jgi097e7s6vsqic99.png)

## **3.3 Downloading Directly from the NuGet Website**

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

- Navigate to the link "https://www.nuget.org/packages/IronPdf/"
- Select the "download package" option from the menu on the right-hand side.
- Open the downloaded package. 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 browse the location of the downloaded reference.
- Click OK to add the reference.

## **4. Create PDf documents with the Blazor server app**

With IronPDF, producing a PDF is simple. A fresh PDF report will be created from the source file of a website that is generated from a URL.

The Blazor programme lacks a cs file. On the relevant.razor file, the following code can be entered.

```
@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)
        {

        }
    }
```

There are two ways to generate a PDF report that will contain the CSS file for the relevant page and transform the HTML from the URL into a PDF file, as seen in the example above. The first way entails building a PDF document from scratch; the second method entails rendering the URL and saving it as a PDF file on the same line. This speeds up the process by downloading the page source in chunks and turning it into papers. If necessary, we may also use the method SaveAs to save the created file in the server's local storage. The javascript function in Blazor can be called from cs code. utilising the unique feature of the Blazor application.

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

The javascript code mentioned above enables us to download and store documents produced by the Blazor programme. Not only is the function capable of being called from Blazor code, but any Javascript library. The procedure gets the Base64 data from the Blazor server side, converts it to a blob, and stores it to a place on the client side.

## **4.Create pdf Document from HTML String**

IronPDF can be used to convert the webpage source into a document. Here is an illustration of how to create a document from an HTML string. Additionally, it has the capacity to convert any tag element into a PDF file.

```
var Renderer = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>")
```

The previous example shows how to change an HTML string using RenderHtmlAsPdf. In addition, the function that turns the webpage source into a string can accept any amount of HTML strings. By completing the steps above, we can use the aforementioned approach to download the papers.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ktjhkythav2r26r8f75.png)

The screenshot up above shows the page we created for downloading the pdf papers. A javascript library will accept the generated pdf document and launch a c# method to download the file on the client side when the download button is clicked. The supplied information might significantly affect the pdf file.

## **Conclusion**

In this article, I've created a practical PDF library that C# programmers may use to generate PDFs. IronPDF makes programmatic PDF creation simple. Even the most elementary knowledge of programming can be used to understand the library. To use the IronPDF library flawlessly, you must have some basic knowledge. However, it is not open source. The 30-day free trial key can be used, nevertheless, if you want to use it in production without a watermark. You can download the programme from this website.