To convert HTML to PDF in C#, you either run a rendering engine inside your app or call a service that runs one for you. In .NET that means DinkToPdf (a wrapper around wkhtmltopdf), PuppeteerSharp or Playwright (headless Chromium), or a REST API such as ASHDOCS. Each one turns an HTML string, an HTML file or a URL into a PDF; they differ in CSS support, JavaScript and what you have to deploy.
Generating PDFs from HTML is one of those .NET tasks that looks solved until you're the one shipping it. Invoices, order confirmations, reports — the HTML already exists; the question is which rendering engine turns it into a faithful PDF, and what that engine costs you to operate.
We ran every sample in this post on .NET 8 (SDK 8.0.426) on 22 October 2026 with DinkToPdf 1.0.8, PuppeteerSharp 25.15.0 and Microsoft.Playwright 1.64.0, rendering the same three-line invoice with each. The screenshots further down are page one of those PDFs.
Which C# library should you use for HTML to PDF?
Use PuppeteerSharp or Playwright when you need Chrome-exact output and can run a browser on your servers, a REST API when you'd rather not deploy a browser at all, and DinkToPdf only for simple, table-based layouts you control.
| Library | Rendering engine | License | Linux / Docker | JavaScript |
|---|---|---|---|---|
| DinkToPdf | wkhtmltopdf 0.12.4 (an old Qt WebKit build) | MIT wrapper; wkhtmltopdf itself is LGPL-3.0 | Ships libwkhtmltox.so, .dylib and .dll; you copy the right one next to your app | Runs, but on an old WebKit: our flexbox layout came out stacked |
| PuppeteerSharp | Chromium (Chrome for Testing) | MIT | Yes, with Chromium's Linux libraries in the image | Yes, full Chrome |
| Playwright for .NET | Chromium (also Firefox and WebKit) | MIT | Yes; Microsoft's mcr.microsoft.com/playwright/dotnet image includes the browsers and their system dependencies | Yes, full Chrome |
| ASHDOCS REST API | HTML: WeasyPrint (headless Chromium for 512 KB of HTML or more); URLs: headless Chromium | Hosted service with a free plan | Nothing to install; anything that can make an HTTPS call | Not for HTML (scripts never run); yes for URL to PDF |
Sources, checked 22 October 2026: DinkToPdf on GitHub and NuGet, wkhtmltopdf's license, PuppeteerSharp on NuGet, Microsoft.Playwright on NuGet and Playwright's Docker docs.
How do wkhtmltopdf wrappers like DinkToPdf work in C#?
The old workhorse: a WebKit-based CLI with .NET wrappers.
var converter = new SynchronizedConverter(new PdfTools());
var doc = new HtmlToPdfDocument {
GlobalSettings = { PaperSize = PaperKind.A4 },
Objects = { new ObjectSettings { HtmlContent = html } }
};
byte[] pdf = converter.Convert(doc);
Upside: free, offline, battle-tested. Downside: the underlying engine froze years ago — its WebKit predates flexbox and grid as you know them, so modern CSS silently breaks. Native-library deployment on Linux containers is its own small hobby. Choose it only for simple, table-based layouts you control completely.
Install DinkToPdf
dotnet add package DinkToPdf
The NuGet package is only the wrapper. Download the native library for your platform (libwkhtmltox.dll, .so or .dylib) from the v0.12.4 folder of the DinkToPdf repository and copy it to your build output. Create the converter once and reuse it; SynchronizedConverter is the thread-safe one.
HTML string, HTML file and URL with DinkToPdf
using DinkToPdf;
var converter = new SynchronizedConverter(new PdfTools());
// 1. An HTML string
var fromString = new HtmlToPdfDocument
{
GlobalSettings = { PaperSize = PaperKind.A4,
Margins = new MarginSettings { Top = 18, Bottom = 18, Left = 16, Right = 16 } },
Objects = { new ObjectSettings { HtmlContent = "<h1>Invoice INV-1042</h1>",
WebSettings = { DefaultEncoding = "utf-8" } } }
};
File.WriteAllBytes("from-string.pdf", converter.Convert(fromString));
// 2. An HTML file, with a header and a footer
var fromFile = new HtmlToPdfDocument
{
GlobalSettings = { PaperSize = PaperKind.A4 },
Objects = { new ObjectSettings {
Page = Path.GetFullPath("invoice.html"),
WebSettings = { DefaultEncoding = "utf-8", PrintMediaType = true },
HeaderSettings = { Right = "Page [page] of [toPage]", FontSize = 8 },
FooterSettings = { Center = "Northwind Studio", FontSize = 8, Line = true }
} }
};
File.WriteAllBytes("from-file.pdf", converter.Convert(fromFile));
// 3. A URL
var fromUrl = new HtmlToPdfDocument
{
GlobalSettings = { PaperSize = PaperKind.Letter },
Objects = { new ObjectSettings { Page = "http://example.com/" } }
};
File.WriteAllBytes("from-url.pdf", converter.Convert(fromUrl));
One thing that caught us out: on Windows, with the 0.12.4 native library from the repository, http:// pages rendered but every https:// page we tried came back as an empty file, with no exception. If your sources are HTTPS, fetch the HTML yourself with HttpClient and pass it as HtmlContent, or pick another method.
Is wkhtmltopdf still maintained?
No. The wkhtmltopdf GitHub repository was archived by its owner on 2 January 2023 and is read-only, and its last release, 0.12.6, came out in June 2020 (checked 22 October 2026). DinkToPdf's NuGet package was last updated in April 2017 and points at the older 0.12.4 build. Nothing is going to fix its CSS support or its TLS behavior, so treat it as legacy.
How do you use headless Chromium (PuppeteerSharp, Playwright) in .NET?
Run a real browser and print:
await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
await using var page = await browser.NewPageAsync();
await page.SetContentAsync(html, new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });
byte[] pdf = await page.PdfAsync(new PdfOptions { Format = PaperFormat.A4, PrintBackground = true });
Upside: perfect modern-CSS fidelity — it is Chrome. Downside: you now operate a browser fleet: ~300–500 MB memory per instance, zombie processes to reap, Chromium security patches to track, and container images that balloon. Fine for low volume on infrastructure you already babysit.
Install PuppeteerSharp or Playwright
dotnet add package PuppeteerSharp
PuppeteerSharp downloads a matching Chrome build the first time you call new BrowserFetcher().DownloadAsync(). Playwright installs its browsers with a script that the build drops in your output folder:
dotnet add package Microsoft.Playwright
dotnet build
pwsh bin/Debug/net8.0/playwright.ps1 install chromium
HTML string, HTML file and URL with PuppeteerSharp
using PuppeteerSharp;
using PuppeteerSharp.Media;
await new BrowserFetcher().DownloadAsync();
await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
// 1. An HTML string
await using (var page = await browser.NewPageAsync())
{
await page.SetContentAsync("<h1>Invoice INV-1042</h1>");
await page.PdfAsync("from-string.pdf", new PdfOptions { Format = PaperFormat.A4 });
}
// 2. An HTML file, with margins, a header and a footer
await using (var page = await browser.NewPageAsync())
{
var html = await File.ReadAllTextAsync("invoice.html");
await page.SetContentAsync(html, new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });
await page.PdfAsync("from-file.pdf", new PdfOptions
{
Format = PaperFormat.A4,
PrintBackground = true,
MarginOptions = new MarginOptions { Top = "20mm", Bottom = "20mm", Left = "16mm", Right = "16mm" },
DisplayHeaderFooter = true,
HeaderTemplate = "<div style='font-size:8px;width:100%;text-align:right;padding-right:16mm'>INV-1042</div>",
FooterTemplate = "<div style='font-size:8px;width:100%;text-align:center'>Page <span class='pageNumber'></span> of <span class='totalPages'></span></div>",
});
}
// 3. A URL, waiting until the network goes quiet so scripts and fonts finish
await using (var page = await browser.NewPageAsync())
{
await page.GoToAsync("https://example.com/", WaitUntilNavigation.Networkidle0);
await page.PdfAsync("from-url.pdf", new PdfOptions { Format = PaperFormat.Letter, PrintBackground = true });
}
The same three with Playwright for .NET
using Microsoft.Playwright;
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
// 1. An HTML string
var page = await browser.NewPageAsync();
await page.SetContentAsync("<h1>Invoice INV-1042</h1>");
await page.PdfAsync(new PagePdfOptions { Path = "from-string.pdf", Format = "A4" });
// 2. An HTML file, opened by its file:// URL so relative images and CSS resolve
page = await browser.NewPageAsync();
await page.GotoAsync(new Uri(Path.GetFullPath("invoice.html")).AbsoluteUri);
await page.PdfAsync(new PagePdfOptions
{
Path = "from-file.pdf", Format = "A4", PrintBackground = true,
Margin = new Margin { Top = "20mm", Bottom = "20mm", Left = "16mm", Right = "16mm" },
DisplayHeaderFooter = true,
HeaderTemplate = "<span></span>",
FooterTemplate = "<div style='font-size:8px;width:100%;text-align:center'>Page <span class='pageNumber'></span> of <span class='totalPages'></span></div>",
});
// 3. A URL
page = await browser.NewPageAsync();
await page.GotoAsync("https://example.com/", new PageGotoOptions { WaitUntil = WaitUntilState.NetworkIdle });
await page.PdfAsync(new PagePdfOptions { Path = "from-url.pdf", Format = "Letter" });
When should you use a REST API for HTML to PDF in C#?
Move the rendering to someone else's servers:
using System.Net.Http.Json;
using System.Text.Json;
using var http = new HttpClient { BaseAddress = new Uri("https://api.ashdocs.com") };
http.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var resp = await http.PostAsJsonAsync("/api/v1/tools/html-to-pdf",
new { html = "<h1>Invoice #1042</h1>", options = new { output = "url" } });
resp.EnsureSuccessStatusCode();
using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
var fileUrl = doc.RootElement.GetProperty("file_url").GetString()!;
byte[] pdf = await http.GetByteArrayAsync(fileUrl);
Upside: no browser and no native library to deploy; scales without capacity planning; works identically from an Azure Function, a container, or a background worker. Downside: per-conversion cost and a network dependency — mitigate the latter with retries and an idempotency key.
The HTML-to-PDF endpoint reference lists the request fields, options and error codes, and the HTML to PDF tool lets you try the conversion in the browser before you write any C#.
Install nothing
There's no NuGet package to add. HttpClient and System.Net.Http.Json ship with .NET. Get a free test key from the dashboard; test keys never use credits, and on a live key an HTML render costs 1 credit and a URL render 2.
HTML string, HTML file and URL with the API
using System.Net.Http.Json;
using System.Text.Json;
using var http = new HttpClient { BaseAddress = new Uri("https://api.ashdocs.com"),
Timeout = TimeSpan.FromMinutes(3) };
http.DefaultRequestHeaders.Add("X-API-Key", Environment.GetEnvironmentVariable("ASHDOCS_API_KEY"));
async Task SaveFromAsync(HttpResponseMessage resp, string path)
{
resp.EnsureSuccessStatusCode();
using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
var fileUrl = doc.RootElement.GetProperty("file_url").GetString()!; // signed, valid for one hour
await File.WriteAllBytesAsync(path, await http.GetByteArrayAsync(fileUrl));
}
// 1. An HTML string
await SaveFromAsync(await http.PostAsJsonAsync("/api/v1/tools/html-to-pdf",
new { html = "<h1>Invoice INV-1042</h1>", options = new { output = "url" } }), "from-string.pdf");
// 2. An HTML file: send its contents (page size and margins come from its @page rule)
var invoiceHtml = await File.ReadAllTextAsync("invoice.html");
await SaveFromAsync(await http.PostAsJsonAsync("/api/v1/tools/html-to-pdf",
new { html = invoiceHtml, options = new { output = "url" } }), "from-file.pdf");
// 3. A URL, rendered in headless Chromium
await SaveFromAsync(await http.PostAsJsonAsync("/api/v1/tools/url-to-pdf",
new { url = "https://example.com/", options = new { format = "Letter", output = "url" } }), "from-url.pdf");
"output": "url" makes the response a flat object with file_url, expires_at and credits_charged, which is simpler than the full job record. Download the file before expires_at, an hour after the render.
Headers, footers, page size, margins and waiting for JavaScript
Each method controls the page differently, so this is where most porting bugs come from.
| Setting | DinkToPdf | PuppeteerSharp / Playwright | ASHDOCS API |
|---|---|---|---|
| Page size | GlobalSettings.PaperSize | PdfOptions.Format / PagePdfOptions.Format | HTML: CSS @page { size: A4; }; URL: format (A4, Letter, Legal, A3, A5) |
| Margins | GlobalSettings.Margins (mm) | MarginOptions / Margin | HTML: CSS @page { margin: … }; URL: margin_mm (0–50) |
| Header and footer | HeaderSettings, FooterSettings with [page] and [toPage] | DisplayHeaderFooter with HeaderTemplate and FooterTemplate (pageNumber, totalPages classes) | Put them in your HTML and CSS |
| Backgrounds | Printed | PrintBackground = true | Printed |
| Wait for JavaScript | Old WebKit only | Networkidle0 / NetworkIdle, or wait for a selector | HTML: no scripts run, so send finished markup; URL: wait_until (default networkidle) and wait_extra_ms (0–10,000) |
The API's HTML renderer runs no JavaScript at all, so a chart drawn by a script won't appear. Either render the chart to an image or SVG before you send the HTML, or put the page online and use URL to PDF, which runs the page in Chromium and waits for the network to go quiet.
How do you render a Razor view or component to PDF in ASP.NET Core?
Render the Razor markup to an HTML string first, then hand that string to whichever method you picked. Since .NET 8, HtmlRenderer renders a Razor component to a string without an HTTP request, in a console app, a worker or a controller (Microsoft's docs, checked 22 October 2026).
@* Invoice.razor *@
<h1>Invoice @Number</h1>
<p>Bill to: @Customer</p>
<table>
@foreach (var line in Lines)
{
<tr><td>@line.Description</td><td>@line.Amount.ToString("C")</td></tr>
}
</table>
<p><strong>Total due: @Lines.Sum(l => l.Amount).ToString("C")</strong></p>
@code {
[Parameter] public string Number { get; set; } = "";
[Parameter] public string Customer { get; set; } = "";
[Parameter] public List<InvoiceLine> Lines { get; set; } = new();
}
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
var services = new ServiceCollection().AddLogging().BuildServiceProvider();
await using var renderer = new HtmlRenderer(services, services.GetRequiredService<ILoggerFactory>());
var html = await renderer.Dispatcher.InvokeAsync(async () =>
{
var parameters = ParameterView.FromDictionary(new Dictionary<string, object?>
{
["Number"] = "INV-1042",
["Customer"] = "Acme Inc",
["Lines"] = new List<InvoiceLine> { new("Website redesign", 2400m), new("Hosting", 120m) },
});
var output = await renderer.RenderComponentAsync<Invoice>(parameters);
return output.ToHtmlString();
});
// html now holds the rendered invoice: pass it to DinkToPdf, PuppeteerSharp or the API.
public record InvoiceLine(string Description, decimal Amount);
The project needs <Project Sdk="Microsoft.NET.Sdk.Razor">; outside ASP.NET Core, also add the Microsoft.AspNetCore.Components.Web and Microsoft.Extensions.Logging packages. In an ASP.NET Core app they're already there. Keep the component free of anything that only works in a browser, such as JavaScript interop, because there's no browser at this stage.
What does each method's output look like?
These are page one of the same invoice.html rendered by each method. The file uses flexbox for the header and the "Bill to" and "Payment terms" columns.
HeaderSettings.
@page rule.Which HTML to PDF method should you pick in C#?
Static, simple markup and zero budget → wkhtmltopdf. Modern CSS, low volume, existing browser ops → PuppeteerSharp. Modern CSS at production volume, or a team that would rather not patch Chromium → the API. A useful tiebreak: if PDF generation is your product, own the fleet; if it's a feature, rent it.
Very large documents are the other deciding factor. A browser you run yourself handles them as long as your server has the memory. On the API, HTML of 2 MB or more is accepted with 202 Accepted and a job_id instead of the finished file, and you collect the result when the job completes, by polling or with a webhook.
FAQ
Why does my C# HTML to PDF output look different from the browser? Almost always the rendering engine: wkhtmltopdf's WebKit predates modern flexbox/grid. Rendering through actual Chromium (PuppeteerSharp or Playwright locally, or a URL-to-PDF API) makes output match Chrome's print preview.
Can I generate PDFs in Azure Functions? Headless Chromium inside Functions is possible but fights cold starts and memory caps. An HTTP call to a conversion API sidesteps both.
How do I keep backgrounds and colors?
Set PrintBackground = true in PuppeteerSharp or Playwright — Chrome's print pipeline strips backgrounds by default. DinkToPdf and the ASHDOCS HTML renderer print them as they are.
Is there a free way to test? The free tier includes 10 credits monthly, and sandbox keys render without consuming credits.
What is the best C# library for HTML to PDF? For most projects that need modern CSS, PuppeteerSharp or Playwright for .NET: both drive real Chromium and are MIT-licensed. If you don't want to run a browser, call a REST API instead. DinkToPdf only suits simple layouts, because wkhtmltopdf is no longer maintained.
Is there a free C# HTML to PDF library? Yes. DinkToPdf, PuppeteerSharp and Playwright for .NET are all free and open source. Commercial libraries exist too; IronPDF, for example, sells perpetual per-developer licenses starting at $999 (ironpdf.com/licensing, checked 22 October 2026).
Is wkhtmltopdf still maintained? No. Its GitHub repository was archived on 2 January 2023 and its last release was 0.12.6 in June 2020. DinkToPdf wraps the even older 0.12.4 build.
Can I convert a Razor view to PDF?
Yes. Render the view or component to an HTML string first (HtmlRenderer does it for Razor components since .NET 8), then pass that string to PuppeteerSharp, Playwright, DinkToPdf or an HTML to PDF API.
Does HTML to PDF in C# support JavaScript? PuppeteerSharp and Playwright run JavaScript fully; wait for the network to go idle or for a selector before printing. DinkToPdf runs it in an old WebKit. The ASHDOCS HTML renderer doesn't run scripts, but its URL to PDF route does.
How do I convert an HTML string without saving a file?
Pass the string directly: HtmlContent in DinkToPdf, SetContentAsync in PuppeteerSharp and Playwright, or the html field in an API request. None of them needs a file on disk.
Should I use a library or an API? Use a library when you want everything on your own servers and can run and patch Chromium. Use an API when PDFs are one feature among many and you'd rather pay per document than operate a browser.
First PDF in five minutes — get a free API key.