Recursive AI

HTML to PDF

All onepdf-html docs

RecursiveAI.OnePdf.Html.Render converts HTML to a tagged PDF: a string, file, stream or URL in, bytes, a stream or a file out. It is a thin layer over OneRender, which lays the HTML out for print and writes the PDF. This package decides what a document may load and adds what a converter API needs: page size and margins, running headers and footers, link handling, an outline, metadata, and PDF/UA-1 and PDF/A-2a. Everything is in the namespace OnePdf.Html.Render.

It is a separate package from the PDF to HTML converter, so PDF to HTML users do not pull in a layout engine and its fonts.

The happy path: HtmlToPdf

C#
using OnePdf.Html.Render;
 
byte[] pdf = HtmlToPdf.ConvertFile("page.html");                                 // relative CSS, images and fonts load from the file's folder
HtmlToPdfResult written = HtmlToPdf.ConvertFile("page.html", "page.pdf");        // writes the file; nothing is left behind if it fails
byte[] fromString = HtmlToPdf.ConvertHtml("<h1>Hello</h1><p>From a string.</p>");
Console.WriteLine($"{pdf.Length} bytes, {written.PageCount} page(s), {fromString.Length} bytes from a string");

The defaults: A4 with 0.5 inch margins unless the document's @page rule says otherwise, a tagged PDF with bookmarks from the headings, web and in-document links, and no network access except for a URL input. No script runs.

CallWhat it does
ConvertHtml(string html, options, rootDirectory)HTML text to bytes. With a stream: ConvertHtml(html, Stream output, ...) returns a HtmlToPdfResult.
ConvertFile(path, options)A file to bytes. ConvertFile(path, outputPath, options) writes the PDF to a file.
ConvertStream(Stream html, options, rootDirectory)HTML bytes read from a stream to its end (left open), in any encoding a browser would detect.
ConvertUrl(string url, options)Fetches the page over http or https, with the style sheets, images and fonts it refers to.
Convert(HtmlSource source, options), ConvertAsync(...)Any HtmlSource; ConvertAsync runs on a worker thread.
ConvertAll(sources, options), ConvertFiles(paths, outputDirectory, options)Batches, in parallel. See batches.

Every call takes a CancellationToken last. rootDirectory is the folder relative references (style sheets, images, fonts) may read from; null reads no files.

Inputs

HtmlSource names an input:

FactoryInput
HtmlSource.FromHtml(string html, string? rootDirectory = null)HTML text.
HtmlSource.FromBytes(ReadOnlyMemory<byte> html, rootDirectory, contentType)Bytes in any encoding a browser would guess: byte order mark, charset of the content type, or a <meta> tag.
HtmlSource.FromStream(Stream html, rootDirectory, contentType)A stream, read to its end when the conversion runs (left open; a batch must not share one).
HtmlSource.FromFile(string path, string? rootDirectory = null)A file. Its folder is the default root for relative references.
HtmlSource.FromUrl(string), FromUrl(Uri)A page fetched over http or https; it and its resources are read over the network.

Path, RootDirectory and Url give back what a source was made from.

C#
using OnePdf.Html.Render;
 
HtmlSource[] sources =
[
    HtmlSource.FromFile("page.html"),
    HtmlSource.FromHtml("<html lang=\"en\"><title>Inline</title><h1>Inline</h1>"),
    HtmlSource.FromBytes(File.ReadAllBytes("page.html"), rootDirectory: Directory.GetCurrentDirectory()),
];
foreach (HtmlSource source in sources)
{
    byte[] pdf = HtmlToPdf.Convert(source);
    Console.WriteLine($"{source.Path ?? "memory"}: {pdf.Length} bytes");
}
 
using var stream = File.OpenRead("page.html");
byte[] fromStream = HtmlToPdf.ConvertStream(stream, rootDirectory: Directory.GetCurrentDirectory());
Console.WriteLine(fromStream.Length);
C#
using OnePdf.Html.Render;
 
static class Rendering
{
    public static Task<byte[]> RenderAsync(CancellationToken cancellationToken) =>
        HtmlToPdf.ConvertAsync(HtmlSource.FromFile("page.html"), new HtmlToPdfOptions { Title = "Async" }, cancellationToken);
}

Options

HtmlToPdfOptions is immutable (every property is init-only). A property left null defers to the document, then to the default.

PropertyDefaultWhat it does
PageSize, Orientation, Marginsthe document's @page, else A4, portrait, 0.5 inchPages. Once set, they win over the document's @page rule.
Header, FooternoneRunning headers and footers.
LinksWebWhich links are clickable.
Outlineevery heading levelBookmarks from the headings; null for none.
Title, Author, Subject, Keywords, Languagefrom the HTMLMetadata.
CreatorOnePdf.HtmlThe producing application written to the file.
CreationDatenoneThe creation date. The converter never reads the clock.
DocumentIdderived from the titleSixteen bytes for the file's /ID.
ProfileNonePDF/UA-1, PDF/A-2a, or both.
TaggedtrueWrite the tag structure.
CompresstrueCompress the streams.
RasterDpi192Resolution, 24 to 600 pixels per inch, of the images that stand in for what PDF cannot express (blur, some filters, inline SVG).
MaxPages100,000More pages fail with HtmlToPdfFailure.Limit.
ResourcesnoneA callback that supplies a resource by address before the built-in loader runs.
NetworkoffHtmlNetworkOptions.
Limitssee belowHtmlResourceLimits.
Fontsthe packaged fontsAn OneRender IFontProvider.
Layoutthe default engineAn OneRender ILayoutEngine.
MaxDegreeOfParallelism0 (the smaller of 4 and the processor count)The most inputs a batch converts at once.

HtmlToPdfOptions.Default is the instance with every default. Argument mistakes throw ArgumentException or ArgumentOutOfRangeException when a conversion starts.

Pages: size, orientation and margins

Size and margins are CSS pixels (1/96 inch) inside, with factories for the units people use.

  • HtmlPageSize: A3, A4, A5, B5, Letter, Legal, Tabloid; FromMillimeters(w, h), FromInches(w, h), FromPoints(w, h); Landscape() and Portrait() turn a size. Each edge must be 1 to 14,400 px.
  • HtmlPageOrientation: Portrait makes the longer edge the height, Landscape the width.
  • HtmlMargins: None, All(px), FromMillimeters(mm), FromMillimeters(top, right, bottom, left), FromInches(...) and the constructor new HtmlMargins(top, right, bottom, left).

The options are applied as one @page rule appended before the last </body>, so it follows the document's own style sheets and wins over them for the properties you set. A document without options keeps its own @page size and margin.

C#
using OnePdf.Html.Render;
 
var options = new HtmlToPdfOptions
{
    PageSize = HtmlPageSize.FromMillimeters(148, 210),              // A5
    Orientation = HtmlPageOrientation.Landscape,
    Margins = HtmlMargins.FromMillimeters(top: 25, right: 15, bottom: 25, left: 15),
};
HtmlToPdf.ConvertFile("page.html", "a5.pdf", options);
 
var custom = new HtmlToPdfOptions { PageSize = new HtmlPageSize(800, 600), Margins = HtmlMargins.None };
HtmlToPdf.ConvertFile("page.html", "slide.pdf", custom);

Headers and footers

HtmlHeaderFooter is up to three templates, one per position (Left, Center, Right) in the top or bottom margin. The margin must be tall enough to hold it (see Margins). A template is an HTML fragment of text; these classes stand for values that change:

ClassValue
pageNumberThe page's number.
totalPagesThe page count.
titleThe document title.
dateHtmlHeaderFooter.Date, or nothing when you give none (the clock is never read).

Style holds CSS declarations for the text (default font-size: 9pt; color: #555; it must not contain <). HtmlHeaderFooter.PageXOfY() is the centred footer "Page 3 of 12" and Centered(text) puts one template in the middle. A template may have at most HtmlHeaderFooter.MaxTemplateLength (2,048) characters.

A template that holds more than text (an image, a table, a link, or an element with its own class, style or id) is drawn as HTML in its margin box. Html is one such template across the whole page area, for a logo with a title beside it or a two-column footer; it replaces Left, Center and Right, which must then be null, and may have at most MaxHtmlLength (65,536) characters. Scripts, style elements, iframes and event attributes in a template are dropped, and its images load through the same rules as the document's.

C#
using OnePdf.Html.Render;
 
var options = new HtmlToPdfOptions
{
    Margins = HtmlMargins.FromMillimeters(25),
    Header = new HtmlHeaderFooter { Left = "Quarterly report", Right = "<span class=\"title\"></span>", Style = "font: 9pt sans-serif; color: #444" },
    Footer = new HtmlHeaderFooter
    {
        Left = "Printed <span class=\"date\"></span>",
        Date = "2026-01-31",
        Right = "Page <span class=\"pageNumber\"></span> of <span class=\"totalPages\"></span>",
    },
};
HtmlToPdf.ConvertFile("page.html", "with-header.pdf", options);
 
var branded = new HtmlToPdfOptions
{
    Margins = new HtmlMargins(top: 90, right: 72, bottom: 72, left: 72),
    Header = new HtmlHeaderFooter { Html = "<div style=\"display:flex;justify-content:space-between\"><b>Acme</b><span class=\"title\"></span></div>" },
    Footer = HtmlHeaderFooter.PageXOfY(),
};
HtmlToPdf.ConvertFile("page.html", "branded.pdf", branded);
  • Links (HtmlLinkPolicy): Web (the default) keeps http, https, mailto and tel links and links to anchors inside the document, and drops other schemes (javascript:, file:, data:) and relative references. InternalOnly keeps only in-document anchors. All keeps every link: a link is only data in a PDF, but a viewer may act on it. None makes no links; the link text is still marked as a link in the tag structure.
  • Outline (HtmlOutlineOptions): bookmarks from the rendered h1 to h6, in document order, nested by level, each going to where the heading starts. MinLevel (1) and MaxLevel (6) pick the levels, MaxEntries (10,000) bounds the count. Null writes no outline.
  • Metadata: Title, Author, Subject, Keywords and Language default to the HTML's <title>, <meta name="author">, description, keywords and the root element's lang. Creator is the producer string. CreationDate is written only when you set it.
  • Tagged: the tag structure (headings, lists, tables with header cells, figures with alternate text, links) that makes the file accessible. Leave it on for accessibility; PDF/UA and PDF/A level A need it.
C#
using OnePdf.Html.Render;
 
var options = new HtmlToPdfOptions
{
    Links = HtmlLinkPolicy.InternalOnly,
    Outline = new HtmlOutlineOptions { MinLevel = 1, MaxLevel = 3 },
    Title = "Quarterly report",
    Author = "Finance",
    Subject = "Results",
    Keywords = "quarterly, results",
    Language = "en-US",
    CreationDate = new DateTimeOffset(2026, 1, 31, 12, 0, 0, TimeSpan.Zero),
    Compress = false,
};
HtmlToPdf.ConvertFile("page.html", "metadata.pdf", options);
HtmlToPdf.ConvertFile("page.html", "plain.pdf", new HtmlToPdfOptions { Outline = null, Tagged = false, Links = HtmlLinkPolicy.None });

PDF/UA and PDF/A

Profile (HtmlPdfProfile) identifies the file and checks it:

ValueMeaning
NoneA tagged PDF, not identified as PDF/UA or PDF/A. Written as a stream, so memory does not grow with the page count.
PdfUA1PDF/UA-1 (ISO 14289-1). Needs a title and a language; fails with HtmlToPdfFailure.ProfileViolation if a rule is broken. Built in memory.
PdfA2aPDF/A-2a (ISO 19005-2, level A). Needs a title and a language. Built in memory.
PdfA2aAndUA1Both in one file. Built in memory.

The failure message lists the rules that were broken. Both profiles need Tagged = true.

C#
using OnePdf.Html.Render;
 
var options = new HtmlToPdfOptions { Profile = HtmlPdfProfile.PdfA2aAndUA1, Title = "Report", Language = "en" };
HtmlToPdf.ConvertFile("page.html", "archive.pdf", options);

Resources, files and the network

Reading the input's style sheets, images and fonts is the part of conversion that touches the outside world, so it is the part with rules. The renderer never fetches; it asks the loader for each address.

  1. Resources (a Func<string, byte[]?>) is asked first, with the absolute address. Return the bytes, or null to let the built-in loader try.
  2. Files. A file: or relative address must lie below the input's folder (or the rootDirectory you gave) after .. is resolved and links are followed. ../, absolute paths and links that point out are refused with a diagnostic.
  3. The network. http and https addresses are fetched only when the input is a URL or HtmlNetworkOptions.Enabled is set. Only http and https are ever used.

HtmlNetworkOptions:

PropertyDefaultWhat it does
EnabledfalseAllow fetching resources over the network for file, string and stream input. A URL input always fetches.
AllowPrivateAddressesfalseAllow loopback, link-local, private-range and other non-public addresses.
RequestTimeout15 sThe longest one request may take.
TotalTimeout60 sThe longest all requests of one conversion may take together.
MaxRedirects5Redirects followed for one resource; each hop is checked again.
UserAgentOnePdf.HtmlThe User-Agent header.

The address is checked on the connection that is actually made, so a name that changes its answer between lookups gains nothing. The one exception to the private-address rule is the host and port of a URL you named as the input, which are trusted, so a local test server can be converted.

HtmlResourceLimits bounds what one conversion reads: MaxInputBytes (64 MiB), MaxResourceBytes (32 MiB per resource), MaxTotalBytes (256 MiB for all resources) and MaxResources (500). A resource over a limit is skipped with a resource-limit warning; an input over MaxInputBytes fails with HtmlToPdfFailure.Input.

C#
using OnePdf.Html.Render;
 
var offline = new HtmlToPdfOptions
{
    Resources = address => address.EndsWith("/logo.png", StringComparison.Ordinal) ? File.ReadAllBytes("page.html") : null,
    Limits = new HtmlResourceLimits { MaxResourceBytes = 8L << 20, MaxResources = 100 },
};
byte[] withHook = HtmlToPdf.ConvertFile("page.html", offline);
Console.WriteLine(withHook.Length);
C#
using OnePdf.Html.Render;
 
var online = new HtmlToPdfOptions
{
    Network = new HtmlNetworkOptions { Enabled = true, RequestTimeout = TimeSpan.FromSeconds(10), MaxRedirects = 3 },
};
byte[] withImages = HtmlToPdf.ConvertFile("page.html", online);                    // its https images and style sheets are fetched
byte[] fromUrl = HtmlToPdf.ConvertUrl("https://example.org/page.html", online);    // the page and its resources are fetched
Console.WriteLine(withImages.Length + fromUrl.Length);

Batches

ConvertFiles(paths, outputDirectory, options) converts HTML files in parallel, each to a PDF of the same name with the extension .pdf in the directory (created if needed). Two inputs that would give the same name get -2, -3 and so on in input order. ConvertAll(sources, options) does the same for any sources and returns the bytes. In both, each PDF is the same bytes the input gives converted alone, an input that fails is reported in its item and does not stop the others, and MaxDegreeOfParallelism bounds the parallelism. Cancelling throws OperationCanceledException.

C#
using OnePdf.Html.Render;
 
string[] files = ["page.html", "page.html"];
IReadOnlyList<HtmlToPdfBatchItem> batch = HtmlToPdf.ConvertFiles(files, "out", new HtmlToPdfOptions { MaxDegreeOfParallelism = 2 });
foreach (HtmlToPdfBatchItem item in batch)
{
    Console.WriteLine(item.Succeeded
        ? $"{item.InputPath} -> {item.OutputPath}: {item.Result!.PageCount} page(s)"
        : $"{item.InputPath} failed: {item.Error!.Message}");
}
 
IReadOnlyList<HtmlToPdfBatchItem> inMemory = HtmlToPdf.ConvertAll([HtmlSource.FromHtml("<h1>One</h1>"), HtmlSource.FromHtml("<h1>Two</h1>")]);
byte[] second = inMemory[1].Result!.Bytes!;
Console.WriteLine(second.Length);

A HtmlToPdfBatchItem has Index, InputPath and OutputPath (file batches), Result, Error and Succeeded.

The low level: HtmlToPdfConverter

HtmlToPdfConverter converts one HtmlSource at a time with full options and holds no state between calls, so one instance can serve many conversions and each equals its one-by-one result. It writes to a stream (left open), a file (under a temporary name and moved into place when complete, so a failure leaves nothing behind) or memory.

C#
using OnePdf.Html.Render;
 
var converter = new HtmlToPdfConverter(new HtmlToPdfOptions { Profile = HtmlPdfProfile.PdfUA1, Title = "Converted", Language = "en" });
using var output = File.Create("stream.pdf");
HtmlToPdfResult result = converter.Convert(HtmlSource.FromFile("page.html"), output);
Console.WriteLine($"{result.Title}: {result.PageCount} page(s)");
HtmlToPdfResult inMemory = converter.Convert(HtmlSource.FromFile("page.html"));
HtmlToPdfResult toFile = converter.Convert(HtmlSource.FromFile("page.html"), "converted.pdf");
Console.WriteLine($"{inMemory.Bytes!.Length} {toFile.Diagnostics.Count} {converter.Options.Profile}");

ConvertAsync has the stream and the bytes forms.

Results, diagnostics and errors

HtmlToPdfResult has PageCount, Title (null when there is none), Bytes (the PDF for the methods that return bytes; null when the output went to a stream or file) and Diagnostics. A HtmlToPdfDiagnostic is a Severity (Info: nothing was lost; Warning: something was left out or approximated), a stable Code and a Message.

CodeWhen
resource-refusedA resource was not loaded by rule: outside the input's folder, a scheme that is never fetched, the network is off, a non-public address, a relative reference with no folder to resolve against.
resource-missingA file could not be read or a network resource did not answer.
resource-limitA resource, or the number or total size of resources, passed a limit in Limits.
render-...The renderer approximated something (for example, drew a feature as an image). The text after render- names the kind.

A conversion that cannot produce a PDF throws HtmlToPdfException; Failure says why:

HtmlToPdfFailureMeaning
InputThe input could not be read or is over Limits.MaxInputBytes.
NetworkThe input URL itself could not be fetched. Other resources are skipped with a diagnostic.
LimitThe document is too large or too deep for a limit: pages, nodes or output size.
ProfileViolationThe file would break a rule of the requested profile (PDF/UA-1 or PDF/A-2a), for example a missing title or language. The message lists the rules.
RenderThe renderer could not write the file for another reason.

Argument mistakes throw ArgumentException; cancellation throws OperationCanceledException.

C#
using OnePdf.Html.Render;
 
try
{
    HtmlToPdf.ConvertHtml("<p>No title and no language</p>", new HtmlToPdfOptions { Profile = HtmlPdfProfile.PdfUA1 });
}
catch (HtmlToPdfException e) when (e.Failure == HtmlToPdfFailure.ProfileViolation)
{
    Console.WriteLine($"Not accessible: {e.Message}");
}
catch (HtmlToPdfException e)
{
    Console.WriteLine($"{e.Failure}: {e.Message}");
}

Determinism

The same input and options give the same bytes: no clock is read, so a creation date is written only if you set CreationDate; the file's /ID is derived from the title unless you set DocumentId; and a batch result equals the one-by-one result. A date in a header or footer is whatever you put in HtmlHeaderFooter.Date.

Type index

TypeWhere
HtmlToPdf, HtmlToPdfBatchItemHappy path, batches
HtmlSourceInputs
HtmlToPdfConverterThe low level
HtmlToPdfOptionsOptions
HtmlPageSize, HtmlMargins, HtmlPageOrientationPages
HtmlHeaderFooterHeaders and footers
HtmlLinkPolicy, HtmlOutlineOptionsLinks, outline, metadata and tags
HtmlPdfProfilePDF/UA and PDF/A
HtmlNetworkOptions, HtmlResourceLimitsResources
HtmlToPdfResult, HtmlToPdfDiagnostic, HtmlToPdfSeverity, HtmlToPdfException, HtmlToPdfFailureResults

The command line is in cli.md; the reverse direction in pdf-to-html.md.