Generate a PDF in Azure Functions without bundling a browser
Published 3 min read
A function that makes PDFs usually runs into the same problem: the usual tools need a browser or
native libraries, and a function wants a small package and a quick start. With an HTTP API there
is nothing to bundle. The function builds a request, sends it with HttpClient and returns the
bytes. This guide uses the .NET isolated worker model and the rustedf.cloud API, with the typed
client from the C# and ASP.NET Core guide.
Register the client
using System.Net.Http.Headers;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;
var host = new HostBuilder() .ConfigureFunctionsWorkerDefaults() .ConfigureServices(services => { services.AddHttpClient<PdfClient>(client => { client.BaseAddress = new Uri("https://api.rustedf.com/"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", Environment.GetEnvironmentVariable("RUSTEDF_KEY")); client.Timeout = TimeSpan.FromSeconds(40); }); }) .Build();
host.Run();If AddHttpClient is not found, add the Microsoft.Extensions.Http package.
The key comes from an application setting named RUSTEDF_KEY. Locally it lives in
local.settings.json, which must stay out of source control. In Azure, set it in the app’s
configuration, or as a reference to a Key Vault secret. Never write it into the code.
An HTTP trigger that returns the PDF
using System.Net;using Microsoft.Azure.Functions.Worker;using Microsoft.Azure.Functions.Worker.Http;
public sealed class InvoicePdf(PdfClient pdf){ [Function("InvoicePdf")] public async Task<HttpResponseData> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "invoices/{number}.pdf")] HttpRequestData request, string number, CancellationToken cancellationToken) { var data = await LoadInvoiceDataAsync(number); var file = await pdf.RenderAsync(invoiceTemplateId, data, "en-US", cancellationToken);
var response = request.CreateResponse(HttpStatusCode.OK); response.Headers.Add("Content-Type", "application/pdf"); response.Headers.Add("Content-Disposition", $"attachment; filename=\"invoice-{number}.pdf\""); await response.Body.WriteAsync(file, cancellationToken); return response; }}AuthorizationLevel.Function asks for a function key, so a stranger cannot call the function and
spend your credits. Clean the invoice number before it reaches a file name, and check that the
caller is allowed to see that invoice.
Time limits
A function has limits of its own, and so does the PDF service. Keep three numbers in order: the
HttpClient timeout, above the time limit of your plan so the call does not give up before the
service does; the time the platform allows an HTTP-triggered function to answer; and the size of
the documents you make. A document that takes long to render is a reason to move the work to a
queue, below, instead of holding a web request open.
A queue trigger for batches
When a job is “make this invoice and store it”, let a queue drive it. Each message is one
document, and a failure is retried by the platform. The function below stores the file with
Azure.Storage.Blobs, so register a container client next to the PdfClient:
// in ConfigureServicesservices.AddSingleton(_ => new BlobContainerClient( Environment.GetEnvironmentVariable("STORAGE_CONNECTION"), "invoices"));public sealed class InvoiceBatch(PdfClient pdf, BlobContainerClient container){ [Function("InvoiceBatch")] public async Task Run( [QueueTrigger("invoices-to-render")] string number, CancellationToken cancellationToken) { var data = await LoadInvoiceDataAsync(number); var file = await pdf.RenderAsync(invoiceTemplateId, data, "en-US", cancellationToken);
await container.GetBlobClient($"invoices/{number}.pdf") .UploadAsync(new BinaryData(file), overwrite: true, cancellationToken); }}Two points make this safe:
- Let the right errors escape. A
429(rate limit) and a503(busy) carry aRetry-Afterheader, and a failed render costs no credit. If the client throws on them, the message goes back on the queue and is tried again, up to the number of attempts that you configure, after which it lands in the poison queue. - Make the work repeatable. Uploading with
overwrite: truemeans a message that runs twice leaves one file. A render that succeeded and then lost its answer costs a credit again when retried, so keep batches to what you can afford to repeat.
Several instances of a function may run at once, and the request rate of your plan is shared by
the whole account. Limit how many messages are processed in parallel in the host settings, so a big
queue does not turn into a wall of 429 answers. The batch guide covers the details:
Generate thousands of PDFs in C#.
Check before you deploy
Send the template and sample data to POST /v1/validate: it reports what the service could not
use, without a PDF and without a credit. In tests, add "strict": true so a document that starts
using something unsupported fails with 422 strict_mode_rejected.
Read Rendering a PDF, Authentication and Errors and limits.
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