# HTML to PDF in C# and .NET: an invoice from ASP.NET Core

> Convert HTML to PDF in C#. Render an invoice with HttpClient or a Razor component, stream it from ASP.NET Core, and see how PuppeteerSharp, iText, HtmlRenderer and DinkToPdf compare.

> Part of the Dynamic Document API documentation. Index of all pages for agents: [llms.txt](https://dynamicdocumentapi.com/llms.txt), every page in one file: [llms-full.txt](https://dynamicdocumentapi.com/llms-full.txt).















This tutorial turns an HTML invoice template and a JSON file into a two-page PDF in C# and .NET 10. The invoice has the parts that usually break when HTML becomes a PDF: a Flexbox header with an SVG logo, a web font, a line-item table that runs onto a second page and repeats its header row, totals that stay together, and "Page 1 of 2" in the footer.





Before the code, a test: the same invoice through four open-source libraries that .NET developers usually reach for, so you can see which one fits your project. Then the steps:

1. the template and the invoice data,
2. rendering it with `HttpClient`,
3. paper size, margins and page numbers,
4. the same invoice from a Razor component,
5. an ASP.NET Core endpoint that streams the PDF to the browser,
6. what to change for production.

**Prefer to watch?** This 13-minute video walks through the same steps: the library comparison, the template, plain `HttpClient`, a Razor component, the ASP.NET Core endpoint and the errors to plan for.

[Video: HTML to PDF in C# and .NET: an invoice from a template or Razor (HttpClient, ASP.NET Core)](https://www.youtube.com/watch?v=8_b-LeAgv-c)

You need the .NET 10 SDK and an API key from the dashboard at [https://app.dynamicdocumentapi.com](https://app.dynamicdocumentapi.com/signup) (free plan, no card needed). A test key (`dda_test_…`) is free and adds a TEST watermark. There is no C# SDK yet, so the code uses plain `HttpClient`; only the ASP.NET Core endpoint adds a NuGet package, Microsoft's resilience handler. The complete example is on [GitHub](https://github.com/DynamicDocumentApi/html-to-pdf-csharp): the template, 36 sample line items, the Razor component, every program from this page and the comparison.

## C# HTML to PDF libraries, tested [#c-html-to-pdf-libraries-tested]

We rendered the same invoice with PuppeteerSharp, iText pdfHTML, HtmlRenderer.PdfSharp and DinkToPdf, each with page numbers added the way its documentation describes. Every library got the same finished HTML, rendered from the [Razor component](#already-using-razor-render-a-component-to-html) further down. The test runs in GitHub Actions on Ubuntu 24.04 with .NET 10, like a typical Linux server; the code and all results are in the [`compare` folder](https://github.com/DynamicDocumentApi/html-to-pdf-csharp/tree/main/compare) of the repository.

Page 1 of each result, in this order: PuppeteerSharp, iText pdfHTML, HtmlRenderer.PdfSharp, DinkToPdf with wkhtmltopdf.









|                       | PuppeteerSharp 25.18                     | iText pdfHTML 6.3.4      | HtmlRenderer.PdfSharp 1.6.1        | DinkToPdf 1.0.8 + wkhtmltopdf 0.12.6.1               | Dynamic Document API  |
| --------------------- | ---------------------------------------- | ------------------------ | ---------------------------------- | ---------------------------------------------------- | --------------------- |
| Rendering engine      | Chrome                                   | Own layout engine        | Own layout engine on PDFsharp      | Qt WebKit                                            | Chromium              |
| What you install      | NuGet + about 720 MB of Chrome downloads | NuGet only               | NuGet only                         | NuGet + wkhtmltopdf's native library (archived 2023) | Nothing, `HttpClient` |
| License               | MIT                                      | AGPL-3.0 or commercial   | BSD-3-Clause                       | MIT, wkhtmltopdf LGPL-3.0                            | Free plan, paid plans |
| Latest release        | November 2026                            | September 2026           | July 2026                          | April 2017                                           | –                     |
| Inline SVG logo       | Yes                                      | Yes                      | Missing                            | Yes                                                  | Yes                   |
| Web font (Inter)      | Yes                                      | Yes                      | No, fallback font                  | Yes                                                  | Yes                   |
| Layout as designed    | Yes                                      | Nearly: grid ignored     | No: Flexbox and grid boxes missing | No: Flexbox and grid ignored                         | Yes                   |
| Table header repeated | Yes                                      | Yes                      | No header row                      | Yes                                                  | Yes                   |
| Page numbers via      | `FooterTemplate`                         | CSS `@page` margin boxes | Drawn with PDFsharp afterwards     | `FooterSettings`                                     | `pdf.footer`          |
| Runs JavaScript       | Yes                                      | No                       | No                                 | Yes (old WebKit)                                     | Yes                   |
| Pages                 | 2                                        | 2                        | 2                                  | 2                                                    | 2                     |

How to choose:

* **PuppeteerSharp** prints with a real Chrome, so the PDF looks like the page in Chrome. You run the browser yourself: about 720 MB of downloads on first use, memory per page, timeouts and updates. On Ubuntu 23.10 and later, Chrome also refuses to start until its sandbox is allowed, see the [FAQ](#does-puppeteersharp-work-on-a-linux-server).
* **iText pdfHTML** is the strongest of the libraries without a browser in this test: Flexbox, the web font, the repeated table header and CSS `@page` margin boxes all worked, only CSS grid didn't. It doesn't run JavaScript, and it is licensed under the AGPL-3.0 or commercially, so check which one your project needs.
* **HtmlRenderer.PdfSharp** is small, fast and permissively licensed, but it only supports older CSS. Boxes with `display: flex` or `display: grid` aren't drawn at all: our invoice lost its header, addresses and totals without an error. It fits simple documents built from tables and blocks.
* **DinkToPdf** wraps wkhtmltopdf, which is no longer maintained; DinkToPdf itself was last released in 2017. Its old WebKit ignores Flexbox and grid, and you deploy a native library for every platform. Don't start new projects on it; see [wkhtmltopdf alternatives](https://dynamicdocumentapi.com/alternatives/wkhtmltopdf/).
* **An API** such as Dynamic Document API gives you the Chromium result without running a browser, and adds a template language, page numbers from your data, safe retries and [e-invoices](https://dynamicdocumentapi.com/docs/e-invoicing). The HTML and data leave your server, and live renders count against a plan.

The rest of this tutorial uses the API. To follow along, [create a free account](https://app.dynamicdocumentapi.com/signup) and a test key; no card needed.

## How it works [#how-it-works]

Your code doesn't build the HTML. It sends the template and the data in one request, and Dynamic Document API fills the template, renders it in Chromium and returns the PDF:

1. `Invoice.Load()` reads `invoice.json` and calculates the line amounts and totals with `decimal`.
2. `RenderInvoice` sends `invoice.html` as `html`, the invoice as `data` and the page settings as `pdf` to `POST /v1/pdf/from-html`.
3. The PDF comes back in the response body, and the program writes it to `invoice.pdf`.

The template language uses Jinja syntax: where Razor has `@foreach` and `@if`, the template has `{% for %}` and `{% if %}`. Values from your data are escaped on the server, so a customer named `<b>Acme</b>` can't break the layout. If you'd rather keep your templates in Razor, see [the Razor section](#already-using-razor-render-a-component-to-html): .NET renders the HTML and the API only prints it.

## 1. The template and the data [#1-the-template-and-the-data]

`invoice/invoice.html` is ordinary HTML and CSS with placeholders. The CSS is in the [repository](https://github.com/DynamicDocumentApi/html-to-pdf-csharp/blob/main/invoice/invoice.html); this is the body, where the data goes in:

```html
<!-- invoice/invoice.html (body) -->
<body>
  <div class="top">
    <div class="brand">
      <svg viewBox="0 0 48 48" aria-hidden="true">
        <rect width="48" height="48" rx="10" fill="#2f6b4f"/>
        <path d="M8 36 L19 18 L26 28 L31 21 L40 36 Z" fill="#fff"/>
        <circle cx="34" cy="13" r="4" fill="#f2c14e"/>
      </svg>
      <div>
        <b>{{ seller.name }}</b>
        <span class="muted">{{ seller.address | join(", ") }}</span>
      </div>
    </div>
    <div class="meta">
      <h1>INVOICE</h1>
      <dl>
        <dt>Invoice number</dt><dd>{{ number }}</dd>
        <dt>Issued</dt><dd>{{ issued }}</dd>
        <dt>Due</dt><dd>{{ due }}</dd>
        {% if po_number %}<dt>PO number</dt><dd>{{ po_number }}</dd>{% endif %}
      </dl>
    </div>
  </div>

  <div class="parties">
    <div>
      <h2>Bill to</h2>
      <b>{{ customer.name }}</b><br>
      Attn: {{ customer.contact }}<br>
      {% for line in customer.address %}{{ line }}<br>{% endfor %}
    </div>
    <div>
      <h2>From</h2>
      <b>{{ seller.name }}</b><br>
      {% for line in seller.address %}{{ line }}<br>{% endfor %}
      {{ seller.email }}
    </div>
  </div>

  <table>
    <thead>
      <tr><th>#</th><th>SKU</th><th>Item</th><th class="num">Qty</th><th class="num">Unit price</th><th class="num">Amount</th></tr>
    </thead>
    <tbody>
      {% for item in items %}
      <tr>
        <td class="muted">{{ loop.index }}</td>
        <td class="sku">{{ item.sku }}</td>
        <td>{{ item.description }}{% if item.backorder %}<span class="badge">Backorder</span>{% endif %}</td>
        <td class="num">{{ item.qty }}</td>
        <td class="num">${{ "{:,.2f}".format(item.unit_price) }}</td>
        <td class="num">${{ "{:,.2f}".format(item.amount) }}</td>
      </tr>
      {% endfor %}
    </tbody>
  </table>

  <div class="end">
    <p class="notes muted">{{ notes }}</p>
    <table class="totals">
      <tr><td>Subtotal</td><td class="num">${{ "{:,.2f}".format(totals.subtotal) }}</td></tr>
      <tr><td>Sales tax ({{ totals.tax_percent }}%)</td><td class="num">${{ "{:,.2f}".format(totals.tax) }}</td></tr>
      <tr><td>Shipping</td><td class="num">${{ "{:,.2f}".format(totals.shipping) }}</td></tr>
      <tr class="due"><td>Amount due</td><td class="num">${{ "{:,.2f}".format(totals.total) }}</td></tr>
    </table>
  </div>
</body>
```

The rules that control the pages:

| Rule                                     | Effect                                                               |
| ---------------------------------------- | -------------------------------------------------------------------- |
| `thead { display: table-header-group; }` | The header row repeats at the top of every page the table runs onto  |
| `tr { break-inside: avoid; }`            | A line item is never cut in half at a page break                     |
| `.end { break-inside: avoid; }`          | Notes and totals move to the next page together instead of splitting |

More rules, and fixes for problems such as an empty last page: [pagination basics](https://dynamicdocumentapi.com/docs/pagination). `"{:,.2f}".format()` prints money as 45,172.62; the [`format_currency`](https://dynamicdocumentapi.com/docs/template-language#format_currency) filter formats any currency and locale.

### The data [#the-data]

`invoice/invoice.json` holds the invoice as it would come from your database: seller, customer, dates, the tax rate and 36 line items with quantity and unit price. `Invoice.Load()` reads it into records and calculates the money with `decimal`, rounded to cents, so the PDF shows exactly the amounts your books have. `JsonOptions` writes the properties in snake\_case (`unit_price`, `po_number`), the names the template uses:

```csharp
// src/Invoices/Invoice.cs (excerpt)
public sealed record Invoice(
    string Number,
    string Issued,
    string Due,
    string? PoNumber,
    Party Seller,
    Customer Customer,
    string Notes,
    IReadOnlyList<LineItem> Items,
    Totals Totals)
{
    /// <summary>snake_case keys (unit_price, po_number), the names invoice.html uses.</summary>
    public static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
    {
        PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    };

    public static string TemplatePath => Path.Combine(AppContext.BaseDirectory, "invoice", "invoice.html");

    public static Invoice Load(string? path = null)
    {
        path ??= Path.Combine(AppContext.BaseDirectory, "invoice", "invoice.json");
        var source = JsonSerializer.Deserialize<InvoiceSource>(File.ReadAllText(path), JsonOptions)
            ?? throw new InvalidDataException($"{path} is empty");

        var items = source.Items
            .Select(item => new LineItem(
                item.Sku,
                item.Description,
                item.Qty,
                Cents(item.UnitPrice),
                Cents(item.UnitPrice * item.Qty),
                item.Backorder))
            .ToList();

        var subtotal = items.Sum(item => item.Amount);
        var tax = Cents(subtotal * source.TaxRate);
        var taxPercent = decimal.Parse((source.TaxRate * 100).ToString("G29", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // 8.25, not 8.2500
        var totals = new Totals(subtotal, taxPercent, tax, source.Shipping, subtotal + tax + source.Shipping);

        return new Invoice(
            source.Number,
            LongDate(source.Issued),
            LongDate(source.Due),
            source.PoNumber,
            source.Seller,
            source.Customer,
            source.Notes,
            items,
            totals);
    }

    static decimal Cents(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero);

    // "2026-11-02" -> "November 2, 2026"
    static string LongDate(string iso) =>
        DateOnly.ParseExact(iso, "yyyy-MM-dd", CultureInfo.InvariantCulture)
            .ToString("MMMM d, yyyy", CultureInfo.GetCultureInfo("en-US"));
    // … InvoiceSource and ItemSource: the JSON as it is in the file
}

public sealed record Party(string Name, IReadOnlyList<string> Address, string Email);

public sealed record Customer(string Name, string Contact, IReadOnlyList<string> Address);

public sealed record LineItem(string Sku, string Description, int Qty, decimal UnitPrice, decimal Amount, bool Backorder);

public sealed record Totals(decimal Subtotal, decimal TaxPercent, decimal Tax, decimal Shipping, decimal Total);
```

## 2. Render it with HttpClient [#2-render-it-with-httpclient]

Set your test key and run the first program:

```bash
export DYNAMIC_DOCUMENT_API_KEY="dda_test_..."
dotnet run --project src/RenderInvoice
# Wrote invoice.pdf (2 pages)
```

`RenderInvoice` sends template, data and page settings in one `POST`:

```csharp
// src/RenderInvoice/Program.cs
// The invoice from the Jinja template: one POST with HttpClient, the PDF comes back in the response body.
//
//   export DYNAMIC_DOCUMENT_API_KEY="dda_test_..."
//   dotnet run --project src/RenderInvoice

using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Invoices;

var apiKey = Environment.GetEnvironmentVariable("DYNAMIC_DOCUMENT_API_KEY")
    ?? throw new InvalidOperationException("Set DYNAMIC_DOCUMENT_API_KEY to your API key.");

using var http = new HttpClient
{
    BaseAddress = new Uri("https://api-eu.dynamicdocumentapi.com/v1/"),
    // A little longer than the API ever waits for a render (up to 120 s). A very slow render then
    // comes back as 202, still running, instead of failing here with a timeout.
    Timeout = TimeSpan.FromSeconds(130),
};
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

var request = new
{
    html = await File.ReadAllTextAsync(Invoice.TemplatePath),
    data = Invoice.Load(),
    pdf = new
    {
        paper = new { size = "Letter" },
        margin = new { top = "16mm", right = "16mm", bottom = "20mm", left = "16mm" },
        footer = new { enabled = true, right = "Page {{page}} of {{pages}}", height = "12mm" },
    },
    delivery = "binary",
};

using var response = await http.PostAsJsonAsync("pdf/from-html", request, Invoice.JsonOptions);
if (response.StatusCode != HttpStatusCode.OK)
{
    throw new HttpRequestException(
        $"Render failed: {(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
}

await using (var file = File.Create("invoice.pdf"))
{
    await response.Content.CopyToAsync(file);
}

Console.WriteLine($"Wrote invoice.pdf ({response.Headers.GetValues("X-Pages").Single()} pages)");
```

With `"delivery": "binary"`, the PDF is the response body, and the headers carry the page count (`X-Pages`), the render's ID (`X-Render-Id`) and the number of renders it was billed as (`X-Billed-Renders`). The anonymous objects become the JSON body; `Invoice.JsonOptions` turns `UnitPrice` into `unit_price` on the way. The timeout of 130 seconds is a little longer than the API ever waits for a render: up to 120 seconds, depending on your plan. A very slow render then comes back as `202`, still running, instead of failing in your code with a timeout, see [going to production](#going-to-production). With a test key the request is free and the PDF has a TEST watermark; a live key (`dda_live_…`) produces the clean document.

## 3. Page size, margins and page numbers [#3-page-size-margins-and-page-numbers]

Everything about the page goes in the `pdf` object, see [PDF options](https://dynamicdocumentapi.com/docs/pdf-options):

| Option                  | Here                         | Effect                                                                                          |
| ----------------------- | ---------------------------- | ----------------------------------------------------------------------------------------------- |
| `paper.size`            | `"Letter"`                   | US Letter. `"A4"`, `"Legal"` and other sizes work too, or your own `width` and `height`         |
| `margin`                | 16 mm, 20 mm at the bottom   | The space around the content; the footer sits in the bottom margin                              |
| `footer.right`          | `Page {{page}} of {{pages}}` | Simple mode: text for the `left`, `center` and `right` slots, filled with the template language |
| `{{page}}`, `{{pages}}` | `Page 1 of 2`                | The current page and the total, inserted while the PDF is printed                               |
| `footer.height`         | `"12mm"`                     | The height of the footer band on every page                                                     |

A slot such as `left = "{{ seller.name }} · Invoice {{ number }}"` reads from the same `data` as the page. For a logo in the header or your own layout, switch to HTML mode, see [headers and footers](https://dynamicdocumentapi.com/docs/headers-and-footers).

## Already using Razor? Render a component to HTML [#already-using-razor-render-a-component-to-html]

If your team writes its HTML in Razor, keep it there. Since .NET 8, the `HtmlRenderer` class in `Microsoft.AspNetCore.Components.Web` renders a Razor component to an HTML string, without a browser and without a web server. It is .NET's own class, not the HtmlRenderer.PdfSharp library from the comparison. `InvoiceDocument.razor` is the same invoice with C# instead of placeholders; this is its line-item table:

```razor
@* src/Invoices/InvoiceDocument.razor (excerpt) *@
  <table>
    <thead>
      <tr><th>#</th><th>SKU</th><th>Item</th><th class="num">Qty</th><th class="num">Unit price</th><th class="num">Amount</th></tr>
    </thead>
    <tbody>
      @foreach (var (item, index) in Invoice.Items.Select((item, i) => (item, i + 1)))
      {
        <tr>
          <td class="muted">@index</td>
          <td class="sku">@item.Sku</td>
          <td>@(item.Description)@if (item.Backorder) {<span class="badge">Backorder</span>}</td>
          <td class="num">@item.Qty</td>
          <td class="num">@Money(item.UnitPrice)</td>
          <td class="num">@Money(item.Amount)</td>
        </tr>
      }
    </tbody>
  </table>

@code {
    [Parameter, EditorRequired] public Invoice Invoice { get; set; } = default!;

    // $45,172.62, whatever the server's culture is
    static string Money(decimal value) => value.ToString("C", CultureInfo.GetCultureInfo("en-US"));
}
```

`InvoiceHtml.RenderAsync` renders the component and returns the HTML:

```csharp
// src/Invoices/InvoiceHtml.cs
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace Invoices;

/// <summary>Renders <see cref="InvoiceDocument"/> to an HTML string with .NET's HtmlRenderer, no browser and no web server.</summary>
public static class InvoiceHtml
{
    public static async Task<string> RenderAsync(Invoice invoice)
    {
        await using var services = new ServiceCollection().BuildServiceProvider();
        await using var renderer = new HtmlRenderer(services, NullLoggerFactory.Instance);

        return await renderer.Dispatcher.InvokeAsync(async () =>
        {
            var parameters = ParameterView.FromDictionary(new Dictionary<string, object?> { ["Invoice"] = invoice });
            var output = await renderer.RenderComponentAsync<InvoiceDocument>(parameters);
            return output.ToHtmlString();
        });
    }
}
```

The project that holds the component needs the Razor SDK and ASP.NET Core's shared framework, even when only a console app uses it:

```xml
<!-- src/Invoices/Invoices.csproj -->
<Project Sdk="Microsoft.NET.Sdk.Razor">

  <!-- The invoice data (Invoice.cs), the Razor version of the template (InvoiceDocument.razor) and the
       helper that renders it to an HTML string (InvoiceHtml.cs). Shared by the apps and the comparison. -->

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

  <ItemGroup>
    <!-- invoice.html (the Jinja template the API fills) and invoice.json (the sample data) -->
    <None Include="..\..\invoice\*" LinkBase="invoice" CopyToOutputDirectory="PreserveNewest" />
  </ItemGroup>

</Project>
```

Then send the finished HTML with templating turned off:

```csharp
// src/RenderRazorInvoice/Program.cs (excerpt)
var html = await InvoiceHtml.RenderAsync(Invoice.Load());

// … HttpClient as in step 2

using var response = await http.PostAsJsonAsync("pdf/from-html", new
{
    html,
    templating = false,
    pdf = new
    {
        paper = new { size = "Letter" },
        margin = new { top = "16mm", right = "16mm", bottom = "20mm", left = "16mm" },
        footer = new { enabled = true, right = "Page {{page}} of {{pages}}", height = "12mm" },
    },
    delivery = "binary",
});
```

`templating = false` tells the API that the HTML is final: `{{ }}` in your data is printed as text, not filled in again. `{{page}}` and `{{pages}}` in the footer still work, because the footer belongs to the page options, not to your HTML. Both ways produce the same PDF; in our test, page 1 was pixel-identical. Razor gives you compile-time checks and C# helpers; templates in the API's language can be stored and versioned in the dashboard.

## Serve the PDF from ASP.NET Core [#serve-the-pdf-from-aspnet-core]

In a web app the PDF is usually a download link. `InvoiceApi` is a minimal API with one route, `GET /invoices/{number}.pdf`. It sends the render request through a typed `HttpClient` and streams the PDF to the browser while it arrives, so the server never holds the whole file in memory:

```csharp
// src/InvoiceApi/Program.cs
// GET /invoices/INV-2026-0418.pdf returns the invoice as a PDF, streamed from the API to the browser.
//
//   export DYNAMIC_DOCUMENT_API_KEY="dda_test_..."
//   dotnet run --project src/InvoiceApi
//   open http://localhost:5000/invoices/INV-2026-0418.pdf

using System.Net.Http.Headers;
using Invoices;

var builder = WebApplication.CreateBuilder(args);

var apiKey = builder.Configuration["DYNAMIC_DOCUMENT_API_KEY"]
    ?? throw new InvalidOperationException("Set DYNAMIC_DOCUMENT_API_KEY to your API key.");

builder.Services
    .AddHttpClient<DocumentApiClient>(client =>
    {
        client.BaseAddress = new Uri("https://api-eu.dynamicdocumentapi.com/v1/");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        client.Timeout = Timeout.InfiniteTimeSpan; // the resilience handler below sets the timeouts
    })
    .AddStandardResilienceHandler(options =>
    {
        // The defaults (10 s per attempt, 30 s in total) are made for quick JSON calls and would cancel
        // a render that is still running. A sync render waits up to 120 s on the largest plans.
        options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(130);
        options.TotalRequestTimeout.Timeout = TimeSpan.FromMinutes(5);
        options.CircuitBreaker.SamplingDuration = TimeSpan.FromMinutes(5); // at least twice the attempt timeout
    });

var app = builder.Build();

// The sample data has one invoice. In your app this is a database lookup.
var invoices = new[] { Invoice.Load() }.ToDictionary(invoice => invoice.Number);

app.MapGet("/invoices/{number}.pdf", async (string number, DocumentApiClient api, CancellationToken cancellationToken) =>
{
    if (!invoices.TryGetValue(number, out var invoice))
    {
        return Results.NotFound();
    }

    var pdf = await api.RenderInvoiceAsync(invoice, cancellationToken);
    return Results.Stream(pdf, "application/pdf", fileDownloadName: $"{number}.pdf");
});

app.Run();

public partial class Program;
```

```csharp
// src/InvoiceApi/DocumentApiClient.cs
using System.Net;
using System.Net.Http.Json;
using Invoices;

/// <summary>
/// Typed HttpClient for the Dynamic Document API. <see cref="RenderInvoiceAsync"/> returns the PDF as a
/// stream that is still being read from the network, so the caller can pass it on without buffering it.
/// </summary>
public sealed class DocumentApiClient(HttpClient http)
{
    static readonly string Template = File.ReadAllText(Invoice.TemplatePath);

    public async Task<Stream> RenderInvoiceAsync(Invoice invoice, CancellationToken cancellationToken)
    {
        using var request = new HttpRequestMessage(HttpMethod.Post, "pdf/from-html")
        {
            Content = JsonContent.Create(new
            {
                html = Template,
                data = invoice,
                pdf = new
                {
                    paper = new { size = "Letter" },
                    margin = new { top = "16mm", right = "16mm", bottom = "20mm", left = "16mm" },
                    footer = new { enabled = true, right = "Page {{page}} of {{pages}}", height = "12mm" },
                },
                delivery = "binary",
            }, options: Invoice.JsonOptions),
        };
        // One key per invoice request. The resilience handler resends this same message on a retry,
        // key included, so a retry after a timeout can never produce a second document.
        request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());

        // ResponseHeadersRead: return as soon as the headers are in, the body streams afterwards.
        var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
        if (response.StatusCode == HttpStatusCode.Accepted)
        {
            // The render took longer than your plan's sync timeout and goes on in the background. An invoice
            // doesn't get there; for long documents render with "mode": "async" and a webhook instead.
            var location = response.Headers.Location;
            response.Dispose();
            throw new TimeoutException($"The render is still running: {location}");
        }
        if (response.StatusCode != HttpStatusCode.OK)
        {
            using (response)
            {
                var body = await response.Content.ReadAsStringAsync(cancellationToken);
                var requestId = response.Headers.TryGetValues("X-Request-Id", out var ids) ? ids.First() : "none";
                throw new HttpRequestException(
                    $"Render failed with {(int)response.StatusCode} (request {requestId}): {body}",
                    inner: null,
                    response.StatusCode);
            }
        }

        // Disposing this stream (Results.Stream does) releases the response and its connection.
        return await response.Content.ReadAsStreamAsync(cancellationToken);
    }
}
```

```bash
dotnet run --project src/InvoiceApi
# open http://localhost:5000/invoices/INV-2026-0418.pdf
```

In your own project, add the resilience handler with `dotnet add package Microsoft.Extensions.Http.Resilience`. What the pieces do:

* **`AddHttpClient<DocumentApiClient>`** registers a typed client whose connections `IHttpClientFactory` manages.
* **`HttpCompletionOption.ResponseHeadersRead`** returns as soon as the headers are in. `Results.Stream` copies the body to the browser while it is still arriving and disposes the response afterwards; `fileDownloadName` makes it a download with the invoice number as file name.
* **The `CancellationToken`** belongs to the browser's request: if the user closes the tab, the call to the API is canceled too.
* **`AddStandardResilienceHandler`** adds retries with exponential backoff, a circuit breaker and timeouts. Its defaults, 10 seconds per attempt and 30 seconds in total, would cancel a render that is still running, so the code raises them. The total timeout has to stay above the attempt timeout and the circuit breaker's sampling duration at least twice as long, otherwise creating the client fails with an `OptionsValidationException`.
* **The handler retries `POST` too.** It resends a request after `408`, `429`, `5xx`, timeouts and network errors, and honours `Retry-After`. That is safe here only because of the `Idempotency-Key`: the handler resends the same message, key included, and the API answers a repeated key with the original response instead of rendering a second time. We tested it: against a server that answered `503` twice, the handler sent the request three times, each with the same key and body.

## Going to production [#going-to-production]

* **Log the `request_id`.** Errors come as problem details (`application/problem+json`) with a stable `code` to branch on and a `request_id`, which is also in the `X-Request-Id` header. `DocumentApiClient` puts both into the exception; quote the ID to support. All codes: [errors](https://dynamicdocumentapi.com/docs/errors).
* **Don't retry what fails the same way again.** For example, `422 template_runtime_error` is a mistake in the template, and `402 render_limit_reached` means the Free plan's renders are used up. The standard handler retries none of the `4xx` codes except `408` and `429`.
* **Keys for whole jobs.** The new GUID protects one request and its retries. When your job queue retries a whole job, derive the key from the invoice, such as `invoice-INV-2026-0418`: within 24 hours the second run gets the first response back, with no second render and no second bill. When the invoice changes, use a new key; the same key with a different body fails with `422 idempotency_key_reused`.
* **Long documents.** A render waits synchronously up to your plan's sync timeout (30 seconds on Free, up to 120 seconds on higher plans). After that the API answers `202` with a `Location` header and the render continues; `DocumentApiClient` turns that into a `TimeoutException`. Fetch the render with `GET /v1/renders/{id}` once it has succeeded. Send long documents and monthly invoice runs as async renders with a [webhook](https://dynamicdocumentapi.com/docs/webhooks), or on paid plans as a [batch](https://dynamicdocumentapi.com/docs/batches). Binary responses are limited to 20 MB; larger files fail with `413 output_too_large`, so use the download URL for them. Limits per plan: [plans and limits](https://dynamicdocumentapi.com/docs/plans-and-limits).
* **Store the template.** Save `invoice.html` as a template in the dashboard and send only its ID and the data to `POST /v1/pdf/from-template`. Templates are versioned, so a design change never breaks a running integration.
* **Go live.** Keep the key out of `appsettings.json` (use `dotnet user-secrets` or an environment variable) and swap the test key for a live key. Test renders are free and their files are deleted after 24 hours; the Free plan includes 50 live renders a month.

## Frequently asked questions [#frequently-asked-questions]

### How do I convert HTML to PDF in C# without wkhtmltopdf? [#how-do-i-convert-html-to-pdf-in-c-without-wkhtmltopdf]

Use one of the other options from the [comparison](#c-html-to-pdf-libraries-tested): PuppeteerSharp if you can run Chrome yourself, iText pdfHTML if its license fits and you don't need JavaScript, or an HTML to PDF API that runs Chromium for you. HtmlRenderer.PdfSharp only fits simple layouts without Flexbox or grid. wkhtmltopdf has been archived since January 2023 and its WebKit doesn't support Flexbox or grid, so DinkToPdf and other wrappers around it inherit both; the [wkhtmltopdf alternatives](https://dynamicdocumentapi.com/alternatives/wkhtmltopdf/) page covers the migration.

### What about iTextSharp? [#what-about-itextsharp]

The `itextsharp` package on NuGet is iText 5. HTML conversion in current iText versions is the pdfHTML add-on, the `itext.pdfhtml` package (formerly `itext7.pdfhtml`), which we tested above. Both are licensed under the AGPL-3.0 or commercially.

### Does PuppeteerSharp work on a Linux server? [#does-puppeteersharp-work-on-a-linux-server]

Yes, with some setup. On first use it downloads Chrome: about 720 MB in our test, Chrome plus its headless shell, so put it into your image or server instead of downloading it at startup. On Ubuntu 23.10 and later, Chrome then stops with "No usable sandbox!", because AppArmor restricts the user namespaces its sandbox needs. Our [workflow](https://github.com/DynamicDocumentApi/html-to-pdf-csharp/blob/main/.github/workflows/compare.yml) allows them with one `sysctl` line instead of turning the sandbox off with `--no-sandbox`.

### How do I add page numbers to a PDF generated from HTML in C#? [#how-do-i-add-page-numbers-to-a-pdf-generated-from-html-in-c]

It depends on the tool: `FooterTemplate` with the `pageNumber` and `totalPages` classes in PuppeteerSharp, CSS `@page` margin boxes with `counter(page)` and `counter(pages)` in iText pdfHTML, `[page]` and `[topage]` in DinkToPdf's `FooterSettings`, and for HtmlRenderer.PdfSharp, drawing the numbers onto each page with PDFsharp afterwards. All four are in [`Renderers.cs`](https://github.com/DynamicDocumentApi/html-to-pdf-csharp/blob/main/compare/Compare/Renderers.cs). With the API, put `{{page}}` and `{{pages}}` into `pdf.footer` or `pdf.header`, as in [step 3](#3-page-size-margins-and-page-numbers).

### Is it free to try? [#is-it-free-to-try]

Yes. Test keys are free on every plan and add a TEST watermark. The Free plan includes 50 live renders a month, no card needed. [Create an account](https://app.dynamicdocumentapi.com/signup).

## Next steps [#next-steps]

* **The same invoice in Python.** The [Python tutorial](https://dynamicdocumentapi.com/docs/tutorials/html-to-pdf-python) uses the Python SDK and compares xhtml2pdf, WeasyPrint, pdfkit and Playwright.
* **Long reports.** The [Node.js tutorial](https://dynamicdocumentapi.com/docs/tutorials/html-to-pdf-nodejs) builds a nine-page report with long tables, a new page per section and a running header; the same options work from C#.
* **E-invoices.** Add a ZUGFeRD / Factur-X XML to the same invoice PDF, see [ZUGFeRD and Factur-X invoices](https://dynamicdocumentapi.com/docs/tutorials/zugferd-xrechnung-invoices-api).
* **The product pages:** [HTML to PDF API](https://dynamicdocumentapi.com/html-to-pdf-api/), [PDF generation API](https://dynamicdocumentapi.com/pdf-generation-api/) and [invoice PDF API](https://dynamicdocumentapi.com/invoice-pdf-api/).

Related: [renders](https://dynamicdocumentapi.com/docs/renders), [template language](https://dynamicdocumentapi.com/docs/template-language), [PDF options](https://dynamicdocumentapi.com/docs/pdf-options), [pagination basics](https://dynamicdocumentapi.com/docs/pagination), [headers and footers](https://dynamicdocumentapi.com/docs/headers-and-footers), [errors](https://dynamicdocumentapi.com/docs/errors), [SDKs and integrations](https://dynamicdocumentapi.com/docs/sdks-and-integrations).
