Generate PDFs in ASP.NET Core with Api2Pdf: Razor Components, Typed HttpClient and Background Jobs
Summary. .NET still has no built-in HTML to PDF converter, and the usual workarounds each cost something: commercial libraries such as IronPDF or Aspose bring per-developer licences and a bundled Chromium, PuppeteerSharp or Playwright for .NET make you download, patch and babysit a browser on every server and container, and the wkhtmltopdf wrappers (DinkToPdf, Rotativa) sit on an archived WebKit engine. This guide keeps what ASP.NET Core developers already use, Razor and IHttpClientFactory, and hands rendering to the Api2Pdf Headless Chrome endpoint. You will make a first call with the official NuGet package, build a typed HttpClient with Microsoft.Extensions.Http.Resilience timeouts and retries that suit PDF rendering, render invoices from a Razor component with HtmlRenderer, stream them from a Minimal API endpoint, run a year-end statement job in a BackgroundService that merges and password-protects a packet and writes it straight into S3, and test all of it with WebApplicationFactory.
Using another stack? There are companion posts for Go, Spring Boot, Ruby on Rails, Laravel, FastAPI and Next.js App Router.
The architecture in one paragraph
The API key lives in configuration (user secrets in development, an environment variable or Key Vault in production), never in the browser. Your app renders a Razor component to an HTML string and sends it to POST https://v2.api2pdf.com/chrome/pdf/html with the raw key in the Authorization header (no Bearer prefix). With ?outputBinary=true the response body is the PDF itself, which an endpoint can return with Results.Stream. Without it you get JSON with a FileUrl that Api2Pdf hosts for 24 hours plus a ResponseId; that is the form you chain into merge and password calls. If the PDF belongs in your own bucket, add useCustomStorage and a presigned URL and Api2Pdf uploads it there for you. There is no Chromium in your container, no native dependency in your publish output, and nothing to patch when Chrome ships a security fix.
Step 1: the first PDF with the official NuGet package
Create an account and API key at portal.api2pdf.com. The quickest way to see a PDF is the official Api2Pdf package (2.2.0, netstandard2.0), which wraps every endpoint:
dotnet new console -n Hello && cd Hello
dotnet add package Api2Pdf
export API2PDF_API_KEY=your-key
// Hello/Program.cs
using Api2Pdf;
var apiKey = Environment.GetEnvironmentVariable("API2PDF_API_KEY")
?? throw new InvalidOperationException("Set API2PDF_API_KEY");
var client = new Api2Pdf.Api2Pdf(apiKey);
var result = await client.Chrome.HtmlToPdfAsync(new ChromeHtmlToPdfRequest
{
Html = "<h1>Hello from .NET</h1><p>Rendered by Headless Chrome.</p>",
FileName = "hello.pdf"
});
if (!result.Success)
{
Console.Error.WriteLine($"Api2Pdf error: {result.Error}");
return 1;
}
Console.WriteLine($"{result.FileUrl} (cost ${result.Cost}, response {result.ResponseId})");
return 0;
dotnet run prints a link to the PDF. Note the fully qualified Api2Pdf.Api2Pdf: the class and its namespace share a name. The package is a fine choice for scripts, console tools and older .NET Framework apps. In an ASP.NET Core app you usually want the HTTP calls to go through IHttpClientFactory instead, so they share pooled connections, get resilience policies and telemetry from the host, and can be faked in tests. The API is JSON over HTTPS, so a typed client takes about 150 lines, and the rest of this post builds one. All code below was compiled and tested with the .NET 10 SDK. It uses C# 12 features (primary constructors, collection expressions), so it needs .NET 8 or later.
dotnet new web -n Billing && cd Billing
dotnet add package Microsoft.Extensions.Http.Resilience
dotnet add package AWSSDK.S3
dotnet user-secrets init
dotnet user-secrets set "Api2Pdf:ApiKey" "your-key"
In production, set the same key as the environment variable Api2Pdf__ApiKey (double underscore) or load it from your secrets manager. appsettings.json only holds the non-secret parts:
{
"Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } },
"AllowedHosts": "*",
"Api2Pdf": { "BaseUrl": "https://v2.api2pdf.com" },
"Storage": { "Bucket": "my-billing-pdfs" }
}
Step 2: options and request and response records
Bind the configuration to an options class and validate it at startup, so a missing key fails the deployment instead of the first customer download:
// Billing/Api2Pdf/Api2PdfOptions.cs
using System.ComponentModel.DataAnnotations;
namespace Billing.Api2Pdf;
public sealed class Api2PdfOptions
{
public const string StandardBaseUrl = "https://v2.api2pdf.com";
public const string XlBaseUrl = "https://v2-xl.api2pdf.com"; // 4 CPU, 8 GB, 5 minute limit
[Required]
public string ApiKey { get; set; } = "";
[Required, Url]
public string BaseUrl { get; set; } = StandardBaseUrl;
}
The /chrome/pdf/html body takes html plus the optional fileName, inline, options (the Headless Chrome options) and, for your own storage, useCustomStorage and storage. Every JSON response carries Success, Error, FileUrl, MbOut, Seconds, Cost and ResponseId. Records with nullable properties map onto that cleanly: anything you leave null is not sent, so the API defaults apply. The password endpoint spells its fields userpassword and ownerpassword, so those get an explicit [JsonPropertyName]:
// Billing/Api2Pdf/Models.cs
using System.Text.Json.Serialization;
namespace Billing.Api2Pdf;
// Headless Chrome PDF options. Null properties are not sent, so the API
// defaults apply (A4, .4in margins). Units are strings such as "8.5in".
public sealed record ChromePdfOptions
{
public bool? Landscape { get; init; }
public bool? PrintBackground { get; init; }
public double? Scale { get; init; }
public string? Width { get; init; }
public string? Height { get; init; }
public string? MarginTop { get; init; }
public string? MarginBottom { get; init; }
public string? MarginLeft { get; init; }
public string? MarginRight { get; init; }
public string? PageRanges { get; init; }
[JsonPropertyName("preferCSSPageSize")]
public bool? PreferCssPageSize { get; init; }
public bool? DisplayHeaderFooter { get; init; }
public string? HeaderTemplate { get; init; }
public string? FooterTemplate { get; init; }
public int? Delay { get; init; } // milliseconds
public string? PuppeteerWaitForMethod { get; init; }
public string? PuppeteerWaitForValue { get; init; }
}
// Tells Api2Pdf to upload the result to your own storage (an S3 presigned
// PUT URL, a GCS signed URL or an Azure SAS URL) instead of hosting it.
public sealed record Api2PdfStorage(
string Method,
string Url,
[property: JsonPropertyName("extraHTTPHeaders")] IReadOnlyDictionary<string, string>? ExtraHttpHeaders = null);
// Body of POST /chrome/pdf/html.
public sealed record HtmlToPdfRequest(string Html)
{
public string? FileName { get; init; }
public bool Inline { get; init; }
public ChromePdfOptions? Options { get; init; }
public bool? UseCustomStorage { get; init; }
public Api2PdfStorage? Storage { get; init; }
}
// Body of POST /pdfsharp/merge. The PDFs are merged in list order.
public sealed record MergeRequest(IReadOnlyList<string> Urls)
{
public string? FileName { get; init; }
public bool Inline { get; init; }
public bool? UseCustomStorage { get; init; }
public Api2PdfStorage? Storage { get; init; }
}
// Body of POST /pdfsharp/password. The field names are lower case on the wire.
public sealed record PasswordRequest(
string Url,
[property: JsonPropertyName("userpassword")] string UserPassword)
{
[JsonPropertyName("ownerpassword")]
public string? OwnerPassword { get; init; }
public string? FileName { get; init; }
public bool Inline { get; init; }
public bool? UseCustomStorage { get; init; }
public Api2PdfStorage? Storage { get; init; }
}
// JSON response of every conversion endpoint. FileUrl is hosted for 24 hours.
public sealed record Api2PdfResult(
bool Success,
string? Error,
string? FileUrl,
double MbOut,
double Seconds,
double Cost,
string? ResponseId);
Step 3: one exception type
Failures surface as a single exception that carries the operation, the HTTP status and the ResponseId. The id is what you log and quote to support; the HTML you sent usually contains personal data and should stay out of your logs:
// Billing/Api2Pdf/Api2PdfException.cs
using System.Net;
namespace Billing.Api2Pdf;
public sealed class Api2PdfException(string operation, string message, HttpStatusCode? statusCode = null, string? responseId = null)
: Exception($"{operation} failed ({(int?)statusCode}): {message}")
{
public string Operation { get; } = operation;
public HttpStatusCode? StatusCode { get; } = statusCode;
public string? ResponseId { get; } = responseId; // quote this to support, never the HTML
}
Step 4: a typed HttpClient
The client takes an HttpClient in its constructor and nothing else. The factory hands it one with the base address, the key and the resilience pipeline already attached (Step 5). Two details matter in production:
- Binary responses are streamed, not buffered.
HtmlToPdfStreamAsyncsends the request withHttpCompletionOption.ResponseHeadersRead, peeks at the first four bytes through aPipeReaderto confirm the body starts with%PDF, un-reads them withAdvanceTo(buffer.Start), and returns the stream. A 40 MB report never sits in memory. - Errors are parsed from JSON. Api2Pdf answers failures with
{"Success":false,"Error":"..."}, also when you asked for binary output, and a200withSuccess: falseis still a failure.
// Billing/Api2Pdf/Api2PdfClient.cs
using System.IO.Pipelines;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Billing.Api2Pdf;
// A typed HttpClient. IHttpClientFactory supplies the HttpClient with the
// base address, the Authorization header and the resilience pipeline.
public sealed class Api2PdfClient(HttpClient http)
{
internal static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
// Renders HTML and returns the hosted file. Use this form to chain
// calls (merge, password) or when the result goes to custom storage.
public Task<Api2PdfResult> HtmlToPdfAsync(HtmlToPdfRequest request, CancellationToken ct = default) =>
PostJsonAsync("chrome/pdf/html", request, ct);
public Task<Api2PdfResult> MergeAsync(MergeRequest request, CancellationToken ct = default) =>
PostJsonAsync("pdfsharp/merge", request, ct);
public Task<Api2PdfResult> PasswordAsync(PasswordRequest request, CancellationToken ct = default) =>
PostJsonAsync("pdfsharp/password", request, ct);
// Renders HTML with outputBinary=true and returns the PDF as a stream
// that is read from the network as the caller consumes it.
public async Task<Stream> HtmlToPdfStreamAsync(HtmlToPdfRequest request, CancellationToken ct = default)
{
const string op = "POST chrome/pdf/html";
using var message = new HttpRequestMessage(HttpMethod.Post, "chrome/pdf/html?outputBinary=true")
{
Content = JsonContent.Create(request, options: Json)
};
var response = await http.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, ct);
if (!response.IsSuccessStatusCode)
{
using (response) throw await ErrorFromAsync(op, response, ct);
}
// Peek at the magic bytes without buffering the document.
var reader = PipeReader.Create(await response.Content.ReadAsStreamAsync(ct));
var head = await reader.ReadAtLeastAsync(4, ct);
var isPdf = head.Buffer.Length >= 4 && Encoding.ASCII.GetString(head.Buffer.Slice(0, 4)) == "%PDF";
if (!isPdf)
{
var excerpt = Encoding.UTF8.GetString(head.Buffer.Slice(0, Math.Min(head.Buffer.Length, 500)));
await reader.CompleteAsync();
response.Dispose();
throw new Api2PdfException(op, "response is not a PDF: " + excerpt, response.StatusCode);
}
reader.AdvanceTo(head.Buffer.Start); // un-read the peeked bytes
return reader.AsStream(); // disposing it disposes the response stream
}
// Deletes a hosted file before its 24 hour expiry.
public async Task DeleteAsync(string responseId, CancellationToken ct = default)
{
using var response = await http.DeleteAsync($"file/{Uri.EscapeDataString(responseId)}", ct);
if (!response.IsSuccessStatusCode)
{
throw await ErrorFromAsync("DELETE file", response, ct);
}
}
private async Task<Api2PdfResult> PostJsonAsync<T>(string path, T body, CancellationToken ct)
{
var op = "POST " + path;
using var response = await http.PostAsJsonAsync(path, body, Json, ct);
if (!response.IsSuccessStatusCode)
{
throw await ErrorFromAsync(op, response, ct);
}
var result = await response.Content.ReadFromJsonAsync<Api2PdfResult>(Json, ct)
?? throw new Api2PdfException(op, "empty response body", response.StatusCode);
if (!result.Success)
{
throw new Api2PdfException(op, result.Error ?? "unknown error", response.StatusCode, result.ResponseId);
}
return result;
}
// Failures come back as JSON ({"Success":false,"Error":"..."}), also
// when outputBinary=true was requested.
private static async Task<Api2PdfException> ErrorFromAsync(string op, HttpResponseMessage response, CancellationToken ct)
{
var raw = await response.Content.ReadAsStringAsync(ct);
try
{
var result = JsonSerializer.Deserialize<Api2PdfResult>(raw, Json);
if (!string.IsNullOrEmpty(result?.Error))
{
return new Api2PdfException(op, result.Error, response.StatusCode, result.ResponseId);
}
}
catch (JsonException)
{
}
var message = string.IsNullOrWhiteSpace(raw) ? response.ReasonPhrase ?? "error" : raw[..Math.Min(raw.Length, 500)];
return new Api2PdfException(op, message, response.StatusCode);
}
}
Step 5: register it with timeouts that fit PDF rendering
AddStandardResilienceHandler adds the Polly v8 pipeline Microsoft recommends for outgoing HTTP: a total timeout, retries with exponential backoff and jitter for 408, 429, 5xx and network errors (honouring Retry-After), a circuit breaker and a per-attempt timeout. Its defaults are tuned for chatty microservice calls, though: 10 seconds per attempt and 30 seconds in total. A 40-page report would be cancelled mid-render and retried until the total budget ran out. Standard Api2Pdf requests get up to 90 seconds of processing, so give each attempt 100 seconds and the whole call four minutes:
// Billing/Api2Pdf/ServiceCollectionExtensions.cs
using Microsoft.Extensions.Options;
namespace Billing.Api2Pdf;
public static class ServiceCollectionExtensions
{
public static IHttpClientBuilder AddApi2Pdf(this IServiceCollection services)
{
services.AddOptions<Api2PdfOptions>()
.BindConfiguration("Api2Pdf")
.ValidateDataAnnotations()
.ValidateOnStart();
var builder = services.AddHttpClient<Api2PdfClient>((sp, http) =>
{
var options = sp.GetRequiredService<IOptions<Api2PdfOptions>>().Value;
http.BaseAddress = new Uri(options.BaseUrl.TrimEnd('/') + "/");
// The raw key, no "Bearer" prefix.
http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", options.ApiKey.Trim());
// The resilience pipeline below owns the timeouts.
http.Timeout = Timeout.InfiniteTimeSpan;
});
builder.AddStandardResilienceHandler(r =>
{
// The defaults (10 s per attempt, 30 s in total) are tuned for
// chatty microservice calls and would cut renders off mid-flight.
r.AttemptTimeout.Timeout = TimeSpan.FromSeconds(100);
r.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(200); // must be >= 2x the attempt timeout
r.TotalRequestTimeout.Timeout = TimeSpan.FromMinutes(4);
r.Retry.MaxRetryAttempts = 3;
r.Retry.Delay = TimeSpan.FromSeconds(1);
});
return builder;
}
}
HttpClient.Timeoutmust not fight the pipeline. It defaults to 100 seconds and wraps every retry, so leave it infinite and let the resilience handler own the timeouts.- The circuit breaker validates its window.
SamplingDurationhas to be at least twice the attempt timeout, or resolving the client throwsOptionsValidationException: The sampling duration of circuit breaker strategy needs to be at least double of an attempt timeout strategy's timeout interval. That is why it is raised to 200 seconds. - Retrying a POST is safe here. The standard handler retries every method. An Api2Pdf conversion changes nothing on your side, so the worst case of a retried render is paying for it twice. With
useCustomStoragea retry overwrites the same object key. If you would rather not retry POSTs, callr.Retry.DisableForUnsafeHttpMethods()(namespaceMicrosoft.Extensions.Http.Resilience). - Streaming and timeouts. With
outputBinary=true, Api2Pdf renders the whole PDF before it sends the response headers, so the render is covered by the attempt timeout. Reading the body afterwards is bounded by the cancellation token you pass in, which in an endpoint is the request's own.
Program.cs wires everything together:
// Billing/Program.cs
using Amazon.S3;
using Billing.Api2Pdf;
using Billing.Invoices;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddApi2Pdf(); // typed HttpClient + resilience
builder.Services.AddSingleton<IInvoiceStore, InMemoryInvoiceStore>();
builder.Services.AddScoped<InvoiceRenderer>();
builder.Services.AddSingleton<IAmazonS3, AmazonS3Client>(); // credentials from the default AWS chain
builder.Services.AddSingleton<S3PdfStorage>();
builder.Services.AddSingleton<StatementQueue>();
builder.Services.AddHostedService<StatementWorker>();
var app = builder.Build();
app.MapInvoicePdfs(); // add .RequireAuthorization() once your auth is wired up
app.Run();
public partial class Program; // lets WebApplicationFactory find the entry point in tests
Step 6: render invoices from a Razor component
Since .NET 8, HtmlRenderer (in Microsoft.AspNetCore.Components.Web, part of the shared framework) renders any Razor component to a string outside of an HTTP request. That makes a .razor file a good PDF template: typed parameters, IntelliSense, @foreach, and every value HTML-encoded by default, so a customer named <script> prints as text. The component can be a whole document, <!DOCTYPE html> included. In a Razor file, CSS at-rules need a doubled @@:
@* Invoices/InvoiceDocument.razor: a whole HTML document, rendered to a string on the server *@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Invoice @Invoice.Number</title>
<style>
@@page { size: Letter; margin: 0.6in 0.6in 0.8in; }
body { font: 11pt/1.45 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; color: #1f2937; }
h1 { font-size: 20pt; margin: 0 0 4pt; }
.meta { color: #6b7280; margin-bottom: 18pt; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 6pt 4pt; border-bottom: 1px solid #e5e7eb; text-align: left; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
thead { display: table-header-group; } /* repeat the header on every page */
tr { break-inside: avoid; }
tfoot td { font-weight: 600; border-bottom: 0; }
</style>
</head>
<body>
<h1>Invoice @Invoice.Number</h1>
<div class="meta">
Billed to @Invoice.CustomerName ·
Issued @Invoice.IssuedOn.ToString("MMM d, yyyy", Culture) ·
Due @Invoice.DueOn.ToString("MMM d, yyyy", Culture)
</div>
<table>
<thead>
<tr><th>Description</th><th class="num">Qty</th><th class="num">Unit price</th><th class="num">Amount</th></tr>
</thead>
<tbody>
@foreach (var line in Invoice.Lines)
{
<tr>
<td>@line.Description</td>
<td class="num">@line.Quantity.ToString("N0", Culture)</td>
<td class="num">@line.UnitPrice.ToString("C3", Culture)</td>
<td class="num">@line.Total.ToString("C2", Culture)</td>
</tr>
}
</tbody>
<tfoot>
<tr><td colspan="3" class="num">Total</td><td class="num">@Invoice.Total.ToString("C2", Culture)</td></tr>
</tfoot>
</table>
</body>
</html>
@code {
private static readonly System.Globalization.CultureInfo Culture = new("en-US");
[Parameter, EditorRequired]
public Invoice Invoice { get; set; } = default!;
}
Headless Chrome renders flexbox, grid and web fonts the way your browser does. A few print rules help long documents: @page sets the paper size, display: table-header-group repeats the table header on every page, and break-inside: avoid keeps a row from splitting across pages. The models and an _Imports.razor for the component:
// Billing/Invoices/Invoice.cs
namespace Billing.Invoices;
public sealed record LineItem(string Description, int Quantity, decimal UnitPrice)
{
public decimal Total => Quantity * UnitPrice;
}
public sealed record Invoice(
int Id,
string Number,
int CustomerId,
string CustomerName,
DateOnly IssuedOn,
DateOnly DueOn,
IReadOnlyList<LineItem> Lines)
{
public decimal Total => Lines.Sum(l => l.Total);
}
public interface IInvoiceStore
{
Task<Invoice?> FindAsync(int id, CancellationToken ct);
Task<IReadOnlyList<Invoice>> ForCustomerAsync(int customerId, int year, CancellationToken ct);
Task<string> StatementPasswordAsync(int customerId, CancellationToken ct); // agreed with the customer
}
@using Microsoft.AspNetCore.Components
@using Billing.Invoices
The renderer is a small service. RenderComponentAsync has to run on the renderer's dispatcher, and the renderer is disposed after each document:
// Billing/Invoices/InvoiceRenderer.cs
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
namespace Billing.Invoices;
// Renders Razor components to HTML strings outside of any HTTP request,
// so the same code works in endpoints and background workers.
public sealed class InvoiceRenderer(IServiceProvider services, ILoggerFactory loggerFactory)
{
public async Task<string> RenderAsync(Invoice invoice)
{
await using var renderer = new HtmlRenderer(services, loggerFactory);
return await renderer.Dispatcher.InvokeAsync(async () =>
{
var parameters = ParameterView.FromDictionary(new Dictionary<string, object?>
{
[nameof(InvoiceDocument.Invoice)] = invoice
});
var output = await renderer.RenderComponentAsync<InvoiceDocument>(parameters);
return output.ToHtmlString(); // values are HTML-encoded, like any Razor output
});
}
}
The page setup lives in one place so every caller (download, background job, S3 export) produces the same document. preferCSSPageSize tells Chrome to use the @page size from the template. Chrome renders footerTemplate in its own context, so it needs inline styles and an explicit font-size, and it fills pageNumber and totalPages for you:
// Billing/Invoices/InvoicePdf.cs
using Billing.Api2Pdf;
namespace Billing.Invoices;
public static class InvoicePdf
{
// One place for the page setup every invoice shares. The page size comes
// from @page in the template; the footer prints page numbers.
public static HtmlToPdfRequest For(Invoice invoice, string html) => new(html)
{
FileName = $"invoice-{invoice.Number}.pdf",
Options = new ChromePdfOptions
{
PreferCssPageSize = true,
PrintBackground = true,
DisplayHeaderFooter = true,
HeaderTemplate = "<span></span>",
FooterTemplate = """
<div style="font-size:8pt;color:#6b7280;width:100%;text-align:center">
Page <span class="pageNumber"></span> of <span class="totalPages"></span>
</div>
"""
}
};
}
Step 7: stream the PDF from a Minimal API endpoint
The endpoint loads the invoice, renders the component, calls Api2Pdf with outputBinary=true and returns the stream. Results.Stream sets Content-Type and Content-Disposition, copies the PDF to the response as it arrives and disposes the stream afterwards. The bound CancellationToken is HttpContext.RequestAborted, so a user who closes the tab cancels the Api2Pdf call too. The second route queues the background job from the next step and returns 202 Accepted right away:
// Billing/Invoices/InvoiceEndpoints.cs
using Billing.Api2Pdf;
namespace Billing.Invoices;
public static class InvoiceEndpoints
{
public static IEndpointRouteBuilder MapInvoicePdfs(this IEndpointRouteBuilder app)
{
// GET /invoices/1/pdf streams the PDF straight from Api2Pdf to the browser.
app.MapGet("/invoices/{id:int}/pdf", async (
int id, IInvoiceStore store, InvoiceRenderer renderer, Api2PdfClient pdf, CancellationToken ct) =>
{
var invoice = await store.FindAsync(id, ct);
if (invoice is null) return Results.NotFound();
var html = await renderer.RenderAsync(invoice);
var stream = await pdf.HtmlToPdfStreamAsync(InvoicePdf.For(invoice, html), ct);
return Results.Stream(stream, "application/pdf", $"invoice-{invoice.Number}.pdf");
});
// POST /customers/42/statements/2026 queues a year-end packet and returns at once.
app.MapPost("/customers/{customerId:int}/statements/{year:int}", async (
int customerId, int year, StatementQueue queue, CancellationToken ct) =>
{
await queue.EnqueueAsync(new StatementJob(customerId, year), ct);
return Results.Accepted();
});
return app;
}
}
dotnet run
# in a second terminal, with the port dotnet run printed:
curl -o INV-2026-0001.pdf http://localhost:5000/invoices/1/pdf
Put these routes behind your authorization (.RequireAuthorization() on the group) and check that the signed-in user owns the invoice before rendering it. Controllers work the same way: return File(stream, "application/pdf", fileName); from an MVC action streams just like Results.Stream.
Step 8: write PDFs straight into S3 with useCustomStorage
When the PDF belongs in your own storage (an archive, a customer portal, a data lake), downloading it from Api2Pdf only to upload it again wastes bandwidth and memory. Presign a PUT for the exact object key instead and pass it in the request. Api2Pdf renders the PDF and uploads it to that URL itself. Nothing else in your AWS account is exposed: the URL can write one object, with one content type, for 15 minutes.
// Billing/Invoices/S3PdfStorage.cs
using Amazon.S3;
using Amazon.S3.Model;
using Billing.Api2Pdf;
namespace Billing.Invoices;
// Hands Api2Pdf a presigned PUT URL so the finished PDF goes straight into
// your bucket and never passes through your server.
public sealed class S3PdfStorage(IAmazonS3 s3, IConfiguration config)
{
private readonly string _bucket = config["Storage:Bucket"]
?? throw new InvalidOperationException("Set Storage:Bucket");
public async Task<Api2PdfStorage> PresignPutAsync(string key)
{
var url = await s3.GetPreSignedURLAsync(new GetPreSignedUrlRequest
{
BucketName = _bucket,
Key = key,
Verb = HttpVerb.PUT,
ContentType = "application/pdf",
Expires = DateTime.UtcNow.AddMinutes(15) // must outlive the render
});
// Content-Type is part of the signature, so the upload must send it.
return new Api2PdfStorage("PUT", url, new Dictionary<string, string> { ["Content-Type"] = "application/pdf" });
}
public async Task<long> SizeAsync(string key, CancellationToken ct)
{
var head = await s3.GetObjectMetadataAsync(_bucket, key, ct);
return head.ContentLength;
}
}
- Send every signed header. Because the presign request sets
ContentType, the upload must sendContent-Type: application/pdfor S3 answers403 SignatureDoesNotMatch. Passing it instorage.extraHTTPHeadersalso makes S3 store the object asapplication/pdfrather thanbinary/octet-stream. - Make the expiry outlive the render. The URL has to be valid when Api2Pdf finishes, not just when you send the request. Presign right before the call.
- Verify, then trust.
GetObjectMetadataAsyncconfirms the object exists and returns its size, which is the number worth recording in your database.
useCustomStorage and storage work the same way on the other conversion endpoints, including merge, password, LibreOffice and /zip (see batch PDF generation: zip PDFs and upload to S3). On Azure, pass a Blob SAS URL with write permission and the x-ms-blob-type: BlockBlob header in extraHTTPHeaders; on Google Cloud, a V4 signed URL for PUT.
Step 9: a background job that merges, password-protects and stores a packet
Year-end statements are many small documents that should end up as one protected file, and nobody should wait on an HTTP request while they render. A bounded Channel plus a BackgroundService is the simplest in-process queue. The worker renders the invoices four at a time with Parallel.ForEachAsync (each result goes into its own array slot, so the merge order matches the invoice order without a lock), merges the hosted files with POST /pdfsharp/merge, then calls POST /pdfsharp/password with useCustomStorage so the protected packet lands in S3 in the same request. Finally it deletes the intermediate files with DELETE /file/{responseId} instead of leaving invoice data hosted for 24 hours:
// Billing/Invoices/StatementWorker.cs
using System.Threading.Channels;
using Billing.Api2Pdf;
namespace Billing.Invoices;
public sealed record StatementJob(int CustomerId, int Year);
public sealed class StatementQueue
{
private readonly Channel<StatementJob> _channel = Channel.CreateBounded<StatementJob>(100);
public ValueTask EnqueueAsync(StatementJob job, CancellationToken ct) => _channel.Writer.WriteAsync(job, ct);
public IAsyncEnumerable<StatementJob> ReadAllAsync(CancellationToken ct) => _channel.Reader.ReadAllAsync(ct);
}
// Renders every invoice of the year, merges them into one PDF, password-protects
// it and has Api2Pdf write the result straight into S3.
public sealed class StatementWorker(
StatementQueue queue,
IServiceScopeFactory scopes,
ILogger<StatementWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var job in queue.ReadAllAsync(stoppingToken))
{
try
{
await using var scope = scopes.CreateAsyncScope();
await RunAsync(scope.ServiceProvider, job, stoppingToken);
}
catch (Api2PdfException ex)
{
logger.LogError(ex, "Statement for customer {CustomerId} failed, Api2Pdf response {ResponseId}",
job.CustomerId, ex.ResponseId);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Statement for customer {CustomerId} failed", job.CustomerId);
}
}
}
private async Task RunAsync(IServiceProvider sp, StatementJob job, CancellationToken ct)
{
var store = sp.GetRequiredService<IInvoiceStore>();
var renderer = sp.GetRequiredService<InvoiceRenderer>();
var pdf = sp.GetRequiredService<Api2PdfClient>();
var storage = sp.GetRequiredService<S3PdfStorage>();
var invoices = await store.ForCustomerAsync(job.CustomerId, job.Year, ct);
if (invoices.Count == 0) return;
// 1. Render each invoice, four at a time. Results keep invoice order.
var parts = new Api2PdfResult[invoices.Count];
await Parallel.ForEachAsync(Enumerable.Range(0, invoices.Count),
new ParallelOptions { MaxDegreeOfParallelism = 4, CancellationToken = ct },
async (i, token) =>
{
var html = await renderer.RenderAsync(invoices[i]);
parts[i] = await pdf.HtmlToPdfAsync(InvoicePdf.For(invoices[i], html), token);
});
// 2. Merge the hosted files in order.
var merged = await pdf.MergeAsync(new MergeRequest(parts.Select(p => p.FileUrl!).ToList()), ct);
// 3. Password-protect the packet and upload it to S3 in the same call.
var key = $"statements/{job.CustomerId}/{job.Year}.pdf";
var password = await store.StatementPasswordAsync(job.CustomerId, ct); // never log it
var final = await pdf.PasswordAsync(new PasswordRequest(merged.FileUrl!, password)
{
FileName = $"statement-{job.Year}.pdf",
UseCustomStorage = true,
Storage = await storage.PresignPutAsync(key)
}, ct);
// 4. The intermediate files are invoice data; don't leave them hosted for 24 hours.
foreach (var id in parts.Select(p => p.ResponseId).Append(merged.ResponseId).OfType<string>())
{
await pdf.DeleteAsync(id, ct);
}
logger.LogInformation("Statement {Key} written ({Bytes} bytes), cost {Cost:F5}, response {ResponseId}",
key, await storage.SizeAsync(key, ct), parts.Sum(p => p.Cost) + merged.Cost + final.Cost, final.ResponseId);
}
}
Hosted services are singletons, so the worker creates a scope per job to resolve the scoped renderer and the typed client. Api2Pdf has no rate limits; the parallelism limit keeps your own memory and outbound connections predictable. The in-memory channel loses queued jobs when the process restarts, so once jobs matter, move them to a durable queue (Hangfire, Azure Service Bus, Amazon SQS) and keep the same RunAsync body. The password is userpassword, needed to open the file; add OwnerPassword if you also want to restrict editing and printing permissions.
For DRAFT or CONFIDENTIAL stamps on the same pipeline, add one call to POST /pdfsharp/watermark between the merge and the password step, as shown in the Laravel guide.
Step 10: test without the network
Because the client is a typed HttpClient, every test can swap the primary handler for a stub and keep the real registration, options binding and resilience pipeline. A small handler records each request and returns a canned response:
// Billing.Tests/StubHandler.cs
using System.Net;
using System.Text;
namespace Billing.Tests;
// Records every request and answers with a canned response.
public sealed class StubHandler(Func<HttpRequestMessage, string, HttpResponseMessage> respond) : HttpMessageHandler
{
public List<(HttpRequestMessage Request, string Body)> Calls { get; } = [];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
var body = request.Content is null ? "" : await request.Content.ReadAsStringAsync(ct);
Calls.Add((request, body));
return respond(request, body);
}
public static HttpResponseMessage Json(string json, HttpStatusCode status = HttpStatusCode.OK) =>
new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
public static HttpResponseMessage Pdf() =>
new(HttpStatusCode.OK) { Content = new ByteArrayContent("%PDF-1.7 fake"u8.ToArray()) };
}
The client tests check the raw Authorization header (trimmed), the camelCase JSON body, that null options are omitted, the lower-case password fields, that a 401 becomes an Api2PdfException and is not retried, and that the stream rejects a body that is not a PDF:
// Billing.Tests/Api2PdfClientTests.cs
using System.Net;
using System.Text.Json;
using Billing.Api2Pdf;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Billing.Tests;
public class Api2PdfClientTests
{
// Builds the real registration (options, typed client, resilience) on top of a stub.
private static Api2PdfClient CreateClient(StubHandler stub)
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { ["Api2Pdf:ApiKey"] = "test-key " })
.Build();
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(config)
.AddLogging();
services.AddApi2Pdf().ConfigurePrimaryHttpMessageHandler(() => stub);
return services.BuildServiceProvider().GetRequiredService<Api2PdfClient>();
}
[Fact]
public async Task Sends_raw_key_and_camelCase_body()
{
var stub = new StubHandler((_, _) => StubHandler.Json(
"""{"Success":true,"FileUrl":"https://storage.example/a.pdf","ResponseId":"r1","Cost":0.0001}"""));
var result = await CreateClient(stub).HtmlToPdfAsync(new HtmlToPdfRequest("<h1>Hi</h1>")
{
FileName = "a.pdf",
Options = new ChromePdfOptions { Landscape = true, PreferCssPageSize = true }
});
Assert.Equal("r1", result.ResponseId);
var (request, body) = Assert.Single(stub.Calls);
Assert.Equal("https://v2.api2pdf.com/chrome/pdf/html", request.RequestUri!.ToString());
Assert.Equal("test-key", request.Headers.GetValues("Authorization").Single());
using var json = JsonDocument.Parse(body);
Assert.Equal("<h1>Hi</h1>", json.RootElement.GetProperty("html").GetString());
Assert.False(json.RootElement.GetProperty("inline").GetBoolean());
Assert.True(json.RootElement.GetProperty("options").GetProperty("preferCSSPageSize").GetBoolean());
Assert.False(json.RootElement.TryGetProperty("useCustomStorage", out _));
Assert.False(json.RootElement.GetProperty("options").TryGetProperty("scale", out _));
}
[Fact]
public async Task Password_uses_lower_case_field_names()
{
var stub = new StubHandler((_, _) => StubHandler.Json("""{"Success":true,"FileUrl":"u","ResponseId":"r2"}"""));
await CreateClient(stub).PasswordAsync(new PasswordRequest("https://storage.example/m.pdf", "s3cret") { OwnerPassword = "owner" });
using var json = JsonDocument.Parse(stub.Calls.Single().Body);
Assert.Equal("s3cret", json.RootElement.GetProperty("userpassword").GetString());
Assert.Equal("owner", json.RootElement.GetProperty("ownerpassword").GetString());
}
[Fact]
public async Task Api_errors_become_typed_exceptions()
{
var stub = new StubHandler((_, _) => StubHandler.Json(
"""{"Success":false,"Error":"Invalid API key","ResponseId":"r3"}""", HttpStatusCode.Unauthorized));
var ex = await Assert.ThrowsAsync<Api2PdfException>(() =>
CreateClient(stub).HtmlToPdfAsync(new HtmlToPdfRequest("<p>x</p>")));
Assert.Equal(HttpStatusCode.Unauthorized, ex.StatusCode);
Assert.Equal("r3", ex.ResponseId);
Assert.Single(stub.Calls); // 401 is not retried
}
[Fact]
public async Task Stream_returns_the_pdf_bytes()
{
var stub = new StubHandler((_, _) => StubHandler.Pdf());
await using var stream = await CreateClient(stub).HtmlToPdfStreamAsync(new HtmlToPdfRequest("<p>x</p>"));
using var reader = new StreamReader(stream);
Assert.Equal("%PDF-1.7 fake", await reader.ReadToEndAsync());
Assert.EndsWith("?outputBinary=true", stub.Calls.Single().Request.RequestUri!.ToString());
}
[Fact]
public async Task Stream_rejects_a_body_that_is_not_a_pdf()
{
var stub = new StubHandler((_, _) => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("<html>proxy login</html>")
});
var ex = await Assert.ThrowsAsync<Api2PdfException>(() =>
CreateClient(stub).HtmlToPdfStreamAsync(new HtmlToPdfRequest("<p>x</p>")));
Assert.Contains("not a PDF", ex.Message);
}
}
The endpoint test boots the real app with WebApplicationFactory (add Microsoft.AspNetCore.Mvc.Testing to the test project), renders the real Razor component and replaces only the outbound HTTP handler with ConfigureTestServices:
// Billing.Tests/InvoicePdfEndpointTests.cs
using Billing.Api2Pdf;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
namespace Billing.Tests;
public class InvoicePdfEndpointTests
{
[Fact]
public async Task Streams_the_rendered_invoice_as_a_pdf()
{
var stub = new StubHandler((_, _) => StubHandler.Pdf());
await using var factory = new WebApplicationFactory<Program>().WithWebHostBuilder(web =>
{
web.UseSetting("Api2Pdf:ApiKey", "test-key");
web.ConfigureTestServices(services =>
services.AddHttpClient<Api2PdfClient>().ConfigurePrimaryHttpMessageHandler(() => stub));
});
var response = await factory.CreateClient().GetAsync("/invoices/1/pdf");
response.EnsureSuccessStatusCode();
Assert.Equal("application/pdf", response.Content.Headers.ContentType!.MediaType);
Assert.Equal("invoice-INV-2026-0001.pdf", response.Content.Headers.ContentDisposition!.FileNameStar);
Assert.StartsWith("%PDF", await response.Content.ReadAsStringAsync());
var html = System.Text.Json.JsonDocument.Parse(stub.Calls.Single().Body).RootElement.GetProperty("html").GetString()!;
Assert.StartsWith("<!DOCTYPE html>", html.TrimStart());
Assert.Contains("Invoice INV-2026-0001", html);
Assert.Contains("$51.40", html); // 49.00 + 1,200 x 0.002
}
[Fact]
public async Task Unknown_invoice_is_404_and_never_calls_api2pdf()
{
var stub = new StubHandler((_, _) => StubHandler.Pdf());
await using var factory = new WebApplicationFactory<Program>().WithWebHostBuilder(web =>
{
web.UseSetting("Api2Pdf:ApiKey", "test-key");
web.ConfigureTestServices(services =>
services.AddHttpClient<Api2PdfClient>().ConfigurePrimaryHttpMessageHandler(() => stub));
});
var response = await factory.CreateClient().GetAsync("/invoices/999/pdf");
Assert.Equal(System.Net.HttpStatusCode.NotFound, response.StatusCode);
Assert.Empty(stub.Calls);
}
}
dotnet test
Passed! - Failed: 0, Passed: 7, Skipped: 0, Total: 7, Duration: 343 ms - Billing.Tests.dll (net10.0)
Production notes
- Keep the key server-side. Never call Api2Pdf from Blazor WebAssembly or browser JavaScript; the key in the
Authorizationheader would be visible to every visitor. Go through an endpoint that authorizes the user first. - Let the factory own the HttpClient. Inject
Api2PdfClientwherever you need it and nevernew HttpClient()per request. The factory pools handlers and rotates them, which avoids both socket exhaustion and stale DNS. - Pick the right path for each document. Stream small documents from the endpoint; move big, bulk or chained work to a background worker or queue, and use
useCustomStoragewhen the result belongs in your bucket anyway. - Use V2 XL for large documents. Standard requests get 2 GB of memory and 90 seconds. Long reports with hundreds of pages or heavy charts can use a second typed or named client with
BaseUrlset tohttps://v2-xl.api2pdf.com(4 CPU, 8 GB, 5 minute limit, priced at 10x the standard rate) and an attempt timeout of about 6 minutes. Use it only for those jobs. - Mind the 24 hour
FileUrl. Hosted files are deleted after 24 hours. Copy what you need to keep, delete sensitive files early withDeleteAsync, or skip the hosted copy entirely withuseCustomStorage. - Log the
ResponseId, not the HTML. The id appears in the request logs in the portal, and support can trace a request with it. Use structured logging placeholders, as in the worker, so it is searchable. - Observe it like any other dependency. Calls through
IHttpClientFactoryemit the standardSystem.Net.Httpmetrics and traces, so OpenTelemetry picks up Api2Pdf latency and errors with no extra code, and the resilience pipeline adds retry and circuit-breaker events. - Cost is per use. Billing is based on compute seconds and bandwidth, and each JSON response reports
Seconds,MbOutandCost, so you can record per-feature cost from the JSON calls. A one-page invoice usually costs a fraction of a cent.
Troubleshooting
- 401 Invalid API key. The header must be the key on its own. Remove any
Bearerprefix (do not useAuthenticationHeaderValue, which requires a scheme), make sure the value has no trailing newline, and confirm the deployed environment setsApi2Pdf__ApiKey. OptionsValidationExceptionat startup.ValidateOnStartdid its job: theApi2Pdfsection is missing or has no key in this environment.TimeoutRejectedExceptionor aTaskCanceledExceptionafter 10 or 30 seconds. The standard resilience defaults are still in effect. Configure the attempt and total timeouts as in Step 5, and setHttpClient.Timeoutto infinite.not a PDFfromHtmlToPdfStreamAsync. A proxy or captive portal returned HTML instead of the API response. The exception includes the first bytes of the body; check the outbound proxy settings andHTTPS_PROXY.- Styles or images missing. The CSS or image is on a host Api2Pdf cannot reach, such as
localhost, a private network or a route behind your login. Inline the CSS in the component and use public absolute URLs ordata:URIs for images;~/paths andasp-append-versiondo not resolve outside a request. - Charts or JavaScript-rendered content is blank.
HtmlRendererproduces static HTML, so Blazor interactivity never runs, and client-side chart libraries may not have finished when Chrome prints. SetDelay(milliseconds) or wait for a condition withPuppeteerWaitForMethodandPuppeteerWaitForValue, as described in the Headless Chrome options. Better still, render charts as SVG on the server. - Razor build error on
@pageor@media. Inside a.razorfile those are Razor directives. Write@@pageand@@mediain the<style>block. - Tiny header or footer text, or none at all. Set
DisplayHeaderFooter, give the template an explicitfont-size, and leave enough bottom margin for it to fit. SignatureDoesNotMatchon S3 uploads. A signed header was not sent, or was sent with a different value. KeepextraHTTPHeadersin sync with what you presigned, and make sure the presigned URL has not expired.
Wrap-up
You now have an ASP.NET Core PDF pipeline with no native dependencies: Razor components as typed, HTML-encoded templates, a typed HttpClient with resilience settings that fit PDF rendering, a Minimal API endpoint that streams PDFs without buffering them, a background job that ends in one merged, password-protected file written straight to S3, and tests that never touch the network. The same client covers the rest of the API with one more method each: Markdown to PDF, screenshots, Office conversion through LibreOffice, and file to Markdown extraction. Create a free account to get an API key, or browse the full request reference in the interactive API docs.



