---
title: "PDF to HTML"
url: https://recursiveai.org/onepdf-html/docs/pdf-to-html/
description: "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…"
version: "1.0.0"
source: https://github.com/recursive-ai-oss/onepdf-html-csharp/blob/166c1177813f222de669a1f456eeb495b18e6103/docs/pdf-to-html.md
---

# 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/).
