PDFCraft
ASP.NET Core

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

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

Or by language