Generate a PDF in ASP.NET Core: MVC, Razor Pages and minimal APIs
Published 3 min read
In ASP.NET Core you already have a good way to describe a document: a Razor view. The missing step is turning what the view produces into a PDF without bringing a browser into your deployment. This guide renders the view to an HTML string and sends it to the rustedf.cloud API, so the same code serves an MVC action, a Razor Pages handler and a minimal API endpoint.
It builds on the typed client of the C# and ASP.NET Core guide, which sends a saved template and its data. Here the layout stays in your project, as a view.
Render a view to a string
Add a small service that runs a view and returns its HTML:
using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Abstractions;using Microsoft.AspNetCore.Mvc.ModelBinding;using Microsoft.AspNetCore.Mvc.Razor;using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Routing;
public sealed class ViewRenderer(IRazorViewEngine viewEngine, ITempDataProvider tempData){ public async Task<string> RenderAsync<TModel>(HttpContext http, string viewPath, TModel model) { var actionContext = new ActionContext(http, http.GetRouteData(), new ActionDescriptor());
var found = viewEngine.GetView(executingFilePath: null, viewPath, isMainPage: false); if (!found.Success) throw new InvalidOperationException($"View '{viewPath}' was not found.");
var viewData = new ViewDataDictionary<TModel>( new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model, };
using var writer = new StringWriter(); var context = new ViewContext( actionContext, found.View, viewData, new TempDataDictionary(http, tempData), writer, new HtmlHelperOptions());
await found.View.RenderAsync(context); return writer.ToString(); }}builder.Services.AddControllersWithViews(); // or AddRazorPages(): either adds the Razor view enginebuilder.Services.AddScoped<ViewRenderer>();The path is the full path of the view file, such as ~/Views/Pdf/Invoice.cshtml, so it does not
depend on which controller or page is running.
Send the HTML to the API
Add a method to the typed client that sends HTML instead of a template id:
public async Task<byte[]> RenderHtmlAsync( string html, string title, CancellationToken cancellationToken = default){ // The html field is a template: {{ }} and {% %} would be read as placeholders. if (html.Contains("{{") || html.Contains("{%")) throw new InvalidOperationException("The document contains template syntax.");
using var response = await http.PostAsJsonAsync( "v1/render", new { html, title }, cancellationToken);
if (!response.IsSuccessStatusCode) { var body = await response.Content.ReadFromJsonAsync<ErrorBody>(cancellationToken); throw new InvalidOperationException( body?.Error?.Message ?? $"Render failed ({(int)response.StatusCode})"); }
return await response.Content.ReadAsByteArrayAsync(cancellationToken);}The check is there because of the data in your model. Razor escapes < and &, but it leaves
braces alone, so a customer name with {{ in it would reach the API as a placeholder. Rejecting
the document is the simple answer. If that text can legitimately appear, send it as data in a
saved template instead, where it is always treated as text.
A view made for paper
A view for a PDF is not your site’s page. Give it no layout, put the styles inside it, and leave out scripts:
@model InvoiceViewModel@{ Layout = null;}<style> @@page { size: A4; margin: 20mm; @@bottom-right { content: "Page " counter(page) " of " counter(pages); } } table { width: 100%; } th { text-align: left; border-bottom: 1pt solid #000; } td { padding: 3pt 0; border-bottom: 0.5pt solid #ccc; } .number { text-align: right; } tr { break-inside: avoid; }</style>
<img src="@Html.Raw(Model.LogoDataUrl)" width="120" alt="Logo"><h1>Invoice @Model.Number</h1><p>@Model.CustomerName</p>
<table> <thead> <tr><th>Description</th><th class="number">Amount</th></tr> </thead> <tbody> @foreach (var line in Model.Lines) { <tr> <td>@line.Description</td> <td class="number">@line.Amount.ToString("C", Model.Culture)</td> </tr> } </tbody></table>
<p><strong>Total @Model.Total.ToString("C", Model.Culture)</strong></p>Three things in it are easy to get wrong:
@@page. In a.cshtmlfile@pageis a Razor directive, so a CSS at-rule needs the@written twice. The same goes for@@bottom-right.- The image. The renderer never fetches a web address, so a logo cannot be a path such as
/images/logo.png. Read the file in your code, turn it into adata:image/png;base64,…string in the model, and print it withHtml.Raw: the normal encoding rewrites characters such as+in the string. - No layout. The default layout links stylesheets and scripts. A linked file is not what you want in a document, and JavaScript does not run.
An MVC action
public sealed class InvoicesController(ViewRenderer views, PdfClient pdf) : Controller{ [HttpGet("/invoices/{number}.pdf")] public async Task<IActionResult> Pdf(string number, CancellationToken cancellationToken) { var model = await LoadInvoiceAsync(number); var html = await views.RenderAsync(HttpContext, "~/Views/Pdf/Invoice.cshtml", model); var file = await pdf.RenderHtmlAsync(html, $"Invoice {number}", cancellationToken); return File(file, "application/pdf", $"invoice-{number}.pdf"); }}A Razor Pages handler and a minimal API
The service takes an HttpContext, so the same call works anywhere you have one. In a Razor
Pages model:
public async Task<IActionResult> OnGetAsync(string number){ var html = await views.RenderAsync(HttpContext, "~/Views/Pdf/Invoice.cshtml", model); return File(await pdf.RenderHtmlAsync(html, $"Invoice {number}"), "application/pdf");}And in a minimal API, which needs the Razor view engine registered as above:
app.MapGet("/invoices/{number}.pdf", async ( string number, HttpContext http, ViewRenderer views, PdfClient pdf) =>{ var html = await views.RenderAsync(http, "~/Views/Pdf/Invoice.cshtml", model); return Results.File(await pdf.RenderHtmlAsync(html, $"Invoice {number}"), "application/pdf");});Keep the API key in configuration, not in a view, and give the HttpClient a timeout above your
plan’s time limit.
What the renderer does not do
It lays out HTML and CSS for paper and runs no JavaScript, so a chart drawn by a script
arrives empty. Draw it on the server as an image, or as SVG with rect, circle and line,
which are supported. @import and @font-face are ignored, so use the fonts the service
offers; see Fonts.
Send the same HTML to POST /v1/validate while you build the view: it lists what the service
could not use, without a PDF and without a credit. In tests, add "strict": true so a view that
starts using something unsupported fails with 422 strict_mode_rejected.
Read Supported HTML and CSS, Images and Errors and limits. To keep the layout in your account instead of your project, see Render with a saved template.
Keep reading
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
Code and integrations
Generate thousands of PDFs in C#: pacing, 429 and safe retries
Make a batch of PDFs from C# without a wall of 429 errors: pace the calls, retry only what is safe, resume a stopped run and stop when the credits run out.
3 min read