Guide · C# (.NET)
Convert HTML to PDF in C# (.NET)
Chromium makes the best HTML-to-PDF converter, and the worst dependency: hundreds of megabytes, fonts to install, zombie processes to reap. This C# (.NET) program sends an HTML file to the Formfeed API instead and saves what Chromium prints.
Free plan with 100 units a month, no credit card
What you need
- An API key. Create one in the app under API keys and export it as
FORMFEED_API_KEY. A test key (ff_test_…) is right for trying things out. See the quick start. - C# (.NET). You need the .NET 8 SDK or newer and the
Formfeedpackage from NuGet. - An HTML file.
invoice.htmlnext to the program: a complete document with its CSS inline or linked. A sample is further down.
dotnet new console -o render && cd render
dotnet add package Formfeed # then replace Program.csThe program
The program reads invoice.html, posts it with the paper size and the margins, waits for the result when the API answers 202, stops with the API’s message when something is wrong, and saves the PDF.
using Formfeed;
using var formfeed = new FormfeedClient(Environment.GetEnvironmentVariable("FORMFEED_API_KEY"));
// a problem answer (4xx, 5xx) throws a FormfeedException with the API's code and detail
var render = await formfeed.Renders.CreateAsync(new RenderRequest
{
Html = File.ReadAllText("invoice.html"),
Settings = new Dictionary<string, object?>
{
["paper"] = new Dictionary<string, object?> { ["format"] = "A4" },
["margin"] = new Dictionary<string, object?>
{
["top"] = "20mm",
["right"] = "18mm",
["bottom"] = "20mm",
["left"] = "18mm",
},
},
});
// not done within 60 seconds: the API answered 202 and the render goes on in the background
if (render.Status != "succeeded")
{
render = await formfeed.Renders.WaitForAsync(render);
}
if (render.Status == "failed")
{
Console.Error.WriteLine($"render failed: {render.Error?.Code}: {render.Error?.Message}");
return 1;
}
await formfeed.Renders.DownloadToAsync(render, "invoice.pdf");
Console.WriteLine($"{render.Id} {render.PageCount} page(s), {render.Units} unit(s)");
return 0;Run it
It prints the render’s id, the page count and the units it cost, and invoice.pdf lies next to the program.
export FORMFEED_API_KEY=ff_test_...
dotnet runWhat is particular about C# (.NET)
- Requests are classes. A request is a class with the API’s fields as properties (
RenderRequest,ProtectOptions), and what is left null is not sent; free maps such asData,SettingsandPostare dictionaries. The answer is aRender:DownloadUrl,PageCountandUnitsare properties, andRawholds the whole answer. - Retries are built in. The client sends an
Idempotency-Keywith every render and retries429,503and network errors up to three times with backoff, with the same key: a retry of a request that was answered already gets that answer back instead of a second render. - One client, async throughout. Every call of the client is
…Asyncand takes aCancellationToken. It sends over anHttpClientof its own, or the one you pass, such as one fromIHttpClientFactory, and serves any number of calls at the same time: make it once and keep it. - Trimming and native AOT. The SDK’s JSON is generated at build time, so an application that uses it can be trimmed and compiled ahead of time. An object of your own inside
Datathen needsJsonSerializerOptionswhose resolver knows its type; dictionaries, lists and JSON values need nothing.
An HTML file that prints well
The HTML is printed as it is, with the print rules Chromium supports. Web fonts load from a <link>, and two CSS rules keep a long table readable across pages:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap">
<style>
body { font-family: 'Inter', sans-serif; font-size: 10pt; color: #1e293b; }
h1 { font-size: 20pt; color: #312e81; }
table { width: 100%; border-collapse: collapse; }
td, th { padding: 2mm; border-bottom: 1px solid #e2e8f0; text-align: left; }
thead { display: table-header-group; } /* repeats the head row on every page */
tr { break-inside: avoid; }
</style>
</head>
<body>
<h1>Invoice 2026-0042</h1>
<table>
<thead><tr><th>Item</th><th>Amount</th></tr></thead>
<tbody><tr><td>Consulting</td><td>960.00 €</td></tr></tbody>
</table>
</body>
</html>What the settings control
- Paper.
paper.formattakesA4,Letterand the other common names,landscape: trueturns it, andwidthwithheightsets a custom size such as a 100 × 150 mm label. - Margins. Per side, as CSS lengths such as
20mm. A background that should reach the edge needs margins of0. - Header and footer.
header.htmlandfooter.htmlrepeat on every page inside the top and bottom margin; elements with the classespageNumberandtotalPagesshow the page numbers. - Placeholders. Add
"engine": "jinja2"(orliquid,handlebars) and adataobject, and{{ … }}in the HTML is filled before printing, with all helpers for money, dates, barcodes and charts.
When a template is the better tool
Sending HTML is right for pages your application already renders. When the document is yours to design (invoices, certificates, reports), a stored template gives you an editor with a page-accurate preview, versions, and a request that carries only data. The PDF invoice guide of this language shows that variant.
When the API says no
- One shape for every error. Errors are problem documents (RFC 9457) with
type,title,status,detail, a stablecodeand therequest_idto quote to support; thetypeURL leads to a page about that error. The list is in the error reference. - The usual ones.
401 unauthorizedfor a missing or revoked key,404 template_not_foundfor a wrong template name,422 template_runtime_errorwhen the template fails on the data,429 rate_limitedabove the plan’s requests per second,402 quota_exceededwhen the Free plan’s units are used up (a paid plan bills extra units up to its hard cap). - Retry safely. Send an
Idempotency-Keyheader with the POST, and repeat the request with the same key when you do not know whether the first attempt arrived: for 24 hours the key returns the first answer instead of rendering and billing again. The answer is stored once the first attempt has been answered, so do not retry while it may still run; and problems below 500 are stored too, so a corrected request needs a new key.
The job around this program
This guide is one program. What the job needs around it, from the template to the limits and the price, is on the page HTML to PDF API.
More C# (.NET) guides
- Generate a PDF invoice from JSON in C# (.NET)
- Create a ZUGFeRD / Factur-X e-invoice in C# (.NET)
- Convert Markdown to PDF in C# (.NET)
- Generate Open Graph images in C# (.NET)
- Generate PDFs from a CSV in C# (.NET)
- Merge PDFs and add a password in C# (.NET)
- Async PDF rendering with a verified webhook in C# (.NET)
FAQ
- Can it render a URL instead of an HTML string?
- Yes: send
urlinstead ofhtml. It must be a publichttpspage, which is loaded without your cookies or headers; addresses in private networks are refused, and a page that does not load within 30 seconds fails withnavigation_failed. - How large may the HTML be?
- Up to 5 MB per request. Images and fonts are fetched by URL and do not count towards that. Limits per plan are in the docs.
- Does JavaScript in the page run?
- Yes, Chromium runs it before printing, which is how charts render. It waits until the network has been idle, for at most 30 seconds, so a page that keeps loading fails with
render_timeoutrather than hanging.