# onepdf-html docs, all pages (OnePdf.Html 1.0.0) Every page of https://recursiveai.org/onepdf-html/docs/ as markdown, getting started first. Index: https://recursiveai.org/onepdf-html/llms.txt # Getting started with OnePdf.Html Install OnePdf.Html for .NET 10, turn an HTML page into a tagged PDF/UA-1 file, turn that PDF back into reflowing HTML and into fixed-layout HTML, read a scanned page with OCR, and do the same from the command line. ## Install OnePdf.Html targets `net10.0`, so you need the .NET 10 SDK. The four packages share one version; this guide uses 1.0.0. ```shell dotnet new console -o PdfHtmlStart cd PdfHtmlStart dotnet add package RecursiveAI.OnePdf.Html.Render --version 1.0.0 dotnet add package RecursiveAI.OnePdf.Html --version 1.0.0 dotnet add package RecursiveAI.OnePdf.Html.Ocr --version 1.0.0 ``` `RecursiveAI.OnePdf.Html` converts PDF to HTML. `RecursiveAI.OnePdf.Html.Render` converts HTML to PDF; it is a separate package so that PDF to HTML users don’t get a layout engine and its fonts. `RecursiveAI.OnePdf.Html.Ocr` is only needed for scanned pages. All three are managed code with no native libraries. ## The sample files `report.html` is a one-page library report with headings, a list, a table and a link. `scan-article.pdf` is a picture of a page with no text layer: a scan. Download both into the project folder: ```shell curl -O https://recursiveai.org/onepdf-html/samples/report.html curl -O https://recursiveai.org/onepdf-html/samples/scan-article.pdf ``` ## HTML to PDF `HtmlToPdf.ConvertFile` reads the HTML file, loads its CSS, images and fonts from the file’s folder, and writes a tagged PDF. `HtmlPdfProfile.PdfUA1` makes it a PDF/UA-1 file and checks it: the conversion fails if a rule is broken. PDF/UA-1 needs a title and a language, which come from the page’s `` and `<html lang>`. ```csharp using OnePdf.Html.Render; var options = new HtmlToPdfOptions { Profile = HtmlPdfProfile.PdfUA1, Footer = HtmlHeaderFooter.PageXOfY(), // "Page 1 of 1" }; HtmlToPdfResult result = HtmlToPdf.ConvertFile("report.html", "report.pdf", options); Console.WriteLine($"{result.PageCount} page, title: {result.Title}"); Console.WriteLine($"{result.Diagnostics.Count} diagnostics, {new FileInfo("report.pdf").Length:N0} bytes"); ``` ```text 1 page, title: Harbor Street Library: October report 0 diagnostics, 23,061 bytes ``` The result is [report.pdf](https://recursiveai.org/onepdf-html/samples/report.pdf). `HtmlPdfProfile.PdfA2a` writes PDF/A-2a instead, and `PdfA2aAndUA1` writes both in one file. Page size, margins, headers and footers, and URLs as input are in the [HTML to PDF guide](https://recursiveai.org/onepdf-html/docs/html-to-pdf/). ## PDF to HTML: semantic `PdfHtml.Convert` with no options writes semantic HTML: reflowing text in reading order. `report.pdf` is tagged, so the headings, list and table come from its tags. ```csharp using System.Text.RegularExpressions; using OnePdf.Html; string html = PdfHtml.Convert("report.pdf"); string main = html[html.IndexOf("<main>")..]; Console.WriteLine(Regex.Replace(main, "(?=<(h[1-6]|p|li|tr)[ >])", "\n")); // a line per block ``` ```html <main> <span id="page-1" class="page-marker" role="doc-pagebreak" aria-label="Page 1"></span> <h1><span class="wf1">October report</span></h1> <p><span class="wf0">Harbor Street Library, branch services</span></p> <h2><span class="wf1">Summary</span></h2> <p><span class="wf0">Visits rose for the third month in a row. The reading room reopened on October 6 after the roof repair, and the new self-checkout desks handled more than half of all loans.</span></p> <h2><span class="wf1">Highlights</span></h2><ul> <li><span class="wf0">Story time moved to Saturday mornings.</span></li> <li><span class="wf0">Twelve volunteers joined the homework club.</span></li> <li><span class="wf0">The local history archive is now open on Tuesdays.</span></li></ul> <h2><span class="wf1">Loans by collection</span></h2><table><thead> <tr><th scope="col"><span class="wf1">Collection</span></th><th scope="col"><span class="wf1">September</span></th><th scope="col"><span class="wf1">October</span></th></tr></thead><tbody> <tr><td><span class="wf0">Fiction</span></td><td><span class="wf0">4,210</span></td><td><span class="wf0">4,580</span></td></tr> <tr><td><span class="wf0">Nonfiction</span></td><td><span class="wf0">2,975</span></td><td><span class="wf0">3,120</span></td></tr> <tr><td><span class="wf0">Children</span></td><td><span class="wf0">3,340</span></td><td><span class="wf0">3,615</span></td></tr></tbody></table> <p><span class="wf0">The full figures are on the</span> <a href="https://example.org/library/reports" rel="noopener noreferrer"><span class="wf0">reports page.</span></a></p> </main></body></html> ``` The `wf0` and `wf1` classes set the PDF’s two fonts, written once in the document’s head as WOFF2 subsets; `Fonts = PdfHtmlFontMode.CssFamilies` writes no fonts and leaves the text to the reader’s. The “Page 1 of 1” footer isn’t there: the PDF marks it as page furniture, and tagged artifacts are dropped. The link keeps its `https` target with `rel="noopener noreferrer"`. In Chrome, [report-semantic.html](https://recursiveai.org/onepdf-html/samples/report-semantic.html) looks like this: ![report-semantic.html in Chrome: the heading “October report”, three section headings, a bulleted list of three items, a three-column table of loans and a linked “reports page”, as reflowing text](https://recursiveai.org/onepdf-html/samples/report-semantic.png) ## PDF to HTML: fixed layout `PdfHtmlMode.FixedLayout` writes each page as a box the size of the page, with the text positioned and selectable in the PDF’s own glyph shapes. The path overload writes the file and returns the page count and diagnostics: ```csharp using OnePdf.Html; PdfHtmlResult result = PdfHtml.Convert("report.pdf", "report-fixed.html", new PdfHtmlOptions { Mode = PdfHtmlMode.FixedLayout }); Console.WriteLine($"{result.PageCount} page, {result.Diagnostics.Count} diagnostics"); Console.WriteLine($"report-fixed.html: {new FileInfo("report-fixed.html").Length:N0} bytes"); ``` ```text 1 page, 0 diagnostics report-fixed.html: 21,959 bytes ``` [report-fixed.html](https://recursiveai.org/onepdf-html/samples/report-fixed.html) in Chrome, with the footer where the PDF draws it: ![report-fixed.html in Chrome: one A4 page on a grey background, with the report’s headings, list, a ruled table with right-aligned numbers, and “Page 1 of 1” at the foot of the page](https://recursiveai.org/onepdf-html/samples/report-fixed.png) ## Scanned pages `scan-article.pdf` has no text, only a picture of it. `OcrTextSource` from `RecursiveAI.OnePdf.Html.Ocr` recognizes text on such pages. In `OcrMode.Auto`, the default, it reads only the pages whose own text is missing or can’t be trusted. The models load the first time a page needs them; there is nothing to download. ```csharp using System.Text.RegularExpressions; using OnePdf.Html; using OnePdf.Html.Ocr; using var ocr = new OcrTextSource(new OcrTextSourceOptions { Mode = OcrMode.Auto, Languages = ["en"] }); PdfHtmlResult result = PdfHtml.Convert("scan-article.pdf", "scan-article.html", new PdfHtmlOptions { TextSource = ocr }); foreach (PdfHtmlDiagnostic d in result.Diagnostics) Console.WriteLine(d); string html = File.ReadAllText("scan-article.html"); string main = html[html.IndexOf("<main>")..]; Console.WriteLine(Regex.Replace(main, "(?=<(h[1-6]|p|li|tr)[ >])", "\n")); // a line per block ``` ```text Info: 89 words recognised from a 300 dpi picture (the page has no text layer over a picture with ink on it) [ocr-page] (page 1) <main> <span id="page-1" class="page-marker" role="doc-pagebreak" aria-label="Page 1"></span> <h1>The harbour</h1> <p>Harbour tides follow the moon, and the old pilots kept their own tables of high and low water. See the tide tables for this month.</p> <h1>Early records</h1> <p>Every spring the orchard behind the mill drops its blossom on the water, and the children race paper boats down the race.</p> <h2>Later records</h2> <p>The ledger shows a small surplus in the third quarter, mostly from repairs that were postponed rather than avoided.</p> <p>Notes on method</p> <p>Counts were made by hand each evening and checked against the harbour office log.</p> </main></body></html> ``` All 89 words match the text of the page the scan was made from. With no text layer there are no tags, so the headings come from the size of the type. The package reads Latin, Greek and Cyrillic. For Chinese, Japanese, Korean, Arabic, Hebrew or the Indic languages, add `RecursiveAI.OneOcr.Models.Cjk`, `.Arabic`, `.Hebrew` or `.Indic`; no code changes. ## The command line The `onepdf-html` tool converts in both directions: ```shell dotnet tool install -g RecursiveAI.OnePdf.Html.Tool ``` ```text You can invoke the tool using the following command: onepdf-html Tool 'recursiveai.onepdf.html.tool' (version '1.0.0') was successfully installed. ``` On linux-x64, linux-arm64, osx-arm64 and win-x64 it installs as a native executable; elsewhere it installs a framework-dependent build. You don’t name the platform: `dotnet tool install` picks the package. The direction follows the input, so an HTML file becomes a PDF and a PDF becomes HTML: ```shell onepdf-html report.html -o report.pdf --page-numbers --profile ua1 onepdf-html report.pdf -o report-semantic.html onepdf-html report.pdf --mode fixed -o report-fixed.html onepdf-html scan-article.pdf --ocr auto -o scan-article.html ``` ```text onepdf-html: wrote 1 page(s) to report.pdf onepdf-html: wrote 1 page(s) to report-semantic.html onepdf-html: wrote 1 page(s) to report-fixed.html onepdf-html: wrote 1 page(s) to scan-article.html ``` The four files are byte-identical to the ones the programs above wrote. Without `-o`, a PDF becomes `<input>.html` beside it, so `onepdf-html report.pdf` here would replace `report.html`. `-v` lists every diagnostic. Every option is in the [command-line reference](https://recursiveai.org/onepdf-html/docs/cli/). ## Next - [PDF to HTML](https://recursiveai.org/onepdf-html/docs/pdf-to-html/): every option, the semantic mapping, fixed-layout output, files per page, sinks, text sources and OCR. - [HTML to PDF](https://recursiveai.org/onepdf-html/docs/html-to-pdf/): page size, margins, headers and footers, URLs, resources and the network, PDF/A, batches. - [Diagnostics and limits](https://recursiveai.org/onepdf-html/docs/diagnostics/): every diagnostic code and the bounds on untrusted input. <!-- https://recursiveai.org/onepdf-html/docs/overview/ --> # OnePdf.Html Convert between PDF and HTML in .NET, in both directions. - **PDF to HTML, two ways.** *Semantic* output is clean, reflowing HTML in reading order: headings, paragraphs, lists, tables, figures, links and notes, built from the PDF's tags or inferred from its layout. *Fixed-layout* output looks like the page: positioned, selectable text in the PDF's own glyph shapes over vector graphics and images, one box per page. - **HTML to PDF.** A string, file, stream or URL in, a tagged PDF out, with page size, margins, headers and footers, links, an outline, and PDF/UA-1 or PDF/A-2a. - **Scanned pages.** An optional OCR package recognises text on scans and on pages whose text layer is broken, in both PDF to HTML modes. Pure managed code on [OnePDF](https://github.com/recursive-ai-oss/onepdf-csharp), [OneImage](https://github.com/recursive-ai-oss/oneimage-csharp), [OneHtml](https://github.com/recursive-ai-oss/onehtml-csharp) and [OneRender](https://github.com/recursive-ai-oss/onerender-csharp). `net10.0`, NativeAOT- and trim-compatible, no native libraries, no script and no network use unless you ask for it. ## Install Command line (a native executable for linux-x64, linux-arm64, osx-arm64 and win-x64, so a short document converts in tens of milliseconds; a framework-dependent build for every other platform): ``` dotnet tool install -g RecursiveAI.OnePdf.Html.Tool ``` Libraries: ``` dotnet add package RecursiveAI.OnePdf.Html # PDF to HTML dotnet add package RecursiveAI.OnePdf.Html.Ocr # optional: recognise text on scanned pages (Latin, Greek, Cyrillic) dotnet add package RecursiveAI.OneOcr.Models.Cjk # optional: also Chinese, Japanese, Korean (.Arabic, .Hebrew, .Indic likewise) dotnet add package RecursiveAI.OnePdf.Html.Render # HTML to PDF ``` | Package | What it is | Pulls in | |---|---|---| | `RecursiveAI.OnePdf.Html` | The PDF to HTML converter. | OnePdf, OnePdf.Fonts, OneFont, OneImage, OneImage.Pdf, OneHtml | | `RecursiveAI.OnePdf.Html.Ocr` | A text source that recognises text on scanned pages and on pages with a broken text layer. | OnePdf.Html, OneOcr (and its models, which carry the model weights) | | `RecursiveAI.OnePdf.Html.Render` | HTML to PDF. A separate package, so PDF to HTML users do not get a layout engine and its fonts. | OneRender.Pdf (OneRender, its image back end and OFL fonts), OneHtml | | `RecursiveAI.OnePdf.Html.Tool` | The `onepdf-html` command, both directions. | The three packages above | All four share one version. [THIRD-PARTY-NOTICES.md](https://github.com/recursive-ai-oss/onepdf-html-csharp/blob/166c1177813f222de669a1f456eeb495b18e6103/THIRD-PARTY-NOTICES.md) lists what ships inside them. ## PDF to HTML in a minute ```csharp using OnePdf.Html; string html = PdfHtml.Convert("report.pdf"); // reflowing HTML, as text PdfHtml.Convert("report.pdf", "fixed.html", // fixed-layout pages, one file new PdfHtmlOptions { Mode = PdfHtmlMode.FixedLayout }); PdfHtml.Convert("report.pdf", "pages", // a file per page, images and fonts as files new PdfHtmlOptions { Layout = PdfHtmlOutputLayout.PagePerFile, Assets = PdfHtmlAssetMode.Files, PageRanges = PdfHtmlPageRanges.Parse("1-2") }); ``` Per-page control and your own output go through `PdfHtmlConverter`: ```csharp using OnePdf.Html; using PdfHtmlConverter converter = PdfHtmlConverter.Open("report.pdf", new PdfHtmlOptions { Password = "secret" }); PdfHtmlPage page = converter.ConvertPage(0); // one page: HTML fragment, assets, diagnostics using var sink = new PdfHtmlFileSink("whole.html"); converter.ConvertTo(sink); // any IPdfHtmlSink; pages arrive in order foreach (PdfHtmlDiagnostic d in converter.Diagnostics) { Console.WriteLine(d); // repairs and dropped content } ``` The guide, [docs/pdf-to-html.md](https://recursiveai.org/onepdf-html/docs/pdf-to-html/), covers every option, the semantic mapping, fixed-layout output, sinks, text sources and OCR. ## HTML to PDF in a minute ```csharp using OnePdf.Html.Render; byte[] pdf = HtmlToPdf.ConvertFile("page.html"); // relative CSS, images and fonts load from the file's folder HtmlToPdf.ConvertFile("page.html", "letter.pdf", new HtmlToPdfOptions { PageSize = HtmlPageSize.Letter, Orientation = HtmlPageOrientation.Landscape, Margins = HtmlMargins.FromMillimeters(20), Header = new HtmlHeaderFooter { Left = "Quarterly report", Right = "<span class=\"title\"></span>" }, Footer = HtmlHeaderFooter.PageXOfY(), // "Page 3 of 12" on every page Profile = HtmlPdfProfile.PdfA2aAndUA1, // PDF/A-2a and PDF/UA-1 in one file }); ``` `HtmlToPdf.ConvertUrl` fetches a page and its resources, `ConvertFiles` and `ConvertAll` run batches in parallel, and `HtmlToPdfConverter` is the low level. The guide, [docs/html-to-pdf.md](https://recursiveai.org/onepdf-html/docs/html-to-pdf/), covers every option. ## Command line ``` onepdf-html report.pdf # report.html beside the input (reflowing) onepdf-html report.pdf --mode fixed -o fixed.html onepdf-html report.pdf --per-page --assets files --pages 1-5 onepdf-html scan.pdf --ocr auto # recognise text where a page has none onepdf-html page.html # page.pdf beside the input onepdf-html https://example.org/ -o page.pdf --page-size A4 --landscape --page-numbers --profile ua1 onepdf-html a.html b.html -o out/ # several files in parallel cat page.html | onepdf-html - -o page.pdf ``` The direction follows the input: a PDF becomes HTML; an HTML file, a URL or standard input becomes a PDF. Every option is in [docs/cli.md](https://recursiveai.org/onepdf-html/docs/cli/). ## The two PDF to HTML modes | | Semantic (default) | Fixed layout | |---|---|---| | Use it for | Reading, search, accessibility, content extraction, republishing | Looking like the PDF in a browser | | Output | `h1`..`h6`, `p`, `ul`/`ol`, `table`, `figure`, `aside`, links; in reading order | One box per page: SVG vector graphics, images, selectable text in positioned, transformed lines | | Structure from | The tag tree of a tagged PDF; otherwise inferred (headings from the outline and type sizes, hanging-indent lists, ruled and unruled tables, footnotes, captions) | Not applicable; the text is the extraction's text, so copying a selection gives the page's text | | Fonts | The reader's own, or the PDF's glyph shapes as WOFF2 subsets built once per document (`Fonts`, default web fonts) | The PDF's glyph shapes as WOFF2 subsets, or CSS families chosen from the font name | | What cannot be expressed | Vector figures become pictures cut from the page | Mesh and function shadings, a few pattern forms and some masks come from a page picture, always reported in a diagnostic | Tagged and untagged pages, partly tagged pages, headers and footers (marked, kept or dropped), page boundaries (markers or sections), form fields (text or controls), annotations and right-to-left text are described in the guide. ## Safe by construction PDF files are untrusted input, and HTML is executable in a browser, so the output is built to be inert: - It never contains script and never refers to a remote resource. Nothing is fetched. - Every piece of text and every attribute value goes through one serialiser (OneHtml's), which escapes it. No markup is built by concatenating document text. - Only `http`, `https`, `mailto` and in-document link targets are kept. `javascript:`, `file:`, `data:` and the rest are dropped with a diagnostic, and PDF JavaScript and actions are never converted. - Parsing and output are bounded: OnePDF's `PdfLimits` plus `MaxInputBytes`, `MaxOutputBytesPerPage`, `MaxAssetsPerPage` and `MaxRasterPixels`. - The same input and options give byte-identical output at any degree of parallelism. HTML to PDF runs no script either. A document reads files only below its input's folder, and reads the network only when the input is a URL or you turn it on, with `http`/`https` only, size, count, time and redirect limits, and loopback, link-local and private addresses refused unless you allow them. ## Comparison with pdf2htmlEX [pdf2htmlEX](https://github.com/pdf2htmlEX/pdf2htmlEX) is a native command-line program that makes fixed-layout HTML; OnePdf.Html is a managed library (and tool) with two output modes and the reverse direction. The measured comparison is made with the harness in `tools/OnePdf.Html.Eval`, which runs both converters as external commands on the same pages: Chrome opens each converter's HTML, and the result is compared with the OneImage.Pdf render of the page (visual similarity), with the text OnePDF extracts (text equality), and by output size and conversion time. Fixed layout, 100 pages of the 62 files in `testdata/eval/fixed.csv` (13 categories: text, multi-column, tables and math, forms, images, vector maps, transparency, Type 3, CJK, right-to-left, rotated, scans with a text layer, repaired broken files): | Quality (harness session) | OnePdf.Html | pdf2htmlEX | |---|---:|---:| | Visual similarity to the page render (SSIM, mean of pages; higher is better) | 0.980 | 0.887 | | Ink that differs from the render, % (lower is better) | 1.4 | 26.1 | | Text content error, % against the page's text (lower is better) | 0.4 | 9.9 | | Reading-order error, % (lower is better) | 0.7 | 18.5 | | HTML per page, KiB (total bytes over total pages) | 41 | 147 | | Speed (bench session) | OnePdf.Html | pdf2htmlEX | |---|---:|---:| | Conversion time, ms per page, median of the 62 files (mean in brackets) | 15 (30) | 80 (113) | | Peak memory of one conversion, MiB, median of the files (largest) | 36 (137) | 32 (59) | The memory row is not a win: pdf2htmlEX's resident set is a little smaller, because OnePdf.Html draws a page picture for anything a browser cannot express and holds it while the page is converted. **Method.** Quality: `tools/OnePdf.Html.Eval fixed` on the set above, one full session shortly before the release candidate (the fixed-layout code differs from the release only by the picture-piece limit and the glyph-width and code-point guards listed in the changelog, which touch no page of the set except by the rows they are written for), on a Ryzen 9 7950X3D machine (Linux 7.0), Chrome 155.0.8059.84 headless, the NativeAOT `onepdf-html` tool, pdf2htmlEX 0.18.8.rc1 with its default flags (`--dest-dir`, no other options). Each page is rendered by Chrome from each converter's HTML and compared with the OneImage.Pdf render of the page at 96 dpi (SSIM and ink mismatch); the text is compared with OnePDF's extraction of the page. The quality session ran with other jobs on the machine, so its times are not published. Speed: one process per file, the pages the set lists (the whole file where it says all), converting from a file to a file, three repetitions, the median of the repetitions per file; wall time from `/usr/bin/time` and peak resident set (`%M`) of the process, run alone on the machine (a `bench` lease on a 16-core, 32-thread machine; load average 3 to 5 from the machine's idle services before, during and after). Process start-up is included in both, which favours a native tool. The speed rows come from `tools/OnePdf.Html.Eval/scripts/speed.sh` and `speed-summary.py`. One file (`raw-broken-truncated-tail.pdf`) gives pdf2htmlEX no output and is left out of its rows. Numbers from one machine and one session are indicative of the ratio, not of any other machine. Semantic output has no counterpart in pdf2htmlEX, so it is judged on its own: structure accuracy against tagged PDFs (tags hidden for the untagged run) and reading order against OnePDF's extraction. Semantic results on the 54 files of `testdata/eval/semantic.csv` (generated documents with exact truth, and real producers' tagged files with the tags removed before conversion), 7,415 truth items; F1 % per kind, higher is better: | Kind | Truth items | F1 | |---|---:|---:| | Heading (with level) | 171 | 74.8 | | Paragraph | 836 | 80.8 | | List | 72 | 66.2 | | List item | 198 | 79.9 | | Table | 97 | 85.9 | | Table cell (position, spans, header) | 5,861 | 77.7 | | Figure | 155 | 72.5 | | Caption | 6 | 70.6 | | Link | 17 | 97.1 | | Note | 2 | 100.0 | | All kinds | 7,415 | 77.9 | The generated documents and the ruled, partly ruled, unruled, continued and beside-text table sets score 100.0; the real producers' files carry the loss (slides 69.5, tables 55.5, rotated pages 50.5). Reading order against the truth text (content error / order error, lower is better): 3.2 % / 4.4 % overall, 0.0 / 0.0 on the generated documents. Figure alt text is not recovered from untagged files (0 of 8). One session on the machine of the table above, with other jobs running (load 14 on a 16-core machine), so no time is published for it. ## Limits of this version - Text on a PDF page is converted as the PDF's text layer says. Without OCR, a scan stays a picture of text. - OCR reads Latin, Greek and Cyrillic script, and Chinese, Japanese, Korean, Arabic, Persian, Urdu, Hebrew and nine Indic languages once the matching `RecursiveAI.OneOcr.Models.*` package is added ([measured](https://recursiveai.org/onepdf-html/docs/pdf-to-html/#the-ocr-package): scanned CJK pages 0.4 % text error, Arabic and Hebrew 2.9 %). Other scripts, such as Thai, are left unread. - In semantic output, a figure drawn with paths becomes a picture that includes any text inside its area (kept as hidden text for search and screen readers). - Fixed layout does not simulate overprint, does not apply a shading pattern's graphics state, and draws a knockout group that holds transparent content from a page picture. Meshes and function shadings, some patterns and some masks also come from a page picture. Each case is a diagnostic. - Table detection in untagged files is heuristic: it refuses charts, prose columns and line-number grids on purpose, and a ruled form can still be taken for a table. - HTML to PDF follows what OneRender supports of CSS for print; the document's own `@page` rules apply unless you set the options. See [docs/diagnostics.md](https://recursiveai.org/onepdf-html/docs/diagnostics/) for how each case is reported and [docs/architecture.md](https://recursiveai.org/onepdf-html/docs/architecture/) for how the converter is built. ## Documentation - [PDF to HTML guide](https://recursiveai.org/onepdf-html/docs/pdf-to-html/) - [HTML to PDF guide](https://recursiveai.org/onepdf-html/docs/html-to-pdf/) - [Command-line reference](https://recursiveai.org/onepdf-html/docs/cli/) - [Diagnostics and limits](https://recursiveai.org/onepdf-html/docs/diagnostics/) - [Architecture](https://recursiveai.org/onepdf-html/docs/architecture/) (for maintainers) - [Changelog](https://recursiveai.org/onepdf-html/docs/changelog/) Every code sample in the README and the guides is compiled and run by `tests/OnePdf.Html.Docs.Tests`. ## Build ``` dotnet build OnePdf.Html.slnx dotnet test --solution OnePdf.Html.slnx dotnet publish tests/OnePdf.Html.AotSmoke -r linux-x64 # NativeAOT check; use your own RID dotnet publish tests/OnePdf.Html.Render.AotSmoke -r linux-x64 ``` Set `ONEPDF_HTML_ARTIFACTS` to move build output out of the checkout. Licensed under either of MIT or Apache-2.0 at your option. Copyright Recursive AI, LLC. <!-- https://recursiveai.org/onepdf-html/docs/pdf-to-html/ --> # PDF to HTML `RecursiveAI.OnePdf.Html` converts a PDF to HTML in one of two modes. This guide covers every public option and type. Everything is in the namespace `OnePdf.Html`; OCR is in `OnePdf.Html.Ocr` ([below](#text-sources-and-ocr)). - [Choosing a mode](#choosing-a-mode) - [The happy path: `PdfHtml`](#the-happy-path-pdfhtml) - [Options](#options) - [Semantic output](#semantic-output) - [Fixed-layout output](#fixed-layout-output) - [Where the output goes: files, assets and sinks](#where-the-output-goes-files-assets-and-sinks) - [Page by page: `PdfHtmlConverter`](#page-by-page-pdfhtmlconverter) - [Text sources and OCR](#text-sources-and-ocr) - [Passwords, repair, limits and cancellation](#passwords-repair-limits-and-cancellation) - [Diagnostics](#diagnostics) - [Type index](#type-index) ## Choosing a mode `PdfHtmlOptions.Mode` picks what is written. - **`Semantic`** (the default) writes reflowing HTML in reading order. Use it for reading, search, accessibility, indexing and republishing. It has no fixed page size; it keeps the structure, not the geometry. - **`FixedLayout`** writes each page as a box of the page's size. Use it when the HTML must look like the PDF. Both modes read the same page analysis, so page ranges, passwords, limits, OCR, links, diagnostics and output sinks work alike. ## The happy path: `PdfHtml` ```csharp using OnePdf.Html; string html = PdfHtml.Convert("report.pdf"); // reflowing HTML as text, images inline PdfHtml.Convert("report.pdf", "fixed.html", // fixed-layout pages, one file new PdfHtmlOptions { Mode = PdfHtmlMode.FixedLayout }); PdfHtmlResult result = PdfHtml.Convert("report.pdf", "pages", // a file per page, images and fonts as files new PdfHtmlOptions { Layout = PdfHtmlOutputLayout.PagePerFile, Assets = PdfHtmlAssetMode.Files }); Console.WriteLine($"{result.PageCount} pages, {result.Diagnostics.Count} diagnostics"); ``` `PdfHtml.Convert` has these shapes, each taking `PdfHtmlOptions? options = null` and a `CancellationToken`: | Call | Result | |---|---| | `Convert(string path, ...)`, `Convert(Stream pdf, ...)`, `Convert(ReadOnlyMemory<byte> pdf, ...)` | One HTML document as a string, images inline. `Layout` and `Assets` do not apply. | | `Convert(string path, string outputPath, ...)`, `Convert(ReadOnlyMemory<byte> pdf, string outputPath, ...)` | Writes a file (or a directory for `PagePerFile`) and returns a `PdfHtmlResult` with `PageCount` and `Diagnostics`. If the conversion fails or is cancelled, the files it created are removed. | | `Convert(Stream pdf, Stream output, ...)` | Writes one HTML document, images inline, to `output` (left open). | ```csharp using OnePdf.Html; using var input = File.OpenRead("report.pdf"); string fromStream = PdfHtml.Convert(input); byte[] bytes = File.ReadAllBytes("report.pdf"); string fromMemory = PdfHtml.Convert(bytes, new PdfHtmlOptions { Mode = PdfHtmlMode.FixedLayout }); using var output = File.Create("stream.html"); PdfHtml.Convert(new MemoryStream(bytes), output); ``` ## Options `PdfHtmlOptions` is immutable once built (every property is `init`-only), safe to share between conversions and threads, and every default is safe for untrusted input. `PdfHtmlOptions.Default` is the instance with every default. Values out of range throw `ArgumentOutOfRangeException` when a conversion starts. ### Every mode | Property | Default | What it does | |---|---|---| | `Mode` | `Semantic` | `Semantic` or `FixedLayout`. | | `PageRanges` | all pages | Which pages to convert. See [page ranges](#page-ranges). Pages beyond the document are ignored with a `pages-out-of-range` warning. | | `Password` | none | Tried as the user password, then as the owner password. A wrong or missing password throws `PdfPasswordException` when the file is opened. | | `Limits` | `PdfLimits.Default` | OnePDF's parsing and interpretation bounds (decoded stream size, nesting, operators per page and so on). | | `Strict` | `false` | When true, every repair OnePDF would make while reading the file throws `PdfFormatException` instead. | | `MaxInputBytes` | 1 GiB | The most bytes a path or stream input may have when it is read into memory. | | `MaxOutputBytesPerPage` | 256 MiB | The most bytes one page may produce, HTML and assets together. A page over the bound is written empty with a `page-failed` error. | | `MaxAssetsPerPage` | 4,096 | The most images and fonts one page may produce; the rest are left out with an `asset-limit` or `assets-limit` warning. | | `MaxDegreeOfParallelism` | 0 (the smaller of 4 and the processor count) | Pages analysed at once. They are written in page order, so memory depends on this number, not on the page count. 1 converts on the calling thread. The output does not depend on it. | | `Layout` | `SingleFile` | `SingleFile` or `PagePerFile`. Applies to the path-based methods. | | `Assets` | `Inline` | `Inline` (`data:` URIs) or `Files`. Applies to the path-based methods. | | `Fonts` | `WebFonts` | How the PDF's fonts reach the output, in both modes. See [fonts](#fonts). | | `RasterDpi` | 144 | Resolution of page pictures, 36 to 600: the fixed-layout fallback pictures and the pictures that vector figures become in semantic output. | | `MaxRasterPixels` | 2^26 | The most pixels in one page picture; a larger one is drawn at a lower resolution with a `raster-reduced` note. | | `TextSource` | the PDF's text layer | Supplies each page's text. Set it to an `OcrTextSource` for scans. See [text sources](#text-sources-and-ocr). | ### Semantic only | Property | Default | What it does | |---|---|---| | `HeadersAndFooters` | `Mark` | `Mark`: written apart from the flow with `role="doc-pageheader"` / `"doc-pagefooter"`, so a reader or a style sheet can hide them. `Keep`: ordinary paragraphs where they stand. `Drop`: left out. | | `PageBoundaries` | `Marker` | `Marker`: a zero-size `role="doc-pagebreak"` element with id `page-N` at each page start. `Section`: each page's content in a `section` with id `page-N`. | | `FormFields` | `Text` | `Text`: name and value as text. `Controls`: real `input`, `textarea` and `select` elements filled with the values (no form action, no script). `None`: left out. | | `Annotations` | `true` | Write the text of notes, comments and other annotations as `aside` elements next to the text they sit on. | | `FontMapping` | `Generic` | Reflowing output only: `Generic` marks monospace, serif and sans-serif runs that differ from the document's main family with a generic CSS family; `None` writes no font information. Fixed layout sets each span in its own font's family (see `Fonts`). | ### Fixed layout only | Property | Default | What it does | |---|---|---| | `Zoom` | 1 | Scale of the pages: 1 is 96 CSS pixels per inch of page; between 0.1 and 10. | | `LazyPages` | `false` | Draw a page only when it scrolls near the viewport (CSS `content-visibility`, no script). Each page keeps its size, so scrolling and links work as usual. | ```csharp using OnePdf; using OnePdf.Html; var semantic = new PdfHtmlOptions { Mode = PdfHtmlMode.Semantic, HeadersAndFooters = PdfHtmlHeaderFooter.Drop, PageBoundaries = PdfHtmlPageBoundaries.Section, FormFields = PdfHtmlFormFields.Controls, Annotations = false, Fonts = PdfHtmlFontMode.CssFamilies, FontMapping = PdfHtmlFontMapping.Generic, }; string article = PdfHtml.Convert("report.pdf", semantic); var fixedLayout = new PdfHtmlOptions { Mode = PdfHtmlMode.FixedLayout, Zoom = 1.5, LazyPages = true, RasterDpi = 192, MaxRasterPixels = 1L << 25, Fonts = PdfHtmlFontMode.WebFonts, }; PdfHtml.Convert("report.pdf", "fixed-lazy.html", fixedLayout); var bounded = new PdfHtmlOptions { Limits = PdfLimits.Default, Strict = false, MaxInputBytes = 256L << 20, MaxOutputBytesPerPage = 64L << 20, MaxAssetsPerPage = 1000, MaxDegreeOfParallelism = 2, Password = "user-pw", }; string locked = PdfHtml.Convert("locked.pdf", bounded); ``` ### Page ranges `PdfHtmlPageRanges` selects pages. `All` is every page. `Parse` reads one-based text such as `1-3,7,10-` (an open end runs to the last page; an open start begins at page 1) and throws `ArgumentException` for text it cannot read. `FromIndices` takes zero-based indices. `Resolve(pageCount)` returns the zero-based indices that fall inside a document, ascending, each once. ```csharp using OnePdf.Html; PdfHtmlPageRanges some = PdfHtmlPageRanges.Parse("1-2,5,8-"); IReadOnlyList<int> indices = some.Resolve(10); // 0, 1, 4, 7, 8, 9 PdfHtmlPageRanges explicitPages = PdfHtmlPageRanges.FromIndices([0, 2]); string firstAndThird = PdfHtml.Convert("report.pdf", new PdfHtmlOptions { PageRanges = explicitPages }); Console.WriteLine($"{some} {indices.Count} {PdfHtmlPageRanges.All.Resolve(3).Count} {firstAndThird.Length}"); ``` ## Semantic output The document is `main` holding the pages' content in reading order, with the title, language and metadata in `head` (`title`, `lang`, `meta` for author, subject, keywords, creator and dates). ### Tagged files When a page's marked content is in the structure tree, the tree decides the structure. `/RoleMap` is followed, artifacts are dropped, and `/ActualText`, `/Alt` and `/Lang` are used. | PDF structure type | HTML | |---|---| | `H`, `H1`..`H6`, `Title` | `h1`..`h6` (`Title` is `h1`) | | `P`, `BibEntry` | `p` | | `TOC`, `TOCI` | `nav role="doc-toc"`, `p class="toci"` | | `L`, `LI`, `Lbl`, `LBody` | `ul` (`ol` with its start number when the list numbering says so), `li`; the label is dropped and the body kept | | `Table`, `THead`, `TBody`, `TFoot`, `TR`, `TH`, `TD` | `table`, `thead`, `tbody`, `tfoot`, `tr`, `th` (with `scope`), `td`, with `colspan` and `rowspan` | | `Figure`, `Caption` | `figure` with its picture and alt text; a caption next to a figure goes in its `figcaption`, a table's caption is a `caption` | | `Note`, `FENote` | `aside role="doc-footnote"` | | `Formula` | `div role="math"` with `aria-label` from the alternate text | | `BlockQuote`, `Quote` | `blockquote`, `q` | | `Code` | `code` | | `Link` | `a` (only kept targets, see [links](#links)) | | `Em`, `Strong`, `Sub`, `Sup`, `Span` | `em`, `strong`, `sub`, `sup`, and a language or text run | | `Sect`, `Art`, `Div`, `Part`, `Index` | `section`, `article`, `div` | | Any other type | A `div`, so its content is never lost | Small pictures inside a line become inline `img` elements of that line. A figure drawn with paths has no image object, so its area is cut from a page picture (drawn at `RasterDpi`) and written as the figure's image. A page can be **partly tagged**: text the tree leaves out is built as for an untagged page and put among the tagged elements in reading order. Text inside `/Artifact` marked content is page furniture the producer declared and never comes back as a paragraph. ### Untagged files Structure is inferred from OnePDF's text extraction, which already handles columns, right-to-left text and vertical text. - **Headings** come from the outline first (a line that is exactly an outline title stands alone), then from size and weight against the document's body type. Heading sizes within 10 % are one level. - **Paragraphs** are joined from lines. A line-end hyphen is removed when the next line starts in lower case; CJK lines join without a space. Tightly set blocks that continue are one paragraph. - **Lists**: bullets and numbers are recognised from the marker and the hanging indent, nest by indent and keep their start number. - **Tables**: found from rules and fills the page draws (ruled grids) and from the alignment of words (unruled tables), with row and column spans, header rows and header columns, right-to-left and CJK tables. Charts, prose columns, label/value lines, contents lines, line-number columns and mostly empty grids are refused on purpose. - **Notes**: small print at the foot of a page, led by a marker or set apart, becomes an `aside role="doc-footnote"` linked both ways with its reference. - **Figures** are `figure` elements with a `figcaption` when a caption stands next to them; JPEG is passed through, other images become PNG. An image the PDF gives no description for is written with empty alternative text (an `image-no-alt` note). - **Forms and annotations** follow `FormFields` and `Annotations`. - **Language and direction**: the document language is on `html`; right-to-left blocks carry `dir`. ### Joins across pages A paragraph, list, table or note that a page break cuts is written once, in the page it starts in. A table that continues on the next page with the same columns is one `table`, whether or not its header repeats; a repeated header is not duplicated. ### Headers and footers A header or footer is text near the top or bottom of the page (the outer 12 %) that repeats, with its digits masked, on enough pages of a sample of the document. One page cannot tell, so the whole document decides. `HeadersAndFooters` marks them (default), keeps them as paragraphs or drops them. ### Page boundaries `PageBoundaries.Marker` (default) writes an empty `span` with `role="doc-pagebreak"`, the id `page-N` and an `aria-label` at the start of each page, so links between pages and a "go to page" feature work. `Section` wraps each page in a `section` with that id. ### Links Links keep only targets that are safe: `http`, `https`, `mailto` and in-document destinations. An internal link becomes an anchor to the page (`#page-N` in one file, the page's file name with `PagePerFile`) and only for pages that are part of the conversion. Anything else (`javascript:`, `file:`, `data:`, launch and submit actions, JavaScript) is dropped with a `link-dropped` warning. A link that covers no text is left out with a `link-unplaced` note. ### Fonts `Fonts = WebFonts` (the default) writes each PDF font as one WOFF2 subset for the whole document, holding the characters every converted page uses. Its characters are the Unicode text the extraction read, so the HTML text stays the extracted text and only the look is the PDF's. The `@font-face` rules sit in the document's head (`PdfHtmlDocumentShell.Prefix`); with file assets each font is a `font-<hash>.woff2` file. Non-embedded standard fonts become web fonts from the substitute outlines of `RecursiveAI.OnePdf.Fonts`. `Fonts = CssFamilies` writes no font: runs are set in CSS families chosen from the font's name (Helvetica and Arial as sans-serif, Times and Georgia as serif, Courier as monospace, bold and italic from the name), and `FontMapping` decides how much of that is written. Output is much smaller and the text uses the reader's fonts. The fonts in the output are built anew from the glyph outlines the page draws, so they carry the shapes of the PDF's fonts, in both modes and with inline or file assets. Each is named by the converter (`Page`), never by the font it came from. - **Fonts the PDF does not embed** (the standard 14 and their aliases) are drawn from the substitute fonts of `RecursiveAI.OnePdf.Fonts` (Liberation, Noto Sans Math, Noto Sans Symbols), which are under the SIL Open Font License 1.1. The converter asks for those fonts before any font installed on the machine, so the output does not depend on the machine. Every web font built from such outlines carries, in its `name` table, the source font's copyright line (name ID 0), the licence description (ID 13: the OFL 1.1 notice) and the licence URL (ID 14, <https://openfontlicense.org>). Any other substitute the font providers return (an installed font for a non-standard name) is handled the same way when its own `name` table says it is under the OFL; a substitute under another license gets no notice from the converter. - **Fonts embedded in the PDF** are rebuilt from their outlines with a plain `name` table and no notice. Whether such a font's license allows that is for the document's owner to judge: the converter does not read embedding-permission flags. - `CssFamilies` writes no font. See [THIRD-PARTY-NOTICES.md](https://github.com/recursive-ai-oss/onepdf-html-csharp/blob/166c1177813f222de669a1f456eeb495b18e6103/THIRD-PARTY-NOTICES.md). The notice adds about 0.5 KB to each web font built from OFL outlines before WOFF2 compression and about 0.2 KB in the file. ## Fixed-layout output Each page is a `section` of the page's size (`width` and `height` in CSS pixels, times `Zoom`), with `data-page` and `id="page-N"`: - **Text** is real text. Each extracted line is one absolutely positioned, transformed element holding spans of the extracted Unicode, in reading order, so selecting and copying gives the page's text. Words that run against their line's direction (numbers in right-to-left text) set their own direction so glyph order and copied text both stay logical. Text the PDF does not draw as text (invisible, stroked, clipping, Type 3, pattern-filled) is transparent text in a font that carries only advances. - **Fonts**: with `WebFonts`, each font is rebuilt from the glyph shapes the PDF draws, with a character map that leads each character to its shape and each ligature or cluster to its glyph, and written as WOFF2. A glyph with no Unicode value in the extraction is mapped to a private-use character in a span that is `aria-hidden` and not selectable; where the page's text layer has no word for the glyph (recognised text replaces the layer, form field and annotation appearances) the character is generated content, so it is drawn but never copied. With `CssFamilies` no font is written and every word is placed where the PDF has it; a glyph the extraction has no text for is not drawn. - **Vector graphics** are SVG: paths, clips, gradients, patterns, groups, soft masks and blend modes, in painting order. - **Images** are PNG (JPEG passed through when possible), written once per document when pages share a document. - **Links** are positioned over the page and follow the [link rules](#links). ### The raster fallback Anything a browser cannot express is cut from one render of the page (PNG, or JPEG for large pieces) at `RasterDpi` and placed where it belongs, with the text still selectable over it. It is always reported, once per page, as `raster-fallback`, with the number of elements and the reason: - mesh shadings (types 4 to 7) and function-based shadings; - radial shadings whose inner circle is not extended; - tiling patterns whose cells overlap; - image masks painted with a pattern; - knockout groups whose content is painted with transparency, a blend mode or a soft mask. If a page's drawing cannot be interpreted at all, the whole page is a picture (`raster-fallback`, warning). If even the picture cannot be drawn, the page is empty with a `raster-failed` error. A picture that would pass `MaxRasterPixels` is drawn smaller (`raster-reduced`). Not simulated, as in the reference render, and reported once per page: overprint (`overprint`), a shading pattern's graphics state (`pattern-extgstate`), and a knockout group inside a soft mask or other frame the picture can't stand in for (`knockout-group`). ### Zoom, resolution and lazy loading `Zoom` scales page boxes and everything in them. `RasterDpi` only changes the fallback pictures. `LazyPages` adds a class that uses `content-visibility` so a long document opens quickly in a browser; nothing is scripted. ## Where the output goes: files, assets and sinks `PdfHtmlOptions.Layout` and `Assets` choose how the path-based methods write: | Layout | Assets | Result for `Convert(pdf, outputPath, ...)` | |---|---|---| | `SingleFile` | `Inline` | One HTML file, images and fonts as `data:` URIs. Nothing else is needed to open it. | | `SingleFile` | `Files` | `out.html` and a folder `out_files/` beside it with the images and fonts. | | `PagePerFile` | `Inline` | A directory `out/` with `page-0001.html`, `page-0002.html`, ... and `index.html`, which lists and links the pages. | | `PagePerFile` | `Files` | The same, with `out/assets/` holding the images and fonts. | File names are made by the converter, never taken from the PDF. In one file, pictures used on several pages are written once. All of this is `IPdfHtmlSink`. `PdfHtmlFileSink(path, layout, assets)` writes the files above; `PdfHtmlStreamSink(stream)` writes one document with inline images to a stream; you can write your own. A sink is told its `AssetMode`, its `AssetPathPrefix` (ending in `/`) and `GetPageUrl(pageIndex)` (how links between pages are written), then receives `BeginDocument(PdfHtmlDocumentShell)`, each `PdfHtmlPage` in page order, and `EndDocument(PdfHtmlIndex)`. Set `PagesShareDocument` (an interface default, false) to true when every page ends up in one HTML document, so pages may share definitions. Pages are not kept by the converter, so a sink that writes them out keeps memory flat however long the document is. ```csharp using OnePdf.Html; sealed class PageListSink : IPdfHtmlSink { public PdfHtmlAssetMode AssetMode => PdfHtmlAssetMode.Files; public string AssetPathPrefix => "assets/"; public string GetPageUrl(int pageIndex) => $"page-{pageIndex + 1}.html"; public void BeginDocument(PdfHtmlDocumentShell shell) => Console.WriteLine($"Title: {shell.Title}"); public void WritePage(PdfHtmlPage page) { Console.WriteLine($"page {page.PageIndex + 1}: {page.Width} x {page.Height} pt, {page.Html.Length} characters of HTML"); foreach (PdfHtmlAsset asset in page.Assets) { Console.WriteLine($" {asset.Path} ({asset.MediaType}, {asset.Data.Length} bytes)"); } } public void EndDocument(PdfHtmlIndex index) => Console.WriteLine($"index: {index.Html.Length} characters"); } ``` ```csharp using OnePdf.Html; using PdfHtmlConverter listing = PdfHtmlConverter.Open("report.pdf"); listing.ConvertTo(new PageListSink()); ``` `PdfHtmlPage.Html` is one element (the page's `section`, with id `page-N`) to put inside a body; `PdfHtmlDocumentShell.Prefix` and `Suffix` are everything before and after the pages (doctype, head with title, metadata and style, the opening and closing of `body`), and `PdfHtmlIndex.Html` is a complete page listing. ## Page by page: `PdfHtmlConverter` `PdfHtmlConverter.Open` takes a path, a stream (read to its end and not kept) or memory (referenced, not copied). One converter can be used from several threads; dispose it to release the file. ```csharp using OnePdf.Html; var cancellation = new CancellationTokenSource(); using PdfHtmlConverter converter = PdfHtmlConverter.Open("report.pdf", new PdfHtmlOptions { PageRanges = PdfHtmlPageRanges.Parse("1-2") }); Console.WriteLine($"{converter.PageCount} pages in the file, converting {converter.SelectedPages.Count}"); PdfHtmlPage first = converter.ConvertPage(0, cancellation.Token); // images inline, links to other pages as #page-N PdfHtmlPage second = converter.ConvertPage(1, new PageListSink(), cancellation.Token); // for that sink's asset mode and page URLs PdfHtmlDocumentShell shell = converter.CreateShell(); string document = shell.Prefix + first.Html + second.Html + shell.Suffix; foreach (PdfHtmlDiagnostic diagnostic in converter.Diagnostics) { Console.WriteLine(diagnostic); // Warning: ... [link-dropped] (page 2) } Console.WriteLine($"{document.Length} {converter.Options.Mode} {converter.Document.Pages.Count}"); ``` - `Options` is the options the converter was opened with, and `Document` the open `PdfDocument` from OnePDF for anything the converter does not expose. - `ConvertPage(index)` converts one page with images inline; `ConvertPage(index, sink)` writes for a sink's asset mode and page URLs (it does not call the sink's `WritePage`). - A page that cannot be read, or whose output passes a limit, comes back empty with an error diagnostic (`page-failed`); the other pages are not affected. Cancelling raises `OperationCanceledException`. - `ConvertTo(sink, cancellationToken)` converts every selected page, a window at a time in parallel, and hands them to the sink in order. - `Diagnostics` lists what OnePDF recorded about the file (document diagnostics first, ordered by object number and offset), then the converter's, ordered by page; at most 10,000 are kept. ### Reading what the converter found `Analyze(pageIndex)` returns the analysis both modes are built on, which is useful for your own output. ```csharp using OnePdf.Html; using PdfHtmlConverter reader = PdfHtmlConverter.Open("report.pdf"); PdfHtmlPageAnalysis analysis = reader.Analyze(0); Console.WriteLine($"{analysis.Width} x {analysis.Height} pt, {analysis.Links.Count} links"); foreach (PdfHtmlLink link in analysis.Links) { Console.WriteLine($"{link.Bounds}: {link.Href ?? "page " + (link.TargetPage + 1)}"); } foreach (PdfHtmlTextBlock block in analysis.Text.Blocks) { Console.WriteLine($"{block.Role} {block.Kind}: {string.Join(' ', block.Lines.Select(static l => l.Text))}"); } foreach (PdfHtmlTable table in analysis.Tables) { Console.WriteLine($"{table.RowCount} x {table.ColumnCount} table, {table.HeaderRowCount} header rows, ruled: {table.IsRuled}"); } ``` `PdfHtmlPageAnalysis` also has `PageIndex`, `Page` (the OnePDF page), `TextLayer` (OnePDF's extraction, glyphs retained), `Diagnostics` and `DisplayList` (the page interpreted into a display list, built on first use). `PdfHtmlLink` has `Bounds`, `Href` (a kept `http`, `https` or `mailto` target, or null) and `TargetPage` (zero-based, or -1). `PdfHtmlTable` has its `Cells` (`PdfHtmlTableCell`: `Row`, `Column`, `RowSpan`, `ColumnSpan`, `Bounds`, `IsHeader`, `Text`, `Words`), `Bounds`, `RowCount`, `ColumnCount`, `HeaderRowCount`, `HeaderColumnCount`, `HeaderColumns` (every column whose body cells are row headers, including label columns after the first), `IsRuled`, `IsRightToLeft`, `Columns`, `AtPageTop` and `AtPageBottom`. `PdfHtmlTables.Continues`, `Merge` and `Flow` are the helpers the converter uses to join a table across a page break and to place tables among text blocks. ## Text sources and OCR A **text source** (`IPdfHtmlTextSource`) supplies each page's text in the form both modes read: blocks of lines of words with geometry in points, y up. The converter calls it once per page, possibly from several threads at once. `PdfHtmlOptions.TextSource` null means `PdfHtmlTextSources.TextLayer`, the PDF's own text as OnePDF extracts it, whether or not it is any good. `PdfHtmlTextSources.Assess(request)` says whether a page's own text can be trusted, by rules that need no model: | Verdict | Meaning | Rule codes | |---|---|---| | `Usable` | The text can be used as it is. | `text-layer-ok` | | `Empty` | No text and nothing to read: no picture, or a picture with next to no ink. | `empty-page` | | `NoText` | No text over a picture with ink on it: a scan. | `scanned-page` | | `Garbled` | Text whose characters cannot be trusted: many replacement or private-use characters, glyphs with no Unicode value, UTF-8 read as a single-byte encoding, or words that are not words (wrong character maps). | `replacement-characters`, `private-use-characters`, `mojibake`, `unreadable-words`, `implausible-letters` | | `Misplaced` | Invisible text over a picture that has no ink where the text claims to be. | `text-off-ink` | `NeedsRecognition` is true for `NoText`, `Garbled` and `Misplaced`. `PdfHtmlTextSources.IsTextLayerUsable(textLayer)` is the cheap, text-only part of the rules. ```csharp using OnePdf.Html; sealed class ReportingTextSource : IPdfHtmlTextSource { public PdfHtmlPageText GetPageText(PdfHtmlTextRequest request, CancellationToken cancellationToken) { PdfHtmlTextLayerAssessment verdict = PdfHtmlTextSources.Assess(request, cancellationToken); Console.WriteLine($"page {request.PageIndex + 1}: {verdict.Verdict} ({verdict.Code}): {verdict.Message}"); return PdfHtmlTextSources.TextLayer.GetPageText(request, cancellationToken); } } ``` ```csharp using OnePdf.Html; string withSource = PdfHtml.Convert("report.pdf", new PdfHtmlOptions { TextSource = new ReportingTextSource() }); ``` A `PdfHtmlTextRequest` gives the source the `Page`, `PageIndex`, `TextLayer`, `Width`, `Height` and `RenderPage(dpi)`, which draws the page for a source that recognises text. A source returns a `PdfHtmlPageText` (`Origin` of `TextLayer` or `Recognized`, `Blocks`, `Tables`, `Diagnostics`) built from `PdfHtmlTextBlock` (`Lines`, `Bounds`, `Role`, `IsTable`, `Kind` of `Unknown`, `Text`, `Title`, `List` or `FormField`), `PdfHtmlTextLine`, `PdfHtmlTextWord` (text, bounds, font size, bold, italic, font name, marked-content id) and, for tables whose grid the source knows, `PdfHtmlTextTable` and `PdfHtmlTextTableCell`. ### The OCR package `RecursiveAI.OnePdf.Html.Ocr` implements the seam with [OneOcr](https://github.com/recursive-ai-oss/oneocr-csharp). It keeps the weights out of the core package, and the models are loaded the first time a page needs them. The package itself brings the Latin, Greek and Cyrillic models; other scripts come from the script-family packages below. ```csharp using OnePdf.Html; using OnePdf.Html.Ocr; using var ocr = new OcrTextSource(new OcrTextSourceOptions { Mode = OcrMode.Auto, Languages = ["en"], RenderDpi = 300, MaxConcurrentPages = 2, }); string text = PdfHtml.Convert("scan.pdf", new PdfHtmlOptions { TextSource = ocr }); ``` | `OcrTextSourceOptions` | Default | What it does | |---|---|---| | `Mode` | `Auto` | `Auto`: recognise a page only where `Assess` says its own text is missing or cannot be trusted. `Always`: recognise every page; the PDF's own text is used only where recognition fails. `Never`: never. | | `RenderDpi` | 300 | Resolution the page is drawn at before it is read, 100 to 600. | | `MaxPixels` | 40 million | A page whose picture would be larger is drawn at a lower resolution (`ocr-dpi-reduced`). | | `Languages` | none | BCP 47 tags the document is expected to be in (`en`, `ja`, `zh-Hant`, `ar`). With none, the recogniser decides line by line from the models installed. With tags, only the models for their scripts are tried, which is faster and avoids look-alike mix-ups; naming the language also keeps Latin text exactly as the Latin model alone reads it (see the note below). A tag whose script has no model installed leaves those lines unread, and each page that needed recognition gets an `ocr-language-unsupported` warning. | | `MaxConcurrentPages` | 2 | Pages recognised at once, whatever the converter's own parallelism. | | `MaxDegreeOfParallelismPerPage` | 0 (the recogniser chooses) | Threads one page's recognition may use. The text does not depend on it. | | `MinWordConfidence` | 0 | Words the recogniser is less sure of than this (0 to 1) are left out. | | `Engine` | the bundled models, plus any script-family models installed beside the application | A `OneOcr.OcrEngine` to use instead. | **Scripts and packages.** Add the packages for the scripts you need to the application (or the tool); each one drops its model into `oneocr-models/` beside the program, in builds and in NativeAOT publishes, and the default engine picks it up. Nothing in the code changes. | Package | Reads | Size (nupkg) | |---|---|---| | `RecursiveAI.OneOcr` and `RecursiveAI.OneOcr.Models` (brought by `RecursiveAI.OnePdf.Html.Ocr`) | Latin with accents, Greek, Cyrillic | 0.6 MB and 8.0 MB | | `RecursiveAI.OneOcr.Models.Cjk` | Chinese (Simplified, Traditional), Japanese including vertical lines, Korean | 17.3 MB | | `RecursiveAI.OneOcr.Models.Arabic` | Arabic, Persian, Urdu | 4.4 MB | | `RecursiveAI.OneOcr.Models.Hebrew` | Hebrew | 4.3 MB | | `RecursiveAI.OneOcr.Models.Indic` | nine Indic languages | 8.7 MB | Thai, Armenian, Georgian and other scripts have no model yet. Right-to-left lines come back in logical order. **Measured** (text error of the converted page against the truth text, `Auto` mode, no `Languages`; OneOcr 1.2.0 with all four family packages installed): the scanned Japanese, Korean and Chinese pages read 0.4 % content / 0.6 % order error (with the Latin models alone: 48.8 % / 71.4 %); the Arabic and Hebrew pages 2.9 % / 4.6 % (with the Latin models alone: 89.7 % / 102.3 %); Greek and Cyrillic read 0.0 %. Latin scans read the same with or without the family packages: 12 scans read 1.1 % / 2.5 % in semantic output and 0.2 % / 1.1 % in fixed-layout output. Scans run about 0.1 to 1.5 s per page at the default settings; a page of Chinese or Arabic text takes the longest. One `OcrTextSource` is safe to share between threads and conversions; dispose it when you are done. What comes back is words, lines and blocks in reading order with boxes in page points, line direction, header and footer roles, block kinds where the recogniser says (title, list) and tables with their grid (used as given by the table output). A page that is recognised carries an `ocr-page` note, with the number of words and the rule that decided. ```csharp using OnePdf.Html; using OnePdf.Html.Ocr; using var everything = new OcrTextSource(new OcrTextSourceOptions { Mode = OcrMode.Always, MinWordConfidence = 0.6 }); PdfHtml.Convert("scan.pdf", "recognised.html", new PdfHtmlOptions { Mode = PdfHtmlMode.FixedLayout, TextSource = everything }); ``` In fixed layout, recognised text is placed over the page picture as selectable text; in semantic output it is structured like any other text. ## Passwords, repair, limits and cancellation - **Passwords.** Set `Password`; a wrong or missing one throws `PdfPasswordException`. The command line exits with code 3. - **Repair.** Damaged files are repaired where the repair is unambiguous (bad offsets, wrong lengths, missing cross-reference tables), and each repair is a diagnostic. `Strict = true` turns them into `PdfFormatException`. - **Limits.** The `Limits` bounds and the output bounds are checked before the work or allocation they guard. An input over `MaxInputBytes` throws `PdfHtmlLimitException` when it is opened. A page that passes an output bound is written empty with a `page-failed` error and the other pages go on. A file that is not a PDF throws `PdfFormatException`. - **Cancellation.** Every conversion method takes a `CancellationToken` and throws `OperationCanceledException`; files a path-based conversion had created are removed. - **Parallelism.** `MaxDegreeOfParallelism` bounds how many pages are analysed at once. The output is the same at any degree. - **Determinism.** The converter reads no clock, culture or thread identity. The same input and options give byte-identical output. ```csharp using OnePdf; using OnePdf.Html; try { PdfHtml.Convert("locked.pdf"); } catch (PdfPasswordException) { Console.WriteLine("The document needs a password: set PdfHtmlOptions.Password."); } catch (PdfFormatException e) { Console.WriteLine($"Not a readable PDF: {e.Message}"); } catch (OperationCanceledException) { Console.WriteLine("Cancelled."); } ``` ## Diagnostics Everything the converter repaired, dropped or reduced is a `PdfHtmlDiagnostic`: `Severity` (OnePDF's `PdfSeverity`: info, warning, error), `Source` (`Pdf` for what OnePDF reported while reading the file, `Converter` for a decision of the converter), `PageIndex` (zero-based, or -1 for the document), a stable `Code` (empty for `Pdf` diagnostics) and a `Message`. `ToString()` gives a one-line form. The codes are listed in [diagnostics.md](https://recursiveai.org/onepdf-html/docs/diagnostics/). ## Type index Every public type of `RecursiveAI.OnePdf.Html` and where it is described: | Type | Where | |---|---| | `PdfHtml`, `PdfHtmlResult` | [The happy path](#the-happy-path-pdfhtml) | | `PdfHtmlConverter` | [Page by page](#page-by-page-pdfhtmlconverter) | | `PdfHtmlOptions`, `PdfHtmlMode`, `PdfHtmlFontMode`, `PdfHtmlOutputLayout`, `PdfHtmlAssetMode`, `PdfHtmlHeaderFooter`, `PdfHtmlPageBoundaries`, `PdfHtmlFormFields`, `PdfHtmlFontMapping`, `PdfHtmlPageRanges` | [Options](#options) | | `IPdfHtmlSink`, `PdfHtmlFileSink`, `PdfHtmlStreamSink`, `PdfHtmlPage`, `PdfHtmlAsset`, `PdfHtmlDocumentShell`, `PdfHtmlIndex` | [Where the output goes](#where-the-output-goes-files-assets-and-sinks) | | `PdfHtmlPageAnalysis`, `PdfHtmlLink`, `PdfHtmlTable`, `PdfHtmlTableCell`, `PdfHtmlTables` | [Reading what the converter found](#reading-what-the-converter-found) | | `IPdfHtmlTextSource`, `PdfHtmlTextSources`, `PdfHtmlTextRequest`, `PdfHtmlPageText`, `PdfHtmlTextBlock`, `PdfHtmlTextBlockKind`, `PdfHtmlTextLine`, `PdfHtmlTextWord`, `PdfHtmlTextTable`, `PdfHtmlTextTableCell`, `PdfHtmlTextOrigin`, `PdfHtmlTextLayerAssessment`, `PdfHtmlTextLayerVerdict` | [Text sources](#text-sources-and-ocr) | | `PdfHtmlDiagnostic`, `PdfHtmlDiagnosticSource`, `PdfHtmlLimitException` | [Diagnostics](#diagnostics), [diagnostics.md](https://recursiveai.org/onepdf-html/docs/diagnostics/) | | `OcrTextSource`, `OcrTextSourceOptions`, `OcrMode` (`RecursiveAI.OnePdf.Html.Ocr`) | [The OCR package](#the-ocr-package) | The reverse direction is in [html-to-pdf.md](https://recursiveai.org/onepdf-html/docs/html-to-pdf/); the command line in [cli.md](https://recursiveai.org/onepdf-html/docs/cli/). <!-- https://recursiveai.org/onepdf-html/docs/html-to-pdf/ --> # HTML to PDF `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](https://github.com/recursive-ai-oss/onerender-csharp), 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`](#the-happy-path-htmltopdf) - [Inputs](#inputs) - [Options](#options) - [Pages: size, orientation and margins](#pages-size-orientation-and-margins) - [Headers and footers](#headers-and-footers) - [Links, outline, metadata and tags](#links-outline-metadata-and-tags) - [PDF/UA and PDF/A](#pdfua-and-pdfa) - [Resources, files and the network](#resources-files-and-the-network) - [Batches](#batches) - [The low level: `HtmlToPdfConverter`](#the-low-level-htmltopdfconverter) - [Results, diagnostics and errors](#results-diagnostics-and-errors) - [Determinism](#determinism) - [Type index](#type-index) ## The happy path: `HtmlToPdf` ```csharp 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. | Call | What 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](#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: | Factory | Input | |---|---| | `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. ```csharp using OnePdf.Html.Render; HtmlSource[] sources = [ HtmlSource.FromFile("page.html"), HtmlSource.FromHtml("<html lang=\"en\"><title>Inline

