How to generate a PDF from HTML in C# and ASP.NET Core
Published 2 min read
In .NET, turning HTML into a PDF usually means adding a rendering library and the native pieces
it depends on to every environment you deploy to. With an API it is one HTTP request, and
HttpClient already does it. This guide shows a small typed client and an ASP.NET Core
endpoint that returns the file, with the rustedf.cloud API.
A typed client
using System.Net.Http.Json;
public sealed class PdfClient(HttpClient http){ public async Task<byte[]> RenderAsync( string templateId, Dictionary<string, object?> data, string locale = "en-US", CancellationToken cancellationToken = default) { using var response = await http.PostAsJsonAsync( "v1/render", new { template_id = templateId, locale, data }, 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); }}
public sealed record ErrorBody(ErrorDetail? Error);public sealed record ErrorDetail(string? Code, string? Message);A successful response is the PDF itself, so the bytes are the file. On a failure the body is JSON
with a stable code and a message.
Build data as a dictionary. System.Text.Json renames the properties of a class or an
anonymous object (CustomerName becomes customerName), and the keys of your template must match
exactly. The keys of a dictionary are left as you write them.
Register it and serve a PDF
using System.Net.Http.Headers;
builder.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);});
app.MapGet("/invoices/{number}.pdf", async (string number, PdfClient pdf) =>{ var data = new Dictionary<string, object?> { ["number"] = number, ["customer"] = new Dictionary<string, object?> { ["name"] = "Ana Souza" }, ["total"] = "2040.50", }; var file = await pdf.RenderAsync(builder.Configuration["Rustedf:InvoiceTemplate"]!, data, "pt-BR"); return Results.File(file, "application/pdf");});Keep the key in configuration, a secret store or an environment variable
(Rustedf__Key), never in a view or in the browser. Set the timeout above the time limit of your
plan, so your request does not give up before the service does.
To send HTML instead of a saved template id, use an html property in place of template_id.
Pass anything a user typed through data, not inside the HTML string: values in data are
escaped, and the HTML itself is read as a template.
Retry when the service is busy
A 429 (rate limit) or a 503 (busy) carries a Retry-After header. A failed render costs no
credit, so retrying is safe.
if (response.StatusCode is HttpStatusCode.TooManyRequests or HttpStatusCode.ServiceUnavailable){ var wait = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(2); await Task.Delay(wait, cancellationToken); // send the request again, a limited number of times}Errors worth handling
| Status | code |
What to do |
|---|---|---|
| 401 | unauthorized |
The key is missing, wrong or revoked. |
| 402 | insufficient_credits |
No credits left. Nothing was rendered. |
| 422 | invalid_template |
The template or its data failed. Read message. |
| 429 | rate_limited |
Wait for Retry-After and retry. |
| 503 | busy |
The service is busy. Wait for Retry-After and retry. |
| 504 | render_timeout |
The document took longer than your plan allows. |
Run POST /v1/validate with the same body while you build the template: it lists anything the
service did not fully support, without returning the PDF or using a credit.
Read Rendering a PDF, Authentication and Errors and limits.
More guides for C#
- Generate a PDF in ASP.NET Core: MVC, Razor Pages and minimal APIs
- Convert a web page to PDF in C# without a headless browser
- C# PDF report generator: a paged table with totals and page numbers
- Save a PDF in C#: to disk, as a download or in blob storage
- HTML to PDF in C#: PdfSharp, QuestPDF, iText, Puppeteer or an API
- Generate a PDF in Blazor: Server and WebAssembly
- Generate a PDF in Azure Functions without bundling a browser
- Generate thousands of PDFs in C#: pacing, 429 and safe retries
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