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 Asp.Net Core client.

The PDF service client will make a HTTP call to the 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


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

    window.triggerFileDownload = (fileName, url) => {
        const anchorElement = document.createElement('a');
        anchorElement.href = url; = fileName ?? '';;

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: