Convert a web page to PDF in C# without a headless browser
Published 3 min read
Searching for how to convert a web page to PDF in C# usually ends at a headless browser: a Chromium to download, patch and keep running on every server. The rustedf.cloud renderer is not a browser. It lays out HTML and CSS for paper, and you call it over HTTP. That makes the conversion short, but it also decides which pages it suits, so this guide starts with that.
What it does and what it does not
The renderer reads HTML and CSS and draws pages. Three things follow from that:
- No JavaScript runs. A page whose content is built in the browser, such as a single-page app, arrives as an empty shell. For those you need a real browser.
- It never fetches anything. An
<img>that points at a web address is skipped and reported. Images must bedata:URLs or images you uploaded to your account. @importand@font-faceare ignored. Anything unsupported is ignored and reported, never an error, unless you ask for strict mode.
It suits pages the server already renders as complete HTML: receipts, statements, articles, documentation, a page of your own app made for printing. Read Supported HTML and CSS for the full list.
Fetch the page, send the HTML
Add a method to the typed client from the C# and ASP.NET Core guide that sends HTML directly:
public async Task<byte[]> RenderHtmlAsync( string html, string title, CancellationToken cancellationToken = default){ using var response = await http.PostAsJsonAsync( "v1/render", new { html, title }, cancellationToken);
if (!response.IsSuccessStatusCode) { var body = await response.Content.ReadFromJsonAsync<ErrorBody>(cancellationToken); throw new InvalidOperationException( body?.Error?.Message ?? $"Render failed ({(int)response.StatusCode})"); }
return await response.Content.ReadAsByteArrayAsync(cancellationToken);}Then fetch the page and render what you got:
public sealed class PageToPdf(HttpClient fetcher, PdfClient pdf){ public async Task<byte[]> ConvertAsync(Uri page, CancellationToken cancellationToken = default) { var html = await fetcher.GetStringAsync(page, cancellationToken);
// The html field is a template: {{ }} and {% %} are read as placeholders. if (html.Contains("{{") || html.Contains("{%")) throw new InvalidOperationException("The page uses template syntax of its own.");
return await pdf.RenderHtmlAsync(html, page.Host, cancellationToken); }}The check matters. The html field is a template, so a page that contains {{ or {%, for
example a code sample or the shell of a front-end framework, would be read as placeholders.
When your HTML is already final and has none, send it as it is and leave data out.
Images
The images of a page usually point at web addresses, and those are skipped. Download them
yourself and embed them as data: URLs before you send the HTML:
private static readonly Regex ImageSource = new("""<img\b[^>]*?\bsrc="(?<src>[^"]+)""", RegexOptions.IgnoreCase);
private async Task<string> InlineImagesAsync( string html, Uri page, CancellationToken cancellationToken){ var sources = ImageSource.Matches(html).Select(m => m.Groups["src"].Value).Distinct();
foreach (var source in sources) { if (source.StartsWith("data:")) continue;
using var response = await fetcher.GetAsync(new Uri(page, source), cancellationToken); var type = response.Content.Headers.ContentType?.MediaType; if (!response.IsSuccessStatusCode || type is not ("image/png" or "image/jpeg")) continue;
var bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken); html = html.Replace($"\"{source}\"", $"\"data:{type};base64,{Convert.ToBase64String(bytes)}\""); }
return html;}Call it between the fetch and the render. Only PNG and JPEG load, and very large or very
high-resolution images are refused with a note rather than slowing the render. A regular
expression is enough for simple markup; for untidy pages, read the HTML with a parser such as
AngleSharp instead. A logo you use in every document is better uploaded once and referenced as
asset:<id>; see Images.
Check before you rely on it
Send the same body to POST /v1/validate. It renders the page, returns a list of what the
service could not use, and returns no PDF and takes no credit.
using var check = await http.PostAsJsonAsync("v1/validate", new { html, title }, cancellationToken);Console.WriteLine(await check.Content.ReadAsStringAsync(cancellationToken));An entry such as ImageLoadFailed or UnsupportedProperty tells you what the page lost. In
your tests, add "strict": true to the render so a page that uses something unsupported
fails with 422 strict_mode_rejected and the list of what it used.
When the address comes from a user
Your server makes the request to the page, so the address is a risk in your code, not in the renderer: the service never fetches an address from a template, and that is by design. If a user can type the address:
- accept
httpsonly, and check the host against an allow-list; - turn off automatic redirects (
AllowAutoRedirect = false) or check where each one leads, so a public address cannot send you to an internal one; - set a timeout and a maximum response size on the
HttpClient.
Read Render with inline HTML, Validating a document and Errors and limits.
Keep reading
Code and integrations
Generate a PDF in ASP.NET Core: MVC, Razor Pages and minimal APIs
Turn a Razor view into a PDF in ASP.NET Core with one API call: a view renderer, a print-ready view, an MVC action, a Razor Pages handler and the traps to avoid.
3 min read
Code and integrations
C# PDF report generator: a paged table with totals and page numbers
Build a PDF report in C# from a list of objects: a table whose header repeats on every page, a total, page numbers and the page count, with one HTTP call.
3 min read
Code and integrations
Save a PDF in C#: to disk, as a download or in blob storage
Save the PDF returned by a render call in C#: write it to disk, send it as a download from ASP.NET Core, keep a signed link or upload it, and avoid saving an error.
2 min read
Code and integrations
Generate thousands of PDFs in C#: pacing, 429 and safe retries
Make a batch of PDFs from C# without a wall of 429 errors: pace the calls, retry only what is safe, resume a stopped run and stop when the credits run out.
3 min read