rustedf.cloud
Menu

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

Program.cs
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 ConfigureServices
services.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 a 503 (busy) carry a Retry-After header, 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: true means 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.

← All posts