Create PDF files in Blazor

date Mar 15, 2023

Creating PDF files in Blazor and calling them from the browser is really easy with the Rotativa.io Asp.Net Core client.

The Rotativa.io PDF service client will make a HTTP call to the Rotativa.io API service, This way you can bypass the typical problems that arise when attempting to install and operate PDF tools on a server. And you can deploy your code on Windows or Linux machines without any concerns about dealing with diverse environments.

Installation is easy. You need to add the Rotativaio.AspNetCore package to you project.

PM> Install-Package Rotativaio.AspNetCore

Or

> dotnet add package Rotativaio.AspNetCore

Configuration is done by code in the Program.cs file, by adding a call to the AddRotativaIo services extension method and adding routing for controllers:

builder.Services.AddRotativaIo("<YOUR ENDPOINT>", "<YOUR KEY>");

app.MapControllerRoute("mvc", "{controller}/{action}");

You should replace placeholders with the values you will find in your account preferences page. You can register for one at the Rotativa.io Singup page (free account is available).

You will need to add an MVC controller to your project and add using Rotativaio.AspNetCore; to reference the Rotativa.io client:

using Microsoft.AspNetCore.Mvc;
using Rotativaio.AspNetCore;

namespace RotativaIoBlazorSample.Controllers
{
    public class PdfController : Controller
    {
        ....
    }
}

You’ll need to add a razor view file (.cshtml) for each PDF you’ll need to produce. It will work exactly like regular Asp.net MVC apps.

Creating PDF docs from your views will be exactly the same as in Rotativa:

public IActionResult Index()
{
    return new ViewAsPdf();
}

You’ll need to add a javascript function to the ~/Pages/Layout.cshtml file, it will let client side code download PDF files.

<script>
    window.triggerFileDownload = (fileName, url) => {
        const anchorElement = document.createElement('a');
        anchorElement.href = url;
        anchorElement.download = fileName ?? '';
        anchorElement.click();
        anchorElement.remove();
    }
</script>

In razor pages you just need to add code to call the javascript function we added to the Layout.chtml file.

@inject IJSRuntime JS
@code {
    private async Task DownloadFileFromURL(string name)
    {
        var fileURL = "Pdf/" + name;
        await JS.InvokeVoidAsync("triggerFileDownload", name, fileURL);
    }
}

And call it from the page html:

<NavLink class="nav-link" @onclick="@( e => DownloadFileFromURL("pdf-view-name"))">

You can find all the code mentioned here in a sample project on Github:

https://github.com/RotativaHQ/RotativaIoBlazorSample