Generate a PDF in Blazor: Server and WebAssembly
Published 3 min read
Blazor runs C# in two places: on the server, or in the visitor’s browser as WebAssembly. That difference decides how a PDF is made. The rustedf.cloud API is called with a secret key, and the key must stay on a server. So whichever kind of Blazor you use, the call to the API is made by code that runs on your server, and the browser only receives the finished file.
This guide uses the typed client from the C# and ASP.NET Core guide and shows three ways to hand the file to the user.
The rule: the key never reaches the browser
A Blazor WebAssembly app is downloaded and run by each visitor. Everything in it, including
wwwroot/appsettings.json, can be read by anyone. A key put there is public, and anyone with a
key can spend your credits. The service also refuses requests that come from a web page.
Keep the key in the server project, in configuration or a secret store:
// Server project, Program.csbuilder.Services.AddHttpClient<PdfClient>(client =>{ client.BaseAddress = new Uri("https://api.rustedf.com/"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", builder.Configuration["Rustedf:Key"]); client.Timeout = TimeSpan.FromSeconds(40);});An endpoint for the file
For Blazor WebAssembly, and for Blazor Server too, the simplest design is an endpoint in the ASP.NET Core project that returns the PDF:
app.MapGet("/invoices/{number}.pdf", async (string number, PdfClient pdf, ClaimsPrincipal user) =>{ // Check here that this user may see this invoice. var data = await LoadInvoiceDataAsync(number); var file = await pdf.RenderAsync(invoiceTemplateId, data, "en-US"); return Results.File(file, "application/pdf", fileDownloadName: $"invoice-{number}.pdf");}).RequireAuthorization();The check matters: an endpoint that takes a number and returns a document is a way to read other people’s documents if it does not ask who is asking. Because the page and the endpoint share an origin, the sign-in cookie goes with the request.
A download button
In a component, send the browser to the endpoint. A response with a file name is downloaded, and the page stays where it is:
@inject NavigationManager Navigation
<button @onclick="Download">Download PDF</button>
@code { [Parameter] public string Number { get; set; } = "";
private void Download() => Navigation.NavigateTo($"/invoices/{Number}.pdf", forceLoad: true);}A preview in the page
Leave the file name out of the response, and the browser shows the PDF instead of downloading
it. Then an iframe is a preview:
<iframe src="/invoices/@Number/preview.pdf" title="Invoice @Number" style="width:100%; height:80vh; border:0"></iframe>with an endpoint like the one above that calls Results.File(file, "application/pdf") without
the third argument.
Blazor Server: download from a component
In Blazor Server a component runs on the server, so it can inject PdfClient directly and ask for
the PDF without an endpoint. To give the file to the browser, stream it through JavaScript
interop:
@inject PdfClient Pdf@inject IJSRuntime JS
<button @onclick="DownloadAsync">Download PDF</button>
@code { private async Task DownloadAsync() { var file = await Pdf.RenderAsync(invoiceTemplateId, data, "en-US"); using var stream = new MemoryStream(file); using var reference = new DotNetStreamReference(stream); await JS.InvokeVoidAsync("downloadFileFromStream", "invoice.pdf", reference); }}<!-- App.razor or wwwroot/index.html --><script> window.downloadFileFromStream = async (fileName, contentStreamReference) => { const buffer = await contentStreamReference.arrayBuffer(); const url = URL.createObjectURL(new Blob([buffer])); const anchor = document.createElement('a'); anchor.href = url; anchor.download = fileName ?? ''; anchor.click(); anchor.remove(); URL.revokeObjectURL(url); };</script>A stream reference sends the file in pieces. Passing a large PDF as one byte[] or a base64 string
through interop runs into the size limit of the connection between the browser and the server.
Mistakes to avoid
- The key in a WebAssembly project. Not in
appsettings.json, not in a constant, not in a request made from the browser. - An endpoint without authorization. The number in the address must be checked against the user.
- User text in the HTML. If you send HTML instead of a saved template, the
htmlfield is a template, so text with{{in it is read as a placeholder. Send what users type indata. - No timeout. Set the
HttpClienttimeout above the time limit of your plan, and show the user a message when the call fails.
Read Rendering a PDF, Authentication and Errors and limits.
Keep reading
Code and integrations
Generate a PDF in ASP.NET Core: MVC, Razor Pages and minimal APIs
Turn a Razor view into a PDF in ASP.NET Core with one API call: a view renderer, a print-ready view, an MVC action, a Razor Pages handler and the traps to avoid.
3 min read
Code and integrations
Convert a web page to PDF in C# without a headless browser
Fetch a page with HttpClient and turn its HTML into a PDF with one API call in C#. Which pages this suits, which it does not, and how to check before you rely on it.
3 min read
Code and integrations
C# PDF report generator: a paged table with totals and page numbers
Build a PDF report in C# from a list of objects: a table whose header repeats on every page, a total, page numbers and the page count, with one HTTP call.
3 min read
Code and integrations
Save a PDF in C#: to disk, as a download or in blob storage
Save the PDF returned by a render call in C#: write it to disk, send it as a download from ASP.NET Core, keep a signed link or upload it, and avoid saving an error.
2 min read