PDF generation in ASP.NET Core
Razor gives the HTML and `FileStreamResult` returns it without buffering — but the real reason for a page here is `IHttpClientFactory`, because getting HttpClient lifetime wrong in .NET is a production incident rather than a slowdown.
The code
// Program.cs
builder.Services.AddHttpClient("pdfcraft", client =>
{
client.BaseAddress = new Uri("https://api.pdfcraft.dev/");
client.Timeout = TimeSpan.FromSeconds(60);
client.DefaultRequestHeaders.Authorization =
new("Bearer", builder.Configuration["PdfCraft:ApiKey"]);
});
// InvoiceController.cs
public async Task<IActionResult> Pdf(string id)
{
var html = await razor.RenderToStringAsync("Invoice", await repo.GetAsync(id));
var client = factory.CreateClient("pdfcraft");
var upstream = await client.PostAsJsonAsync("v1/render", new
{
html,
options = new { printBackground = true, margin = new { top = "20mm" } }
});
if (!upstream.IsSuccessStatusCode)
return StatusCode(502, await upstream.Content.ReadAsStringAsync());
return new FileStreamResult(await upstream.Content.ReadAsStreamAsync(), "application/pdf")
{
FileDownloadName = $"invoice-{id}.pdf"
};
}What to watch for
- Use `IHttpClientFactory`. A `new HttpClient()` per request exhausts sockets under load; a single static one never picks up DNS changes. The factory handles both.
- `FileStreamResult` disposes the stream for you once the response is written — do not wrap it in a `using`.
- Configuration, not `Environment.GetEnvironmentVariable`, so the key can come from Key Vault in production without a code change.
Why not run the browser yourself
You can. Puppeteer and Playwright both work, and for a script you run by hand they are the right answer. The cost arrives at the point it becomes a service someone depends on: one long-lived browser per process rather than one per request, a semaphore so four renders do not become forty, a hard timeout that force-closes a hung page before it holds a slot forever, a scheduled restart because Chromium leaks, and a Chromium version you are now responsible for patching.
None of that is hard. All of it is work that has nothing to do with your product, and it fails under concurrency rather than in testing — which is the worst time to discover it.
Other frameworks
- PDF generation in Next.js
- PDF generation in Django
- PDF generation in Ruby on Rails
- PDF generation in Laravel
- PDF generation in AWS Lambda
- PDF generation in Cloudflare Workers
- PDF generation in Supabase Edge Functions
- PDF generation in Spring Boot
- PDF generation in FastAPI
- PDF generation in Express
- PDF generation in n8n