Inline

"), 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); ``` ```csharp using OnePdf.Html.Render; static class Rendering { public static Task 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. | Property | Default | What it does | |---|---|---| | `PageSize`, `Orientation`, `Margins` | the document's `@page`, else A4, portrait, 0.5 inch | [Pages](#pages-size-orientation-and-margins). Once set, they win over the document's `@page` rule. | | `Header`, `Footer` | none | [Running headers and footers](#headers-and-footers). | | `Links` | `Web` | Which links are clickable. | | `Outline` | every heading level | Bookmarks from the headings; null for none. | | `Title`, `Author`, `Subject`, `Keywords`, `Language` | from the HTML | Metadata. | | `Creator` | `OnePdf.Html` | The producing application written to the file. | | `CreationDate` | none | The creation date. The converter never reads the clock. | | `DocumentId` | derived from the title | Sixteen bytes for the file's `/ID`. | | `Profile` | `None` | PDF/UA-1, PDF/A-2a, or both. | | `Tagged` | `true` | Write the tag structure. | | `Compress` | `true` | Compress the streams. | | `RasterDpi` | 192 | Resolution, 24 to 600 pixels per inch, of the images that stand in for what PDF cannot express (blur, some filters, inline SVG). | | `MaxPages` | 100,000 | More pages fail with `HtmlToPdfFailure.Limit`. | | `Resources` | none | A callback that supplies a resource by address before the built-in loader runs. | | `Network` | off | `HtmlNetworkOptions`. | | `Limits` | see below | `HtmlResourceLimits`. | | `Fonts` | the packaged fonts | An OneRender `IFontProvider`. | | `Layout` | the default engine | An OneRender `ILayoutEngine`. | | `MaxDegreeOfParallelism` | 0 (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 ``, 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`. ```csharp 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: | Class | Value | |---|---| | `pageNumber` | The page's number. | | `totalPages` | The page count. | | `title` | The document title. | | `date` | `HtmlHeaderFooter.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. ```csharp using OnePdf.Html.Render; var options = new HtmlToPdfOptions { Margins = HtmlMargins.FromMillimeters(25), Header = new HtmlHeaderFooter { Left = "Quarterly report", Right = "", Style = "font: 9pt sans-serif; color: #444" }, Footer = new HtmlHeaderFooter { Left = "Printed ", Date = "2026-01-31", Right = "Page of ", }, }; 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 = "
Acme
" }, Footer = HtmlHeaderFooter.PageXOfY(), }; HtmlToPdf.ConvertFile("page.html", "branded.pdf", branded); ``` ## Links, outline, metadata and tags - **`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 ``, `<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. ```csharp 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: | Value | Meaning | |---|---| | `None` | A tagged PDF, not identified as PDF/UA or PDF/A. Written as a stream, so memory does not grow with the page count. | | `PdfUA1` | PDF/UA-1 (ISO 14289-1). Needs a title and a language; fails with `HtmlToPdfFailure.ProfileViolation` if a rule is broken. Built in memory. | | `PdfA2a` | PDF/A-2a (ISO 19005-2, level A). Needs a title and a language. Built in memory. | | `PdfA2aAndUA1` | Both in one file. Built in memory. | The failure message lists the rules that were broken. Both profiles need `Tagged = true`. ```csharp 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`: | Property | Default | What it does | |---|---|---| | `Enabled` | `false` | Allow fetching resources over the network for file, string and stream input. A URL input always fetches. | | `AllowPrivateAddresses` | `false` | Allow loopback, link-local, private-range and other non-public addresses. | | `RequestTimeout` | 15 s | The longest one request may take. | | `TotalTimeout` | 60 s | The longest all requests of one conversion may take together. | | `MaxRedirects` | 5 | Redirects followed for one resource; each hop is checked again. | | `UserAgent` | `OnePdf.Html` | The `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`. ```csharp 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); ``` ```csharp 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`. ```csharp 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. ```csharp 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`. | Code | When | |---|---| | `resource-refused` | A 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-missing` | A file could not be read or a network resource did not answer. | | `resource-limit` | A 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: | `HtmlToPdfFailure` | Meaning | |---|---| | `Input` | The input could not be read or is over `Limits.MaxInputBytes`. | | `Network` | The input URL itself could not be fetched. Other resources are skipped with a diagnostic. | | `Limit` | The document is too large or too deep for a limit: pages, nodes or output size. | | `ProfileViolation` | The 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. | | `Render` | The renderer could not write the file for another reason. | Argument mistakes throw `ArgumentException`; cancellation throws `OperationCanceledException`. ```csharp 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 | Type | Where | |---|---| | `HtmlToPdf`, `HtmlToPdfBatchItem` | [Happy path](#the-happy-path-htmltopdf), [batches](#batches) | | `HtmlSource` | [Inputs](#inputs) | | `HtmlToPdfConverter` | [The low level](#the-low-level-htmltopdfconverter) | | `HtmlToPdfOptions` | [Options](#options) | | `HtmlPageSize`, `HtmlMargins`, `HtmlPageOrientation` | [Pages](#pages-size-orientation-and-margins) | | `HtmlHeaderFooter` | [Headers and footers](#headers-and-footers) | | `HtmlLinkPolicy`, `HtmlOutlineOptions` | [Links, outline, metadata and tags](#links-outline-metadata-and-tags) | | `HtmlPdfProfile` | [PDF/UA and PDF/A](#pdfua-and-pdfa) | | `HtmlNetworkOptions`, `HtmlResourceLimits` | [Resources](#resources-files-and-the-network) | | `HtmlToPdfResult`, `HtmlToPdfDiagnostic`, `HtmlToPdfSeverity`, `HtmlToPdfException`, `HtmlToPdfFailure` | [Results](#results-diagnostics-and-errors) | The command line is in [cli.md](https://recursiveai.org/onepdf-html/docs/cli/); the reverse direction in [pdf-to-html.md](https://recursiveai.org/onepdf-html/docs/pdf-to-html/). <!-- https://recursiveai.org/onepdf-html/docs/cli/ --> # Command-line reference `onepdf-html` converts in both directions. Install it as a .NET tool: ``` dotnet tool install -g RecursiveAI.OnePdf.Html.Tool ``` The tool installs as a native executable on linux-x64, linux-arm64, osx-arm64 and win-x64 (no .NET runtime is started, so a short document converts in tens of milliseconds) and as a framework-dependent package on every other platform. The output is byte-identical either way. ## Which direction The direction follows the input: a `.pdf` file becomes HTML; a `.html`, `.htm` or `.xhtml` file, a URL (`http://` or `https://`) or standard input (`-`, anything that does not start with `%PDF`) becomes a PDF. To say it explicitly, put `to-html` or `to-pdf` first: ``` onepdf-html report.pdf onepdf-html to-html report.pdf --mode fixed onepdf-html to-pdf page.html -o page.pdf ``` `--help` and `-h` print the text below, `--version` prints the version. With no arguments the tool prints the help and exits with code 2. ## Help text This block is the tool's own `--help` output; a test fails if it differs, so it cannot drift. <!-- help:begin --> ```text onepdf-html: convert between PDF and HTML. onepdf-html [to-html] <input.pdf|-> [-o <output>] [options] Converts a PDF to HTML. Without -o the output is <input>.html beside the input (with --per-page, the directory <input>_pages). '-o -' writes one document to standard output. -m, --mode semantic|fixed reflowing text (default) or fixed-layout pages --pages 1-3,7,10- pages to convert, one-based (default: all) --password <text> password of an encrypted PDF --per-page one HTML file per page in a directory, plus index.html --assets inline|files images inside the HTML (default) or as files beside it --dpi <n> resolution of the fixed-layout page picture (default 144) --zoom <x> scale of fixed-layout pages (default 1) --lazy draw fixed-layout pages only when they scroll into view --fonts web|css fixed layout: web fonts built from the PDF's glyphs (default) or CSS font families by name --ocr auto|always|never recognise text from the page picture: only where a page has no usable text (default), on every page, or never --ocr-lang <tags> the document's languages, e.g. en,de or ja (default: the recogniser decides per line) -j, --parallel <n> pages converted at once (default: up to 4) -v, --verbose list every diagnostic; -q, --quiet: no summary onepdf-html to-pdf <input.html|URL|-> [-o <output.pdf|dir|->] [options] Converts HTML (a file, an http(s) URL or standard input) to a tagged PDF. Several input files need -o <directory>. Page: --page-size A4|A3|A5|B5|Letter|Legal|Tabloid|<W>x<H>[mm|cm|in|pt|px] --landscape --portrait --margin <len> --margins <top,right,bottom,left> (lengths take mm, cm, in, pt or px; default px) Running: --header <text> --header-left <text> --header-right <text> --footer <text> --footer-left <text> --footer-right <text> --page-numbers (footer "Page N of M") --header-style <css> --footer-style <css> --header-html <file> --footer-html <file> (an HTML template across the page area; images load like the document's) In a text, <span class="pageNumber"></span>, <span class="totalPages"></span> and <span class="title"></span> are replaced. Output: --links web|internal|all|none (default web) --no-outline --no-tags --profile ua1|a2a|a2a-ua1 --title <t> --author <a> --subject <s> --keywords <k> --language <bcp47> --date <ISO 8601> --no-compress Resources: --root <dir> (where relative files may be read; default the input's folder) --network (allow http/https resources) --allow-private (allow loopback and private addresses) --timeout <seconds> --max-resource-mb <n> --max-resources <n> Other: -j <n> parallel conversions for several inputs -v list diagnostics -q quiet The direction follows the input: .pdf files become HTML; .html, .htm, URLs and standard input become PDF. Exit codes: 0 done, 1 failed, 2 usage, 3 password needed, 130 cancelled. ``` <!-- help:end --> ## PDF to HTML (`to-html`) Every option maps to a property of `PdfHtmlOptions` ([guide](https://recursiveai.org/onepdf-html/docs/pdf-to-html/#options)). | Option | Property | Notes | |---|---|---| | `-o`, `--output <path>` | | Without it, `<input>.html` beside the input; with `--per-page`, the directory `<input>_pages`. `-o -` writes one document to standard output. | | `-m`, `--mode semantic\|fixed` | `Mode` | Reflowing text (default) or fixed-layout pages. | | `--pages <ranges>` | `PageRanges` | One-based, such as `1-3,7,10-`. | | `--password <text>` | `Password` | | | `--per-page` | `Layout = PagePerFile` | One HTML file per page in a directory, plus `index.html`. | | `--assets inline\|files` | `Assets` | Images and fonts inside the HTML (default) or as files beside it: `<output>_files/` for one file, `assets/` in the per-page directory. | | `--dpi <n>` | `RasterDpi` | 36 to 600, default 144. | | `--zoom <x>` | `Zoom` | 0.1 to 10, default 1. | | `--lazy` | `LazyPages` | | | `--fonts web\|css` | `Fonts` | Web fonts built from the PDF's glyphs (default) or CSS font families by name. | | `--ocr auto\|always\|never` | `TextSource` | `auto` (default) recognises text only where a page has none usable; `never` uses the PDF's own text everywhere. | | `--ocr-lang <tags>` | `OcrTextSourceOptions.Languages` | Comma-separated BCP 47 tags, such as `en,de` or `ja`. The tool includes the Latin, Greek, Cyrillic, CJK, Arabic, Hebrew and Indic models. | | `-j`, `--parallel <n>` | `MaxDegreeOfParallelism` | Pages converted at once. | | `-v`, `--verbose` | | Prints every diagnostic to standard error. | | `-q`, `--quiet` | | No summary line. | The options for headers and footers, form fields, page boundaries, annotations, limits and font mapping have no flag; use the library for those. Standard input (`-`) needs `-o <output>`. ``` onepdf-html report.pdf # report.html, reflowing onepdf-html report.pdf --mode fixed --lazy -o book.html onepdf-html report.pdf --per-page --assets files --pages 1-5 onepdf-html scan.pdf --ocr always --ocr-lang en,de onepdf-html locked.pdf --password secret -o - # to standard output cat report.pdf | onepdf-html - -o report.html ``` ## HTML to PDF (`to-pdf`) Every option maps to a property of `HtmlToPdfOptions` ([guide](https://recursiveai.org/onepdf-html/docs/html-to-pdf/#options)). | Option | Property | Notes | |---|---|---| | `-o`, `--output <path>` | | A file, or a directory when there are several inputs. Without it, `<input>.pdf` beside the input, or `<host>.pdf` in the current folder for a URL. `-o -` writes the PDF to standard output. | | `--page-size <size>` | `PageSize` | `A4`, `A3`, `A5`, `B5`, `Letter`, `Legal`, `Tabloid`, or `<W>x<H>` with an optional unit (`210x297mm`, `8.5x11in`). | | `--landscape`, `--portrait` | `Orientation` | | | `--margin <len>` | `Margins` | One length for every side. Units are `mm`, `cm`, `in`, `pt` or `px`; a bare number is px. | | `--margins <t,r,b,l>` | `Margins` | Four lengths: top, right, bottom, left. | | `--header`, `--header-left`, `--header-right`, `--footer`, `--footer-left`, `--footer-right` `<text>` | `Header`, `Footer` | A template for the centre, left or right of the margin. In a text, `<span class="pageNumber"></span>`, `<span class="totalPages"></span>` and `<span class="title"></span>` are replaced. | | `--page-numbers` | `Footer` | A footer reading "Page N of M". | | `--header-style`, `--footer-style <css>` | `HtmlHeaderFooter.Style` | CSS declarations for the text. | | `--header-html`, `--footer-html <file>` | `HtmlHeaderFooter.Html` | An HTML template across the page area; its images load like the document's. | | `--links web\|internal\|all\|none` | `Links` | Default `web`. | | `--no-outline` | `Outline = null` | | | `--no-tags` | `Tagged = false` | | | `--profile ua1\|a2a\|a2a-ua1` | `Profile` | PDF/UA-1, PDF/A-2a, or both. | | `--title`, `--author`, `--subject`, `--keywords`, `--language` | metadata | | | `--date <ISO 8601>` | `CreationDate` | Written only when given. | | `--no-compress` | `Compress = false` | | | `--root <dir>` | | Where relative files may be read; default the input's folder. | | `--network` | `Network.Enabled` | Allow `http`/`https` resources. A URL input always fetches. | | `--allow-private` | `Network.AllowPrivateAddresses` | Allow loopback and private addresses. | | `--timeout <seconds>` | `Network.RequestTimeout` | | | `--max-resource-mb <n>` | `Limits.MaxResourceBytes` | | | `--max-resources <n>` | `Limits.MaxResources` | | | `-j <n>`, `--parallel <n>` | `MaxDegreeOfParallelism` | Parallel conversions for several inputs. | | `-v`, `-q` | | Print every diagnostic; no summary line. | Several input files need `-o <directory>`. Standard input needs `-o <output.pdf>`. ``` onepdf-html page.html # page.pdf onepdf-html https://example.org/ -o page.pdf --page-size A4 --landscape --page-numbers --profile ua1 onepdf-html a.html b.html -o out/ -j 4 onepdf-html page.html --margins 25mm,15mm,25mm,15mm --header-left "Quarterly report" --page-numbers onepdf-html page.html --title Report --language en --profile a2a-ua1 cat page.html | onepdf-html - -o page.pdf ``` ## Exit codes | Code | Meaning | |---|---| | 0 | Done. Diagnostics, if any, are counted in the summary line (`-v` lists them). | | 1 | The conversion failed: an unreadable or damaged input, a limit, a file or network error, a profile violation. | | 2 | Usage: an unknown option, a missing value or input, an unreadable template. Nothing was converted. | | 3 | The PDF is encrypted and the password is missing or wrong (`--password`). | | 130 | Cancelled (Ctrl+C). Files the conversion had started are removed. | The summary and diagnostics go to standard error, so `-o -` can be piped. <!-- https://recursiveai.org/onepdf-html/docs/diagnostics/ --> # Diagnostics and limits A conversion never fails silently and never stops at the first thing it cannot do. Whatever it repaired, dropped, approximated or reduced is reported as a diagnostic, and the rest of the document is converted. ## Reading diagnostics - **PDF to HTML.** `PdfHtmlResult.Diagnostics`, `PdfHtmlConverter.Diagnostics`, `PdfHtmlPage.Diagnostics` and `PdfHtmlPageAnalysis.Diagnostics` hold `PdfHtmlDiagnostic` records: `Severity` (`Info`, `Warning` or `Error`, OnePDF's `PdfSeverity`), `Source`, `PageIndex` (zero-based, -1 for the whole document), `Code` and `Message`. On the command line, `-v` prints them to standard error and the summary line counts the warnings and errors. - **HTML to PDF.** `HtmlToPdfResult.Diagnostics` holds `HtmlToPdfDiagnostic` records: `Severity` (`Info` or `Warning`), `Code` and `Message`. Codes are stable identifiers; messages are for people and may change. ```csharp using OnePdf; using OnePdf.Html; PdfHtmlResult result = PdfHtml.Convert("report.pdf", "diagnosed.html"); foreach (PdfHtmlDiagnostic d in result.Diagnostics.Where(static d => d.Severity != PdfSeverity.Info)) { string where = d.PageIndex < 0 ? "document" : $"page {d.PageIndex + 1}"; Console.WriteLine($"{where}: {d.Code}: {d.Message} ({d.Source})"); } ``` ## PDF to HTML codes `Source` is `Converter` for every code below. Diagnostics with `Source` = `Pdf` come from OnePDF while it reads the file (a repaired cross-reference table, a wrong length, a missing object); their `Code` is empty and the message names the object number and offset. | Code | Severity | Mode | Meaning | |---|---|---|---| | `page-failed` | Error | both | A page could not be converted (a damaged page, or its output would pass `MaxOutputBytesPerPage`). It is written as an empty page with `data-error="true"`; other pages are not affected. | | `pages-out-of-range` | Warning | both | `PageRanges` reaches beyond the document; those pages were ignored. | | `link-dropped` | Warning (Info for a link to a page outside the conversion) | both | A link was dropped: it ran JavaScript, used an action other than web, mail or in-document, led outside the document or to a missing page, or its target scheme is not allowed. | | `link-unplaced` | Info | semantic | A link covers no text and was left out. | | `image-no-alt` | Info | semantic | An image has no description in the PDF and is written with empty alternative text. | | `image-skipped` | Info | semantic | An image that cannot be shown as a picture (no decoder, or an unsupported colour space) was left out. | | `image-failed` | Warning | semantic | An image could not be read and was left out. | | `image-too-large` | Warning | semantic | An image with more pixels than `MaxRasterPixels` was left out. | | `image-unusable` | Warning | fixed | An image has no usable data and was left out. | | `image-limit` | Warning | fixed | An image was left out because a decoding or size limit applies to it. | | `asset-limit` | Warning | both | An image, web font or page picture was left out because the page reached `MaxAssetsPerPage`. | | `assets-limit` | Warning | semantic | A picture of a figure or image was left out because the page reached `MaxAssetsPerPage`. | | `element-limit` | Warning | fixed | The page has more drawing operations than one page may write; the rest were left out. | | `raster-fallback` | Info (Warning when the whole page is a picture) | fixed, semantic figures | Elements were drawn from the page picture, with the number and the reason (a shading type, a pattern, a knockout group). As a warning: the page's drawing could not be interpreted, so the whole page is a picture. | | `raster-reduced` | Info | both | The page picture was drawn at a lower resolution than `RasterDpi` to stay within `MaxRasterPixels`. | | `raster-limit` | Warning | fixed | A page asked for more than 256 pieces of the page picture (a tiling pattern whose cells overlap, repeated thousands of times); the rest are left out, with their number. | | `raster-failed` | Error | both | The page picture, or a piece of it, could not be drawn, or the page is not drawn because its strokes would take too long and too much memory (the message says which bound: the segments of all stroked paths, over 1,000,000, or one stroked path of over 100,000 segments); the elements that needed it are left out. | | `text-unmatched` | Info | fixed | The page's glyphs could not be matched to its drawing, so its text is placed word by word. | | `overprint` | Info | fixed | Overprint is not simulated: content is painted as if it knocked out what is below, as the reference render does. Once per page. | | `pattern-extgstate` | Info | fixed | A shading pattern's graphics state (`/ExtGState`) is not applied. Once per page. | | `knockout-group` | Info | fixed | A knockout group inside a soft mask or another frame is drawn as an ordinary group. Once per page. | | `table-rules-limit` | Info | semantic | The page has too many rules to look for ruled tables; tables are found from the text. | | `table-rules-unavailable` | Warning | semantic | The page's drawing could not be read, so tables are found from the text alone. | ### OCR codes (`RecursiveAI.OnePdf.Html.Ocr`) | Code | Severity | Meaning | |---|---|---| | `ocr-page` | Info | A page was recognised: the number of words, the resolution, and the rule that decided. | | `ocr-dpi-reduced` | Info | The page was drawn at a lower resolution than `RenderDpi` to stay within `MaxPixels`. | | `ocr-empty` | Warning | Recognition found no text; the PDF's own text was kept. | | `ocr-language-unsupported` | Warning | The page needs recognition, but a language in `Languages` is written in a script that has no recogniser installed (add the matching `RecursiveAI.OneOcr.Models.*` package, or there is no model for it yet); those lines were left unread and the PDF's own text was kept where recognition found nothing. | | `ocr-page-too-large` | Error | The page is too large to draw for recognition within the pixel limit; its own text was kept. | | `ocr-render-failed` | Error | The page could not be drawn for recognition; its own text was kept. | | `ocr-failed` | Error | Recognition failed; its own text was kept. | ### Text-layer rules (`PdfHtmlTextSources.Assess`) These are the `Code` of a `PdfHtmlTextLayerAssessment`, not diagnostics by themselves: `text-layer-ok`, `empty-page`, `scanned-page`, `replacement-characters`, `private-use-characters`, `mojibake`, `unreadable-words`, `implausible-letters` and `text-off-ink`. [The guide](https://recursiveai.org/onepdf-html/docs/pdf-to-html/#text-sources-and-ocr) says what each means. ## HTML to PDF codes | Code | Severity | Meaning | |---|---|---| | `resource-refused` | Warning | A 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, or a relative reference with no folder or address to resolve against. | | `resource-missing` | Warning | A file could not be read, or a network resource did not answer. | | `resource-limit` | Warning | A resource, or the count or total size of resources, passed a limit in `HtmlResourceLimits`. The rest are skipped. | | `render-...` | Warning | The renderer approximated something, such as drawing a feature as an image. The text after `render-` names the kind. | ## Limits Every bound is checked before the work or allocation it guards, and none follows input depth. Defaults: ### PDF to HTML (`PdfHtmlOptions`) | Bound | Default | When it is passed | |---|---|---| | `MaxInputBytes` | 1 GiB | `PdfHtmlLimitException` when the input is opened. | | `MaxOutputBytesPerPage` | 256 MiB | The page is written empty with `page-failed`. | | `MaxAssetsPerPage` | 4,096 | Further images and fonts are left out (`asset-limit`, `assets-limit`). | | `MaxRasterPixels` | 2^26 (67 million) | The picture is drawn at a lower resolution (`raster-reduced`); an image above it is left out (`image-too-large`). | | `Limits` (`PdfLimits`) | `PdfLimits.Default` | OnePDF's bounds on decoded stream size, expansion ratio, nesting, XObject and pattern recursion, indirect objects, content operators per page, function operations, image pixels and metadata size. An object or page that passes one is skipped with a diagnostic, or fails with OnePDF's `PdfLimitException`. | | Table rules | internal | `table-rules-limit`. | | Drawing operations per page (fixed layout) | internal | `element-limit`. | | OCR `MaxPixels` | 40 million | The page is drawn at a lower resolution. | ### HTML to PDF (`HtmlToPdfOptions`) | Bound | Default | When it is passed | |---|---|---| | `Limits.MaxInputBytes` | 64 MiB | `HtmlToPdfFailure.Input`. | | `Limits.MaxResourceBytes` | 32 MiB per resource | The resource is skipped (`resource-limit`). | | `Limits.MaxTotalBytes` | 256 MiB for all resources | The rest are skipped (`resource-limit`). | | `Limits.MaxResources` | 500 | The rest are skipped (`resource-limit`). | | `MaxPages` | 100,000 | `HtmlToPdfFailure.Limit`. | | `Outline.MaxEntries` | 10,000 | Further headings get no bookmark. | | `Network.RequestTimeout`, `TotalTimeout`, `MaxRedirects` | 15 s, 60 s, 5 | The resource is skipped (`resource-missing`), or the input URL fails (`HtmlToPdfFailure.Network`). | Time is the caller's limit: pass a `CancellationToken`. <!-- https://recursiveai.org/onepdf-html/docs/architecture/ --> # Architecture How the converter is put together and where each kind of work belongs. HTML to PDF lives in `OnePdf.Html.Render`, a separate package; everything below is PDF to HTML. ## Flow ``` PDF -> PdfHtmlConverter -> per page: PageAnalyzer -> PdfHtmlPageAnalysis -> emitter -> PdfHtmlPage -> IPdfHtmlSink (open, options, size, text layer, (shared by both Semantic or fragment, single file, page selection) text source, links emitters) FixedLayout assets, file per page, after safety rules diagnostics or your own ``` `ConvertTo` converts a window of pages in parallel and hands them to the sink in page order, so memory depends on the degree of parallelism, not the page count. Output does not depend on the degree. A picture written inline (a `data:` URI) is not turned into text while its page is built: `AssetStore` puts a placeholder (a random per-conversion nonce and the picture's number) in the markup and keeps the bytes, `PdfHtmlPage` keeps the markup and the bytes together, and the file and stream sinks write the page with `WriteHtml`, which streams each picture as base64 in small pieces. `PdfHtmlPage.Html` makes the whole text on demand for sinks that want a string. `ImageBudget` bounds the pixels of pictures decoded and re-encoded at once across the pages converting in parallel, and `RasterBudget` decides from the page's strokes whether drawing the page picture is affordable (see `docs/diagnostics.md`, `raster-failed`). ## Where things go (`src/OnePdf.Html`) | Folder | Holds | Work that belongs here | |---|---|---| | root | `PdfHtml` (happy path), `PdfHtmlConverter` (per page, streaming), options, diagnostics, page ranges | API shape, coordination of pages, limits | | `Analysis/` | `PageAnalyzer`, `Tables/` (`TableDetector`, `PdfHtmlTable`), `PdfHtmlPageAnalysis`, `DocumentContext`, `PageGeometry`, `PageRasterizer` | Everything computed once per page and shared by both emitters: text, links, the display list (built on first use), page geometry, outline lookups. New facts about a page (figures, footnotes, images from the display list) are added to the analysis, not to an emitter | | `Text/` | `IPdfHtmlTextSource`, the page-text model (`PdfHtmlPageText` and below), the text-layer source | The text seam. A source returns blocks, lines and words with geometry; both emitters read only this model, so extracted and recognised text behave alike | | `Semantic/` | `SemanticEmitter` | Reflowing output: structure (headings, paragraphs, lists, tables, figures, footnotes, headers and footers), de-hyphenation and line joins, accessible markup | | `Fixed/` | `FixedLayoutEmitter` | Fixed-layout output: positioned text and fonts, vector graphics as SVG, images, raster fallback per element or page | | `Output/` | `IPdfHtmlSink` and its implementations, `AssetStore`, `DocumentShellBuilder` | Where bytes go: single file, page files, asset files or data URIs, the document head and metadata | | `Html/` | `HtmlBuilder`, `LinkPolicy`, `CssFormat` | Building markup through OneHtml and the output safety rules | An emitter implements `PageEmitter.Emit(EmitContext)`: it reads the analysis, builds one page element with the `HtmlBuilder`, puts images through `context.Assets` and reports with `context.Report`. Emitters hold no per-page state, because one instance serves every thread. `SemanticEmitter` and `FixedLayoutEmitter` share nothing but the analysis, so they can be worked on independently. `OnePdf.Html.Ocr` implements `IPdfHtmlTextSource` (see below). `OnePdf.Html.Tool` is the `onepdf-html` command; its `IConversionCommand` list (`Cli.cs`) is where each direction plugs in. ## OCR (`src/OnePdf.Html.Ocr`) `OcrTextSource` decides per page whether the PDF's own text is used. The rules are in core (`PdfHtmlTextSources.Assess`, `Text/PdfHtmlTextLayerAssessment.cs`), need no model and look at the page's text first: - **No text** and a picture with ink on it (page resources hold an image of at least 64 by 64 samples, so colour swatches and bullets do not make a scan, a 72 dpi drawing of the page has at least 0.2 % ink): a scan. - **Garbled**: over 20 % of the characters are replacement, private-use or control characters (or over 20 % of the glyphs have no Unicode value); UTF-8 read as a single-byte encoding; words that are not words: 40 % of the letters in words of 25 letters or more, more than half of the words with digits among capitals while the page has almost no lowercase, a page whose distinct words have letter proportions no language has (vowels outside 24 to 68 %, more than 15 % of words with no vowel; words in capitals only are left out so code tables pass, unless the page has no lowercase at all). - **Misplaced**: a layer of invisible text over a picture where fewer than half of up to 200 sampled words lie on ink. - Everything else is used as it is. A page with no text and no picture, or with a picture and no ink, is left alone. A page that needs it is drawn at 300 dpi (lowered to fit `MaxPixels`, 40 million by default) through the request's `RenderPage`, read by OneOcr, and its page model (pixels, y down) is mapped to points, y up: words with boxes, lines with direction, blocks with header/footer role and `Kind` (title, list, text, form field) from the recognizer's regions, and tables with row/column spans as `PdfHtmlPageText.Tables`. Font sizes come from the line's ink height (measured: 0.855 of the em). The engine loads once per source and is shared by all pages; at most `MaxConcurrentPages` (2) pages are recognised at once. The text does not depend on the degree of parallelism. The recognizer reads Latin, Greek and Cyrillic; `Languages` naming only other scripts leaves pages alone with a warning. ## Semantic output (`Semantic/`) The reflowing mode builds a small model per page (`SPage` of `SNode`s and styled `SRun`s) and renders it afterwards, so what a page break cuts can be joined first. - **Two phases.** `PageEmitter.Prepare` builds a page's model (pages of a window in parallel), `Join` moves what continues from the next page into the page before (a paragraph, a list, a table, a note; one that ends a page and goes on at the top of the next is written once), `Render` writes the DOM. A page whose content all moved up is empty, and the next page joins the last page that still has content. Output is the same at any degree of parallelism. - **Tagged pages** (`TaggedBuilder`): when any of a page's marked content is in the structure tree, the tree decides each block it covers (and the page is mixed, below): headings, paragraphs, lists (`Lbl` dropped, `LBody` kept), tables (`THead`/`TBody`/`TFoot`, `TH` scope, spans), figures with alt text, captions (next to a figure they go in its `figcaption`), notes (`Note` and `FENote`), formulas, quotes, code, links, `Span` language and `ActualText`; `/RoleMap` is followed and artifacts are dropped. Small pictures (under about two lines tall) inside a text element, or loose in a section, are inline `img` runs of that line (`SRun.Inline`); a figure drawn with paths has no image object, so its area is cut from the page picture drawn once at the raster resolution and written as the figure's image (text inside the area is part of the picture). A figure has no text of its own, so it is placed in reading order after the last text block above it that shares some of its width. - **Artifacts are not leftovers.** Words drawn inside `/Artifact` marked content (`PageObjects.IsArtifactWord`, matched by glyph origin) are page furniture the producer declared, so they never count as text the tree left out. Before this, running heads and page numbers re-emerged as paragraphs on partly tagged pages. - **Repeated table headers.** A table that goes on over a page break and repeats its header (`PageJoiner`): header rows that arrive as the continuing table's own `thead` are dropped when their text equals the first part's header, and header cells that arrive as plain blocks (each cell, or the whole row, before the table or right after it in reading order) are dropped when together they spell exactly the first part's header cells and a table follows. Then the two tables join as usual. A repeated header that differs at all is kept. - **Joins past notes and pictures.** A picture that repeats on most pages (a letterhead or logo, written as a decoration) and opens a page does not stop the paragraph before it from continuing when the text under it starts in lower case (`PageJoiner.PeelLeadingDecorations`); a picture that closes a page is peeled like a note. What stands at the foot of a page after the text that goes on (a footnote, or a short unmarked paragraph that is a caption or source line such as "Table 2." or "Source: ...") does not stop that text from continuing on the next page: the unit joins past it and the note stays at the end of its own page (`PageJoiner.PeelTail`). A paragraph that only says "Table 5 (continued)" at the top of the next page is dropped when the table joins, and kept when it does not (`DropContinuedMarks`). A caption whose halves the text layer cut apart ("Table 5." at the left, its title at the right, the table read between them) is put back in front of the table it stands over, not after it (`JoinLabels`). - **Mixed pages** (`SemanticEmitter.Mix`): text the tree leaves out (at least half of a line's characters untagged) is built by `UntaggedBuilder` for just those blocks and put among the tagged elements by reading-order index, inside the document element (which stays one node so pages still join). Notes need prose-like text and kept headers and footers are not notes. - **Untagged pages** (`UntaggedBuilder`): blocks come from OnePDF's extraction (columns, RTL, vertical text). Headings come from the outline (a line that is exactly an outline title stands alone), then from size and weight against the document's type facts (`TextStats`, a sample of at most 40 pages; heading sizes within 10 % of the tier's largest size are one tier, so a ladder of close sizes is cut where the page cuts it, and in a document of more than three sampled pages a size set on one line, unless it is the largest, is a pull quote or a sidebar title and not a level); consecutive heading lines of one level are one heading. Wrapped lines under a bullet or number stay in their item (hanging indent), and tightly set paragraph blocks that go on are one paragraph. Paragraph lines are joined, with line-end hyphens removed when the next line starts in lower case, and without spaces between CJK lines. Bullet and numbered lists nest by marker and indent and keep their start number. Small print at the foot of a page, led by a marker or set apart, becomes a note linked both ways. Pictures become figures (JPEG passed through, otherwise PNG) with a caption attached when one stands next to them. Form fields and annotations are written as text or real controls and as asides. - **Figures, labels, columns and decoration in untagged pages** (`UntaggedFigures`, `UntaggedBuilder`). A vector figure (marks from `PageObjects.Marks`: shapes, bars or lines on a common baseline, at least 50 x 36 pt and six marks, not prose, not mostly a table) is cut from the page picture and written as one image (`role=img`, `aria-label` the caption, else its labels). Its text stays in the picture and is also written as visually hidden text inside the figure (`span.figure-text`) so find and copy work and the text is not lost from content metrics; separate paragraphs of axis numbers would break reading order and are noise to assistive technology. Labels near a drawing join it; caption and note labels are kept in a block of their own. A forced line end starts a paragraph, a list item goes on in the next column's paragraph, and lists merge across columns. Text scraps drawn along a curve are decoration (`aria-hidden`). Lines the text layer kept in one block that are two to four columns wide with their columns at the same places are read column by column, one paragraph per short entry; a column of numbers (a contents list with page numbers) marks rows read across instead. Text the tree leaves out on a partly tagged page is placed inside the section it stands in. - **Layout rules for untagged text** (`UntaggedBuilder`, `UntaggedBullets`, `TextVocabulary`). A bullet drawn as a small filled shape (1.2 to 14 pt, about as wide as high, level with a line and up to 3.5 text sizes before its first word) is a list marker; browsers print list discs this way and the text layer has no character for them. A block whose indented lines each follow a line that went on because the next word did not fit is a hanging-entry block (a reference list): an indented line there continues its entry, and a line back at the margin starts the next. Three or more centred lines, one of which stops short of the column by more than the next line's first word, are separate paragraphs. On an upright landscape page with at most 400 words (a slide; not a page turned by `/Rotate`, not sideways text) the only heading is a line in the top 14 % set larger than the body text or in bold (a slide's body is large, so 4 % above it is enough), else text at least 85 % of the page's largest size in its top 40 %, level 2; other large text is body. A numbered coloured line ranks one level lower for each larger heading size the document has above it (its title). A line that is only a web or e-mail address, or a regular label followed by a bold value, is not a heading. A run of at least three centred lines inside a block is a stack of separate paragraphs, and an entry of a reference list that stands alone in its block is hanging when at least three entries of the page share its margin and indent. A column of bullets that the text layer read as a table is a list. Running heads and feet are looked for in the bands of the displayed page (a page turned by `/Rotate` keeps the band depth of the page as made). A bold short line ending in a colon is a label, not a heading. A hyphen at the end of a line is kept when the document spells the compound with it elsewhere (words of the sampled pages, `TextStats.Vocabulary`), when the hyphen is inside a chain ("end-to-"), or when both halves are words of their own (at least three letters) elsewhere; otherwise it only broke a word and goes with the join. Untuned thresholds: the bullet size and gap, the 85 % and 40 % of the slide title, the 400 words. - **Headers and footers.** The text layer of one page cannot tell what repeats, so the document sample decides: text in the top or bottom 12 % of a page that repeats, with its digits masked, on at least two sampled pages and 40 % of them. `PdfHtmlOptions.HeadersAndFooters` marks them (`doc-pageheader` / `doc-pagefooter`, the default), keeps them in the flow or drops them. - **Page boundaries.** A zero-size `doc-pagebreak` marker with the id `page-N` by default; `PdfHtmlPageBoundaries.Section` wraps each page. - **Landmark.** The pages sit in one `main`. - **Tables in untagged pages** (`Analysis/Tables`, `UntaggedTables`): `PdfHtmlPageAnalysis.Tables` finds each page's tables from its words and, when the page has two or more rows of separate cells, from the rules and fills the page draws (the display list is interpreted again only then). A table is a grid of cells with row and column spans, header rows (from bold type, a rule under the first rows, shading, larger type or text above columns of numbers) and header columns (`PdfHtmlTable.HeaderColumns`: the first column when it is bold where the rest is not, and, in a table without header rows, each later column of bold words, as in a list of facts laid out as label, value, label, value; they are `th scope="row"`). Ruled grids come from the lines; unruled tables from the gaps that stay open down a run of rows. Recognised text brings its own grid (`PdfHtmlPageText.Tables`), which is used as given. Refused: label and value lines, contents lines, bulleted lists, columns of prose (also in the unruled search: words of prose blocks and running heads are left out of it), line-number columns, chart, map and diagram grids (many curves or slanted strokes inside, or a picture under more than about a third of the grid), form grids (below), grids that are mostly empty, and small grids that have neither a header, rules between rows, shading nor numbers. A header drawn as a ruled box with the body set without rules under it is one table; footnote marks join their row; a cell's text centred over several lines belongs to the fuller row below it. Tables a page ends and the next page goes on with (same columns, header repeated or not) are one `<table>`: a repeated header shows that the earlier part's first rows are header rows even when only the later page recognised them, and a first row on the next page with an empty first column and text under cells of the last row is that row's second half (its text joins those cells). A table is also joined past what stands under it or over it: a note, a source line, a footnote or a caption under the earlier part, and a "(continued)" label over the later one, do not count as body text when the finder decides whether the table reaches the foot or the top of its page (`TableDetector.FindAsideLines`). - **Rows, wraps and refusals added after real files** (`TableDetector`). Words of one size on one baseline join a row even when East Asian and Latin words sit in boxes of different heights (a Korean cell beside "O" or "$35"). A header cell that wraps against the bottom of its row has its first line, one word alone above the row over the same cell, taken in; a last row's cell may wrap over up to six lines; wrapped lines may sit up to 1.6 em apart when the table's rows are further apart than that. A numbered heading ("7.1" and a title) right over a table is not its first row. Two rules under four points apart with no text between them bound no row. A ruled grid at most three rows deep that is mostly empty cells (squares to write a number in) is not a table. Columns that each stand in a filled box of their own (cards on a slide), when most of the columns do, are not a table; a few shaded columns in a data table are. A column's cells count words per line, so stacked single numbers do not read as running text. In tagged files, a table cell with no marked content (`TagIndex`) is kept as an empty cell, so the cells after it stay in their columns. - **Form grids.** A ruled grid whose cells are labels over room to write is a form, not a table. The test (`LooksLikeForm`, ruled grids only): the text fills under about a third of the area of the boxes it stands in (under a fifth when the grid is regular, i.e. has a cell for most of its rows and columns), and at least half of the labelled boxes are sentence-long (four words or more) or start with a field number ("1. Name", "13A. Are", "(2) Date"); a grid whose first row holds one short label per column (a questionnaire with YES and NO columns) stays a table. Evidence: 193 ruled grids in 164 real files; the rule refuses five, all the boxes of forms, and keeps the two with the same profile that are tables (a regular matrix of long cells, a questionnaire with YES and NO columns); data tables have a word or a number in each cell, or fill their boxes. What a form becomes instead: the refused grid's boxes go to the page analysis (`PdfHtmlPageAnalysis.FormBoxes`), and the builder cuts the text blocks at the box edges, so each label is a paragraph (or list item, when it starts with a number) of its own, read in the order of the page, and a line never runs from one box into the next. Fields of an AcroForm are placed as before. - **Lists, equations, strips and keys that line up like tables** (`TableDetector.Listings.cs`). Each refusal needs several signs at once, and rules or shading around the text turn most of them off. Contents lists and lists of figures (dot leaders in a few columns without a column of figures; titles with page numbers that count up in jumps; a column of section numbers that step 3.1, 3.2, 3.2.1 beside running text), a column of closing brackets (a court caption), lines of `Label: value`, equations set in parts (most cells are fragments of mathematics, few hold words or numbers), a one-row strip of non-numeric cells in the top or bottom 9 % of the page (a journal's header), a small ruled grid with plot strokes on both sides (a chart's key), a ruled grid that text runs across, and a page-sized ruled grid of numbered fields (a form). Header cells that wrap to several lines against the bottom of the header row are one header row, and a column of group labels in the second or later column spans the rows of its group when its first body row begins a group. `tools/OnePdf.Html.TableScan` lists the tables found on each page of a corpus so the share of pages with a table that is not one can be compared between builds. - **Sideways text** (`TableFrame`, `PdfHtmlTextWord.Turn`). Each word carries the quarter turn of the direction its glyphs run in on the displayed page (0 upright, 1 downward, 2 upside down, 3 upward; vertical writing counts as upright). A page `/Rotate`d over upright content, or a wide table drawn turned on an upright page, has all its text in one sideways direction. The table finder searches each direction that has at least six words in a frame turned to read it: words, rules, fills, pictures and art are mapped into the frame (the text runs left to right and the next line is below, whatever the page's axes are), the same detector runs, and the table's bounds and cell bounds are mapped back to page space. Rows and columns are those a reader sees; a table of one frame never joins one of another (`PdfHtmlTable.Turn`). Upright text is searched exactly as before. What the frame does not reach: the headings, lists and paragraph rules of the reflowing builder still read line geometry in page space, so a heading set sideways is written as a paragraph (its size is taken from the line's box, which is turned); lines of sideways text are never taken for scraps of one line drawn along a curve, which hid them as decoration. - **Limits of the table detector:** a continuation page with one leftover row and no header is joined only when that row is one line standing alone at the top of its page, with words in at least two of the earlier table's columns and at least half of them (`PdfHtmlTables.LoneRow`; a row of several lines is not); a column filled in under a quarter of the rows can merge into a gutter; row spans are only inferred in the first column of unruled bodies; header detection needs bold, a rule, fill, size or numbers to go on; diagrams drawn as boxes of text and lists set in two columns can still be taken for tables. `PdfHtmlTables.Continues`, `Merge` and `Flow` place and join them. - **Fonts** (`PdfHtmlOptions.Fonts`). `WebFonts` (default): each PDF font becomes a WOFF2 subset, built once per document (a prepass collects the characters every page uses, merged in page order; `SemanticFaces`, reusing the fixed-layout glyph capture and font builder) whose characters are the Unicode text the extraction read from the glyphs, so the HTML text stays the extracted text and only its look is the PDF's; runs are wrapped in a class that names the face, with the standard fallback family after it, and the face's own weight and slant are not added to again by `strong`/`em`. The rules sit in the document shell's `style` element, with the font data inline or as `font-<hash>.woff2` files written with the first page (page-per-file pages refer to `assets/font-*.woff2`), so a face used on many pages is written once; family names are `wf0`, `wf1`, ... A single page converted alone (`ConvertPage`) keeps page-local faces in its own `style` element. `CssFamilies`: no font is written; runs use the generic family mapping of `FontMapping`. ## Output safety - Every string that comes from a PDF reaches the output through OneHtml's serialiser (`HtmlBuilder`). No code writes markup built from document text. - `LinkPolicy` is the only place a link target is accepted: `http`, `https` and `mailto`, with no control characters. Internal links become page anchors or page-file URLs from the sink, and only for pages in the conversion. - Emitters write numbers through `CssFormat` and never put document text in a `style` value. - No script, no remote reference. A page that fails (a damaged page, a limit) is written empty with an error diagnostic; it does not stop the document. ## Determinism No emitter reads the clock, the culture or thread identity. Numbers are formatted by `CssFormat`. Asset names come from the page number and a counter. Diagnostics are ordered by page, and OnePDF's own by object number and offset. ## Known gaps in this version - Semantic: a figure's picture includes the text inside its area, a tagged table whose repeated header is not recognised as page furniture on a short last page can stay split from its first part, and the ordering of text the tree leaves out among sections (not the document element) is coarse. - Fixed layout: vector content, text and images are drawn as markup in painting order; no page picture is used unless a diagnostic with code `raster-fallback` says which element and why. Elements that fall back (cropped from one render of the page, PNG, or JPEG for large pieces): mesh shadings (types 4 to 7: browsers have no mesh gradient, and tessellating into triangles leaves seams and per-pixel colour differences), function-based shadings, radial shadings whose inner circle is not extended, tiling patterns whose cells overlap, and image masks painted with a pattern. If a page's display list cannot be built, the whole page is a picture. - Fixed layout, constructs a browser can't composite (the reference is the OneImage.Pdf render): - **Knockout groups** (`/K true`, ISO 32000-2 11.4.6.2): CSS and SVG groups never knock out. A knockout group whose content is painted with alpha, a blend mode or a soft mask (or holds a non-opaque group) is cut from the page picture, `raster-fallback` reason `knockout group`; with only opaque content knocking out changes nothing and the group is written as markup. Inside a soft mask, a pattern cell or an enclosing alpha, blend or mask frame the picture can't stand in, so the group is drawn as an ordinary group and reported once per page (`knockout-group`). - **Overprint** (`/OP`, `/op`, `/OPM`, 8.6.7) is not simulated, as in the reference render: content knocks out what is below (reported once per page, `overprint`). - **A soft mask's backdrop colour** (`/BC`) is written: the mask gets a page-sized rectangle in that colour under its content, so unpainted areas take the backdrop's luminosity (black by default), also under a transfer function. - **A shading pattern's `/ExtGState`** is not applied, as in the reference render (reported once per page, `pattern-extgstate`). - A soft mask's transfer function (`/TR`) is written as an SVG filter on the mask content. The reference render of the bridge version in use ignores `/TR`, so where a file has one the page differs from it by design; the markup follows the specification. - Fixed layout: only images are shared between pages (written once per document); clip paths, patterns and gradients are repeated on each page. Large opaque non-JPEG images are written as PNG. - Fixed-layout text (`Fixed/Text/`): the page's text is written once, as real text. Each line of the extraction is one absolutely positioned, transformed element holding spans of the extracted Unicode; the spans are set in WOFF2 fonts built (OneFont `FontBuilder`) from the glyph shapes the PDF draws, whose character map leads each character to its shape and each ligature or cluster to its glyph (`MapSequence`, GSUB `ccmp`/`rlig`). A character that leads to different shapes in one PDF font (Arabic forms, stylistic variants) gets a font of its own. A glyph the extraction has no text for is mapped to a private-use character in a span that is `aria-hidden` and `user-select:none`; when the text layer has no word for the glyph at all (recognised text stands in for the layer, an annotation's appearance, a glyph drawn twice) the character is generated content (`data-g` and `::before`), so it is drawn but never part of the page's text. Lines sit in one container that is not a stacking context, in reading order; the composer gives layers even and text odd `z-index` values so painting order comes from stacking. Text that must stay inside a soft mask, group, blend mode or non-rectangular clip is written in that frame instead, at its painting position. Text that is not drawn by the text itself (invisible, stroked, clipping, Type 3, pattern-filled) is transparent text in a font that carries only advances. Words that run against their line's direction (numbers in right-to-left text) are spans that set their own direction, so glyph order and copied text both stay logical. `PdfHtmlOptions.Fonts = CssFamilies` writes no font: words are set in CSS families chosen from the font name and each word is placed where the PDF has it. - The page picture is drawn by a bridge that parses the file again for each page. - Page pictures are PNG only. ## HTML to PDF (`src/OnePdf.Html.Render`) ``` HtmlSource -> HtmlToPdfConverter -> read input (ResourceLoader: file root | HttpFetcher) -> facts (title, lang, meta) -> PageCss (@page: size, margins, margin boxes) -> OneRender HtmlPdf (layout for print, pages, tagged PDF, outline, links, PDF/UA or PDF/A) -> stream | file | bytes ``` The package is a thin layer: OneRender lays the HTML out and writes the PDF; this package decides what the document may load and fills in what a converter API offers. - **Page options** become one `@page` rule appended before the last `</body>`, so it follows the document's own style sheets and wins over them for the properties the caller set. Properties left null defer to the document's rules, then to A4 with 0.5 inch margins. - **Headers and footers** are templates turned into CSS page-margin boxes: text becomes quoted strings (escaped, `<` as `\3C`, so a template cannot close the style element), the classes `pageNumber` and `totalPages` become `counter(page)` and `counter(pages)`, `title` and `url` become text. OneRender's own pagination fills the counters. - **HTML templates**: a template that holds more than text (`TemplateMarkup.IsRich`: an element other than br, p, div, span, b, i, u, em, strong, small, sub or sup, or one of those with `class`, `style` or `id`) and `HtmlHeaderFooter.Html` are parsed and written out again (scripts, style, iframes, event attributes dropped; text and attribute values escaped; placeholder elements become empty spans filled by `counter(page)`/`counter(pages)` rules, or spans holding the title, URL or caller's date) inside a `div[data-onepdf-hf]` placed at the start of the body. A rule gives that div `position: running(name)` and the margin box `content: element(name)`; `Html` uses the centre box made as wide as the page area. At the start of the body so OneRender assigns it to page 1. Images are loaded by the same resource loader as the document's. - **Resources.** OneRender never fetches; it asks `ResourceLoader` for each address. A caller hook is asked first. `file:` addresses must lie below the input's folder after `..` is resolved and links are followed. `http`/`https` need the network to be on (or a URL input); `HttpFetcher` follows redirects by hand (each hop checked), caps bytes and time, and checks the address of the connection it makes, which also covers names that change their answer. The host and port of a URL the caller named are trusted; everything else non-public is refused unless allowed. Refusals and limit hits are diagnostics, and the document goes on without the resource. - **Outline, link policy, profiles** live in OneRender (`HtmlPdfOptions.Outline`, `PdfOutputOptions.Links`, `PdfOutputOptions.Profile`); this package maps its options to them. - **Batches** run one converter per input on `Parallel.For`; the converter holds no state between calls, so each result equals its one-by-one conversion. <!-- https://recursiveai.org/onepdf-html/docs/changelog/ --> # Changelog All notable changes are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] ## [1.0.0] - 2026-12-04 First release of OnePdf.Html: PDF to HTML (semantic and fixed-layout output, with OCR for scanned pages) and HTML to PDF, as a library and the `onepdf-html` tool. ### Added - `RecursiveAI.OnePdf.Html`: `PdfHtml.Convert` and the per-page `PdfHtmlConverter`, with semantic and fixed-layout output, page ranges, passwords, limits, cancellation, parallel pages written in order, output as one file or a file per page with images inline or as files, and diagnostics. - Semantic output: tables in untagged pages (ruled, unruled, partly ruled, spans, header rows and columns, continued over pages, right-to-left and CJK), also from recognised text; structure from tags or from layout (headings, nested lists, tables the tags describe, figures, captions, footnotes, form fields, annotations), de-hyphenated paragraphs, headers and footers marked, kept or dropped, and paragraphs, lists and tables joined across page breaks. - Semantic output: inferred structure on untagged pages (headings by tier, hanging-indent list items, tight paragraph merges, notes only from prose-like small print, kept headers and footers are not notes), tagged and untagged text mixed per block on partly tagged pages, small pictures inline in their line, vector figures cut from the page picture, and the PDF's fonts as WOFF2 subsets built once per document and shared by all pages, in the document head or as `font-<hash>.woff2` files (`PdfHtmlOptions.Fonts`, `WebFonts` default, `CssFamilies` for generic families), so documents and CJK pages stay small. - Semantic output, untagged pages: tables whose text runs sideways on the displayed page (page `/Rotate` of 90, 180 or 270 over upright content, or a table drawn turned on an upright page) are found as the table a reader sees, ruled or not, with the rows, columns, spans and header rows of the upright table. Generated test pages for every turn and look (`testdata/eval/heldout/h-rot*`, `h-side*`) are part of the held-out set. - Semantic output, untagged pages: a bullet the page draws as a small filled shape (a browser's list disc) makes a list item; an entry whose first line stands at the margin and whose other lines are indented (a reference list) is one paragraph; the centred lines of a title block or an address are paragraphs of their own; a slide (a landscape page with little text) has one title, the largest text near its top, and its other large text is not a heading; a bold line ending in a colon introduces something and is not a heading; a hyphen at the end of a line stays when the document spells the compound with one (or both halves are words of their own elsewhere) and goes when it only broke a word. - Semantic output: a table, paragraph or list that a page break cuts continues past a footnote, a source line or a caption at the foot of the page, and past a "(continued)" label or a letterhead picture at the top of the next; a single table row left at the top of the next page joins its table; a caption read after its table is put back in front of it, and a caption set wider than its small picture stays with it. - Semantic output, untagged pages: numbered items set in blocks of their own (a reference list cut by figures, steps separated by displays) stay list items when the page holds the neighbouring number at the same margin; a drawing does not repeat a running head, foot or page number as its hidden text. - Semantic output, untagged pages: sub-lists nest under their bullets, list items that wrap are joined, arrow bullets (repeated at one left edge) make list items, a chart title beside a list is kept as text, two-column text reads by column with each caption kept with its picture, centred author lines are joined, and a picture the document's own pages draw on most pages (a letterhead) is decoration. - Semantic output: contents lists, lists of figures, numbered definitions, court captions, equations set in parts or in symbol fonts, a few words under a wide ruled frame, journal header strips and chart keys are not taken for tables, and neither are whole-page forms ruled into numbered boxes. Header cells that wrap over several lines are one header row, and group labels in a later column span their rows in tables without rules. - Semantic output: the ruled boxes of a form are not written as a table; each box's label is a paragraph (or numbered list item) of its own, in page order. - Semantic output, untagged pages: vector figures are cut from the page picture with their text kept as visually hidden text, labels join their drawing, columns of short entries are read column by column, curved text scraps are decoration, and left-over text on partly tagged pages is placed inside the section it stands in. - Fixed-layout output (`PdfHtmlMode.FixedLayout`): one box per page that looks like the page. Text is real and selectable, positioned per glyph run in the PDF's own glyph shapes, rebuilt from the outlines as WOFF2 subsets whose character map leads the extracted Unicode to each glyph, so copied text is the extracted text. Vector content is SVG (paths, clips, gradients, patterns, groups, soft masks and blend modes); images are PNG, with JPEG passed through; what cannot be expressed comes from a page picture, per element or per page, with the text still selectable over it. One file or a file per page, assets inline or as files, `Zoom`, and `LazyPages` (CSS only, no script). - `IPdfHtmlTextSource`, so a page's text can come from the PDF or from recognition. - `RecursiveAI.OnePdf.Html.Ocr`: `OcrTextSource` recognises text with OneOcr for scanned pages and pages whose text layer is garbled or lies off the ink, in both modes, and hands over tables with their grid. `OcrMode` (never, auto, always), render resolution, pixel limit, languages, concurrency cap. Core gained `PdfHtmlTextSources.Assess` (the deterministic text-layer rules), `PdfHtmlPageText.Tables` and `PdfHtmlTextBlock.Kind`. The tool takes `--ocr auto|always|never` and `--ocr-lang`. - OCR for Chinese, Japanese (also vertical lines), Korean, Arabic, Persian, Urdu, Hebrew and nine Indic languages. Add `RecursiveAI.OneOcr.Models.Cjk`, `.Arabic`, `.Hebrew` or `.Indic` to the application; the default engine uses the models they install beside it. `OcrTextSourceOptions.Languages` and the tool's `--ocr-lang` pass the document's languages to the recogniser, and a language whose model is not installed gives `ocr-language-unsupported`. The `onepdf-html` tool includes all four families. Measured: scanned CJK pages 0.4 % text error (48.8 % with the Latin models alone), Arabic and Hebrew 2.9 % (89.7 %); Latin scans read the same with the family models installed. - `RecursiveAI.OnePdf.Html.Render`: HTML to PDF. `HtmlToPdf` (string, file, stream or URL in; bytes, stream or file out; batches in parallel) on `HtmlToPdfConverter` and `HtmlSource`. Options: page size, orientation and margins, header and footer templates with page number, total and title, link policy, an outline from the headings, metadata, tagging, PDF/UA-1 and PDF/A-2a. Files are read only below the input's folder; the network is off unless the input is a URL or `HtmlNetworkOptions.Enabled` is set, with `http`/`https`, size, count, time and redirect limits, and non-public addresses refused unless allowed. No script runs. - `RecursiveAI.OnePdf.Html.Tool`: the `onepdf-html` command. - `onepdf-html`: converts HTML (a file, a URL, standard input or several files) to PDF with flags for the options; the input is found among the arguments, so options and their values may come first. - Test pages for the table finder's refusals (grids drawn as art, line numbers down a margin, forms) and rules (cells that wrap or are centred, raised note marks) and for joins past notes, generated by `OnePdf.Html.Eval gen --set refusals`. - Web fonts built from open-licence outlines (the substitutes for fonts a PDF does not embed) carry the source font's copyright line, the SIL Open Font License 1.1 notice and the license URL in their `name` table (IDs 0, 13 and 14), in both modes. The converter asks for the `RecursiveAI.OnePdf.Fonts` substitutes before any installed font, so the output does not depend on the machine's fonts. - Documentation: a guide for each direction (`docs/pdf-to-html.md`, `docs/html-to-pdf.md`), the command-line reference (`docs/cli.md`, which quotes the tool's own help text and is checked against it), a list of diagnostic codes and limits (`docs/diagnostics.md`), a package readme for each package, and complete third-party notices. Every C# sample in the README and the guides is compiled and run by `tests/OnePdf.Html.Docs.Tests`. - `RecursiveAI.OnePdf.Html.Tool` installs as a native executable on linux-x64, linux-arm64, osx-arm64 and win-x64 (platform-specific tool packages, with a framework-dependent `any` package for other platforms). A small fixed-layout document converts about six times faster than with the framework-dependent tool, because there is no runtime start and no code compilation. Output is byte-identical. - `Render`: header and footer templates may be HTML. A template with an image, a table, a link or an element with its own `class` or `style` is drawn as HTML in its margin box, carried by a CSS running element; `HtmlHeaderFooter.Html` is one such template across the whole page area (a logo with a title beside it, a two-column footer). Images in templates load through the same rules as the document's (the input's folder; the network only when enabled). A `date` placeholder shows `HtmlHeaderFooter.Date`, and nothing when the caller gives none. Scripts, event attributes and style elements in a template are dropped. Text-only templates are drawn as text. The tool takes `--header-html <file>` and `--footer-html <file>`. ### Limits and robustness - A page with too many stroked segments for its picture to be drawn in reasonable time and memory (over a million flattened segments together, or over a hundred thousand in one path) is not drawn: the converter counts the segments from the page's own content, with no clock, and past the bound (`RasterBudget`) reports `raster-failed` and goes on without the picture. Text, links and vector output are unaffected; a figure that needed the picture is left out. The bound is the same for every run and machine. Strokes that lie over themselves (plots drawn as a staircase of thousands of tiny steps) are drawn. - Memory stays flat with document size: a picture written inline reaches the output in pieces as the sink writes, never held as one base64 text, so a document of 86 pages and 137 MB of HTML with inline pictures converts in 0.74 GB (semantic) and 0.66 GB (fixed layout) on the command line. `PdfHtmlPage.Html` makes the whole text when read, so a custom sink sees the complete page. The pictures decoded and re-encoded at once are bounded across the pages converting in parallel (12 megapixels), and colour conversion works in strips. - Fixed-layout output: a page that sends thousands of elements to the page picture (a tiling pattern whose cells overlap) cuts at most 256 pieces from it and reports the rest as `raster-limit`. - A figure whose page picture cannot be drawn (a page whose transforms leave the finite range) is left out with a `raster-failed` error, in both modes, and the conversion goes on. - Fixed-layout output: a glyph width beyond what the font tables can store, or a noncharacter or out-of-range code point as a glyph's text, affects only that glyph, not the file. - The command-line tool collects garbage eagerly (no background collections, memory conservation on), so its peak memory follows the live data instead of the allocation rate. - Semantic output, untagged pages: lines of text that run sideways on the displayed page (a page turned by `/Rotate`, a table drawn along the long edge of an upright page) are paragraphs, not decoration. - Fixed-layout output: glyphs with no Unicode value that the page's text layer has no word for (a broken layer under recognised text, form field and annotation appearances, glyphs drawn twice) are drawn from generated content, so they are not part of the copied text, and a page with a broken text layer reads as the recognised text alone. - A page whose only pictures are smaller than 64 by 64 samples (colour swatches, bullets) is not taken for a scan, so it is neither drawn for the ink check nor read by the recogniser. [Unreleased]: https://github.com/recursive-ai-oss/onepdf-html-csharp/compare/v1.0.0...HEAD [1.0.0]: https://github.com/recursive-ai-oss/onepdf-html-csharp/releases/tag/v1.0.0