rustedf.cloud
Menu

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

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

← All posts