This is the abridged developer documentation for Ream
# Convert DOCX, XLSX, PPTX & PDF in the browser
> A TypeScript library that converts Word, Excel, PowerPoint and PDF (legacy .doc, .xls, .ppt too) to PDF, SVG, HTML, Markdown, DOCX or XLSX in the browser.
MITTypeScriptBrowser · Node · Edge Read any office document.\ Convert it to anything. ======================= Ream parses Word, Excel, PowerPoint and PDF — including the legacy .doc / .xls / .ppt — and writes PDF, SVG, HTML, Markdown, DOCX or XLSX. In the browser, straight from the ECMA-376 and ISO 32000 specifications. No LibreOffice, no headless Office, no commercial SDK. [Getting started](/guides/getting-started/)[Try it in the browser](/playground/)[View on GitHub](https://github.com/alex-krassavin/reamkit) Reads · seven formats in .docx.xlsx.pptx.pdf.doc.xls.ppt Ream.parse()→ FlowDoc Writes · six formats out .pdf.svg.html.md.docx.xlsx ## Built from the spec, in the browser One parse, any target — the architecture in six pieces. ### From the spec Built directly from ECMA-376 (OOXML) and ISO 32000 / 19005 (PDF / PDF/A) — not a wrapper around LibreOffice, headless Office, or any commercial SDK. ### Browser-first Pure TypeScript on Uint8Array in and Uint8Array out — zero node:\* imports on the conversion path. The same code runs in the browser, Node, serverless and edge. ### Seven formats in The OOXML trio plus .pdf and the legacy binary .doc / .xls / .ppt (97–2003). A PDF comes back as the document it was — its columns, tables, figures and its own faces — and a password-protected package opens with its password. ### Real typography Type0 + CIDFontType2 embedding with subsetting, Knuth–Plass line breaking, Liang hyphenation, OpenType ligatures and kerning, BiDi and Arabic joining. ### Compliant PDF PDF/A-1/2/3 (a/b/u) and PDF/UA-1 — all veraPDF-validated — plus tagged PDF, digital signatures and AES-256 encryption. ### One parse, any target Ream.parse(bytes) reads once into a format-neutral interlayer; convert renders PDF, SVG, HTML, Markdown, DOCX or XLSX from it. Formats plug in as adapters. [Docs for AI: llms.txt](/llms.txt)[Skills for AI agents](/guides/ai-agents/)Built from ECMA-376 & ISO 32000
# Getting started
> Install Ream from npm and convert your first Word, Excel, PowerPoint or PDF document to PDF, HTML or Markdown — in the browser or in Node.js.
Ream reads Word, Excel, PowerPoint and PDF — the modern `.docx` / `.xlsx` / `.pptx` / `.pdf` and the legacy binary `.doc` / `.xls` / `.ppt` — and converts any of them to PDF, SVG, HTML, Markdown, DOCX or XLSX, implemented from the ECMA-376 and ISO 32000 specifications. It works on `Uint8Array` in and `Uint8Array` out, so the same code runs in the browser, Node.js, serverless and edge runtimes. ## Install [Section titled “Install”](#install) The package is published as `reamkit`:
```sh
npm install reamkit
```
Runtime dependencies are minimal: `fflate` (ZIP/Deflate) and `fast-xml-parser`. ## Convert a document [Section titled “Convert a document”](#convert-a-document) Parse once into the format-neutral interlayer, then convert to any target. The format — any of the seven — is sniffed from the bytes. No fonts to wire up — an open metric-compatible substitute (Arimo for sans, Tinos for serif, Cousine for monospace, plus Carlito/Caladea for Calibri/Cambria — the same families LibreOffice substitutes, Cambria’s Cyrillic and Greek borrowed from Noto Serif) is fetched automatically based on the document’s referenced fonts. Those five are Latin, so a document that holds **Japanese, Korean, Chinese, Arabic, Hebrew, Thai or geometric symbols** also gets a Noto face for that writing system — one weight, fetched only for the scripts the document actually uses, and a font the document **embeds** is used ahead of any of them:
```ts
import { Ream } from 'reamkit';
// e.g. from an or a fetch() — anything that yields bytes.
const bytes = new Uint8Array(await file.arrayBuffer());
const doc = Ream.parse(bytes); // docx, xlsx, pptx, pdf, doc, xls or ppt — sniffed
const pdf = await doc.convert('pdf'); // async — fetches a font if needed
const svg = await doc.convert('svg'); // same parse, different target
const html = await doc.convert('html'); // flowed HTML — needs no fonts at all
const md = await doc.convert('md'); // GitHub-Flavored Markdown — same, narrower
const docx = await doc.convert('docx'); // WordprocessingML back out
const xlsx = await doc.convert('xlsx'); // SpreadsheetML back out (xlsx source)
// Hand the bytes to the browser: preview, download, upload, …
const url = URL.createObjectURL(new Blob([pdf], { type: 'application/pdf' }));
window.open(url);
```
## Open a password-protected document [Section titled “Open a password-protected document”](#open-a-password-protected-document) An encrypted `.docx`/`.xlsx`/`.pptx` is not a zip: ECMA-376 §2.3 puts the whole package inside an OLE container, so it has to be decrypted before anything can read it. Pass the password to `parse` and that happens for you — both Office schemes (the 2007 standard one and the agile one 2010 and later write), and the same option carries a PDF’s user or owner password:
```ts
const doc = Ream.parse(bytes, { password: 'letmein' });
const pdf = await doc.convert('pdf');
```
Every scheme stores a verifier, so a wrong password is refused rather than producing rubbish — as `WrongPasswordError`, which you can catch by type and so tell apart from a corrupt file:
```ts
import { Ream, WrongPasswordError } from 'reamkit';
try {
Ream.parse(bytes, { password });
} catch (e) {
if (e instanceof WrongPasswordError) promptAgain();
else throw e;
}
```
A document that needs a password and gets none throws as well, saying so. To ask before that happens — to put up a password prompt instead of an error — `isEncryptedPackage` answers from the bytes alone for an Office package:
```ts
import { isEncryptedPackage } from 'reamkit';
const password = isEncryptedPackage(bytes) ? await promptForPassword() : undefined;
const doc = Ream.parse(bytes, { password });
```
## Bring your own fonts (no network) [Section titled “Bring your own fonts (no network)”](#bring-your-own-fonts-no-network) To embed specific fonts — or to avoid the network entirely — pass the font bytes in. `convert` then performs zero I/O:
```ts
const fonts = {
regular: new Uint8Array(await fetch('/fonts/MyFont-Regular.ttf').then((r) => r.arrayBuffer())),
bold: new Uint8Array(await fetch('/fonts/MyFont-Bold.ttf').then((r) => r.arrayBuffer())),
};
const pdf = await Ream.parse(bytes).convert('pdf', { fonts });
```
## The document object [Section titled “The document object”](#the-document-object)
```ts
const doc = Ream.parse(bytes);
doc.format; // 'docx' | 'xlsx' | 'pptx' | 'pdf' | 'doc' | 'xls' | 'ppt'
doc.flow; // the parsed interlayer tree (paragraphs, tables, images, …)
doc.losses; // anything dropped/degraded while reading
const { bytes: out, losses } = await doc.convertWithReport('pdf', { fonts });
await doc.convert('pdf', { fonts, strict: true }); // throw on the first loss
```
## Next steps [Section titled “Next steps”](#next-steps) * [Examples](/guides/examples/) — PDF/A, signatures, font providers, SVG preview, recipes. * [Concepts](/guides/concepts/) — the pipeline and the interlayer. * [AI agents](/guides/ai-agents/) — skills that teach Claude Code, Codex, Cursor and Copilot to use Ream, and the docs as plain text.
# Concepts
> How Ream converts a document: readers build one document model from the ECMA-376 and ISO 32000 specs, and writers set it as PDF, SVG, HTML and more.
Ream is written **from the specifications**, not as a wrapper. There is no LibreOffice, headless Office, ZetaJS/WASM, or commercial SDK underneath — the conversion is its own code. Existing implementations (the LibreOffice source, Apache POI) are read only as a reference for the edge cases, never used as a dependency. ## The pipeline [Section titled “The pipeline”](#the-pipeline) A conversion walks the same stages a word processor would, each mapped to a section of the standard: 1. **OPC unpacking** (ECMA-376 Part 2) — the `.docx`/`.xlsx` is a ZIP of XML parts. `fflate` unzips; `fast-xml-parser` parses. (ZIP and XML are the only “incidental” pieces we don’t write ourselves — they are separate standards, not the task.) 2. **OOXML parsing** (Part 1) — WordprocessingML (§17), SpreadsheetML (§18), DrawingML (§20), OfficeMath (§22) become a typed, in-memory **document model**. 3. **Style cascade** (§17.7) — `docDefaults` → named styles → direct formatting are resolved into the effective properties of every run, paragraph and cell. 4. **Layout** — the box model is laid out into lines and pages: **Knuth–Plass** paragraph breaking, **Liang** hyphenation, table auto-layout, the spreadsheet print model (gridlines, print area, fit-to-page, repeated titles, page breaks) — or, for a screen, Excel’s window: each sheet whole, with no paper to fit. 5. **Text shaping** — Unicode text becomes positioned glyphs: OpenType ligatures and kerning (GSUB/GPOS), BiDi reordering (UAX #9), Arabic cursive joining. 6. **PDF writing** (ISO 32000) — content streams, the cross-reference table, Type0 + CIDFontType2 font embedding **with subsetting**, image XObjects. Optionally tagged PDF, a PDF/A profile, or a digital signature. ## The interlayer (FlowDoc) [Section titled “The interlayer (FlowDoc)”](#the-interlayer-flowdoc) The stages above are decoupled by an intermediate representation: readers parse a format into a **FlowDoc** (a semantic, format-neutral document tree — no pages or coordinates yet), the layout turns it into positioned pages (the frozen page model: `PageItem`s in a top-left, point-unit frame), and writers emit a target format from there:
```plaintext
bytes → reader → FlowDoc → layout → pages → writer → bytes
```
`Ream.parse` runs a reader once and hands you the FlowDoc (`doc.flow`); every `doc.convert` renders from it without re-reading the source. A workbook keeps its grid beside it and projects it again for a screen: HTML and SVG get each sheet as Excel’s window shows it, PDF its printed pages. New formats plug in as `DocumentReader`/`DocumentWriter` implementations (the `@experimental` interfaces) instead of new end-to-end converters — the SVG preview writer (consuming positioned pages) and the HTML and Markdown writers (consuming the FlowDoc directly, no layout or fonts involved) are exactly such adapters. The same seam runs in reverse for **PDF input**. A PDF reader is just another `DocumentReader`, but inbound it *reconstructs* a FlowDoc rather than parsing a clean tree: a tagged PDF is rebuilt from its logical structure tree, an untagged one heuristically from glyph positions (lines by baseline, paragraphs by spacing and indent, the page read for its own gutters — as many columns of prose as it was set in, breaking to the next column and balancing the last page where the page does, blocks set side by side read down each on its own, a running head or foot made the section’s header or footer with its page number as a field, a ruled grid rebuilt as a table, a gap no word space could be — or one that lands on a stop the lines around it share — written as a tab on that stop, consecutive lines standing on the same stops rebuilt as a table of their own, a table set across the columns read whole, a code listing kept line for line, a drawing kept with the labels set on it as one figure, and an index’s hanging entries an entry apiece). Which reading it gets is the FILE’s to decide — a paper is mostly lines and re-flows, a form is mostly marks and keeps its page, with nothing for a caller to configure. The result is an ordinary FlowDoc, so `Ream.parse(pdfBytes)` converts onward to HTML, Markdown, docx or a re-laid PDF like any other source. A PDF names FACES (`Inter-SemiBold`, `ArialMT`), which is what a layout finds the document’s own program by; beside them the FlowDoc carries the family each face belongs to (`faceFamilies`, a `FaceFamily` apiece), the name a writer that hands the text to another program — a `.docx` — gives it, with the kind of face it is for a program that has to substitute. And it carries the faces themselves (`faceOutlines`): the outline of every character each face drew and the advance the page set it at, its kerning pairs and the ligatures the page drew, from which the `.docx` writer rebuilds a TrueType font and embeds it where its licence lets it — so the document is set in the type it was set in, on a machine that has none of its fonts. ## Bytes in, bytes out [Section titled “Bytes in, bytes out”](#bytes-in-bytes-out) The public API is deliberately small and I/O-free: `Uint8Array` in, `Uint8Array` out. Ream never touches the filesystem or the network on the conversion path (zero `node:*`, `Buffer`, `process` or `__dirname` imports), which is what lets the identical code run in a browser tab, a Node server, a Lambda, or an edge worker. How the bytes reach you — a `File`, a `fetch`, `fs` — is your call. ## You supply the fonts [Section titled “You supply the fonts”](#you-supply-the-fonts) PDF embeds the fonts it draws with, so a converter needs font bytes. Ream’s model is **caller-supplies-fonts**: the synchronous API takes the TTF bytes you pass; the async API, as a convenience, fetches an open metric-compatible substitute (Arimo, Tinos, Cousine, plus Carlito/Caladea for Calibri/Cambria — the same families LibreOffice substitutes, Cambria’s Cyrillic and Greek borrowed from Noto Serif) based on the document’s referenced fonts, and a Noto face for any writing system those five cannot draw — Han, Kana, Hangul, Arabic, Hebrew, Thai, geometric symbols — asked for only when the document holds that script. A font the document embeds is used ahead of both. There are no bundled fonts on the main path — the library renders faithfully with whatever font you give it. ## Renderer parity [Section titled “Renderer parity”](#renderer-parity) Ream is a *correct* typesetter — it lays out faithfully for the font it’s given, not a clone of any one program. A document Word sets — a `.docx` or a `.doc` — is laid out by Word’s own rules, each measured in Word: its lines as tall as Word sets its faces, two paragraphs the larger of their spacings apart, widow control, a heading kept with what it heads, table borders that take their room. A workbook is drawn by Excel’s: its columns in the digit Excel counts them in, its tints in Excel’s arithmetic, its tables in the styles Excel builds in — each set beside Excel’s own PDF of a workbook made to ask it. When you need the page to track a specific renderer instead, `convert('pdf', { layoutProfile })` switches how text is measured, broken into lines and stacked to match it: `'word'` for Microsoft Word, `'libreoffice'` for LibreOffice, `'ream'` (the default) for Ream’s own typesetter. Combined with the metric-compatible substitutes above, visual parity no longer needs the other tool’s private font metrics — only a font engineered to reproduce them and its layout rules. ## Document model [Section titled “Document model”](#document-model) Beyond the converters, the typed document model is exported from the `reamkit/document-model` subpath — paragraphs, runs, tables, sections, numbering, shapes, math and more. `renderStyledPdf` drives the layout engine directly if you want to build or transform a document programmatically rather than parse one.
# Examples
> Working recipes for Ream: PDF/A, digital signatures, font providers, SVG and HTML, Markdown for language models, strict mode and the document interlayer.
Every snippet below is runnable as-is; they all start from document bytes (`Uint8Array`) however you obtained them — a `File`, a `fetch`, `fs`. ## One parse, many targets [Section titled “One parse, many targets”](#one-parse-many-targets) `Ream.parse` reads the document once into the interlayer; every `convert` renders from it without re-parsing:
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(bytes);
const pdf = await doc.convert('pdf', { fonts });
const svg = await doc.convert('svg', { fonts }); // page-stack preview, no PDF involved
const html = await doc.convert('html'); // flowed HTML — no fonts, zero I/O
const md = await doc.convert('md'); // GitHub-Flavored Markdown — same, narrower
const docx = await doc.convert('docx'); // WordprocessingML back out — no fonts, no layout
const xlsx = await doc.convert('xlsx'); // SpreadsheetML back out — from an .xlsx source
```
## docx → docx: normalize, sanitize, edit [Section titled “docx → docx: normalize, sanitize, edit”](#docx--docx-normalize-sanitize-edit) `convert('docx')` writes the parsed document back to a valid `.docx`. The round-trip is **semantic, not byte-exact** — the writer emits the resolved formatting as direct properties rather than named styles — so use it to normalize, sanitize or programmatically edit a document in the browser, not to preserve the original markup verbatim. Images, tables, lists, links, bookmarks, shapes, headers/footers, multi-section geometry, footnotes/endnotes, charts and OfficeMath all round-trip, and a drawing that states where on the page it belongs is written back as the `wp:anchor` that puts it there rather than flattened into the text flow. No image part the format cannot show goes into the package: JPEG 2000 is dropped with a loss that names it.
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(bytes); // a .docx (xlsx has no docx writer)
const out = await doc.convert('docx');
// `out` is a fresh, valid .docx — hand it to a download, an upload, or re-parse it.
```
## docx → markdown: structure without geometry [Section titled “docx → markdown: structure without geometry”](#docx--markdown-structure-without-geometry) `convert('md')` writes GitHub-Flavored Markdown. Like HTML it is a flow medium — no pagination, no layout engine, no fonts — but a much narrower one, so it keeps what the document *says* and reports everything it cannot say back.
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(bytes);
const { bytes: md, losses } = await doc.convertWithReport('md');
// Headings, lists (with their real numbers and nesting), GFM tables,
// links, footnotes and the text inside shapes all survive.
console.log(new TextDecoder().decode(md));
// Everything markdown has no syntax for is reported — once each, however
// many paragraphs it happened in:
// [dropped] text: paragraph alignment has no markdown expression
// [degraded] tables: merged cells flattened — markdown has no spans
for (const loss of losses) console.log(loss.severity, loss.feature, loss.detail);
```
Pictures are inlined as `data:` URIs so the output is a single self-contained file. When you would rather write the image bytes yourself — a docs site, a repo — ask for links instead and the writer names them predictably:
```ts
const md = await doc.convert('md', { images: 'link' }); // 
const bare = await doc.convert('md', { images: 'drop' }); // no pictures at all
```
A deck’s only structure is where one slide ends and the next begins, and the `.pptx` / `.ppt` readers carry that as a page break. Markdown has no pages, so by default the break is dropped and reported — ask for the rule and each slide gets its own section:
```ts
const deck = Ream.parse(pptxBytes);
const md = await deck.convert('md', { pageBreaks: 'rule' }); // --- between slides
```
A workbook has the same problem and a different answer: markdown cannot tell one sheet from the next, so each opens with a heading carrying its tab name. A printed page never shows one — Excel and Calc emit it nowhere — so this is markdown’s alone, and `{ sheetNames: false }` turns it off:
```ts
const book = Ream.parse(xlsxBytes);
const md = await book.convert('md'); // # Revenue, then its grid; # Costs, then its
```
## Any attachment → Markdown for a language model [Section titled “Any attachment → Markdown for a language model”](#any-attachment--markdown-for-a-language-model) A chat that takes a document and hands it to a model wants what the document says, not how its pages look — and one function serves all seven inputs, a PDF and the legacy binaries included:
```ts
import { Ream } from 'reamkit';
/** An attached document as Markdown a model can read, whatever its format. */
async function attachmentToMarkdown(bytes: Uint8Array): Promise {
const doc = Ream.parse(bytes); // .docx .xlsx .pptx .pdf .doc .xls .ppt — sniffed
const deck = doc.format === 'pptx' || doc.format === 'ppt';
const md = await doc.convert('md', {
images: 'drop', // no base64 pictures in the prompt
pageBreaks: deck ? 'rule' : 'drop', // a deck's slides apart by ---
});
return new TextDecoder().decode(md);
}
```
Markdown needs no fonts, so this touches neither the network nor a file system and runs as well in the page, before anything is uploaded, as on a server. A PDF comes back as the document it was — read from its structure tree when it is tagged, from where its glyphs stand when it is not: paragraphs, headings, lists, columns and tables. A form or a drawing comes back line by line instead, each line where it stands. Ream does no OCR, so a scan gives up its text only from a text layer OCR software left under the picture. What Markdown cannot carry — charts, math, headers and footers — is in `convertWithReport`’s losses, as with any other target. ## xlsx → HTML / SVG: a workbook as Excel shows it [Section titled “xlsx → HTML / SVG: a workbook as Excel shows it”](#xlsx--html--svg-a-workbook-as-excel-shows-it) A workbook comes out two ways. Its PDF is the printed pages — print area, repeated titles, page breaks, fit-to-page, the drawings cut to the page they print on. Its HTML and SVG are what Excel’s window shows: every visible tab, one grid a sheet with all its columns at full size, text running on across the row, drawings over the cells where they are anchored, the window’s gridlines where the sheet asks for them, and a red corner on every cell with a note.
```ts
const book = Ream.parse(xlsxBytes);
const pdf = await book.convert('pdf', { fonts }); // the printed pages
const html = await book.convert('html'); // the window: one a tab
const svg = await book.convert('svg', { fonts }); // a picture of each sheet, whole
```
The HTML needs no fonts — the browser sets the text, and a note shows on hover over its cell. The SVG draws every glyph from its face’s own outline, so it looks the same in any viewer with no font to find; the words are laid over the glyphs unseen, so the text can still be searched and selected. ## xlsx → xlsx: re-emit a workbook [Section titled “xlsx → xlsx: re-emit a workbook”](#xlsx--xlsx-re-emit-a-workbook) `convert('xlsx')` writes a spreadsheet’s grid back to a valid `.xlsx`. Unlike the docx writer it consumes the native grid tree, so the round-trip is **lossless on the grid surface** — cells, styles, merges, the print model, conditional formatting, sparklines, tables and embedded charts all survive a read → write → read loop byte-stably. It requires a spreadsheet source; a `.docx` has no grid.
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(xlsxBytes); // a .xlsx
const out = await doc.convert('xlsx');
// `out` is a fresh, valid .xlsx — normalize, sanitize, or re-parse it.
```
## Password-protected Word and Excel documents [Section titled “Password-protected Word and Excel documents”](#password-protected-word-and-excel-documents) A password-protected `.docx` / `.xlsx` is not a zip at all — ECMA-376 §2.3 puts the whole package inside an OLE container as ciphertext — so it has to be decrypted before any reader sees it. The same `password` option does that, for both Office schemes (the 2007 standard one and the agile one 2010 and later write):
```ts
const doc = Ream.parse(docxBytes, { password: 'letmein' });
const pdf = await doc.convert('pdf');
```
A wrong password is an **error**, not a loss — here and in a PDF alike: every scheme stores a verifier, so the file can say the password is wrong instead of handing back rubbish. It comes as `WrongPasswordError` — a class, so a corrupt file is not mistaken for a bad password:
```ts
import { Ream, WrongPasswordError } from 'reamkit';
try {
Ream.parse(bytes, { password });
} catch (e) {
if (e instanceof WrongPasswordError) promptAgain();
else throw e; // not a password problem
}
```
A document that needs a password and gets none throws too, naming the option to pass. An interface usually wants to know before that — to show a password field rather than an error — and `isEncryptedPackage` answers from the bytes:
```ts
import { Ream, isEncryptedPackage } from 'reamkit';
const password = isEncryptedPackage(bytes) ? await askTheUser() : undefined;
const doc = Ream.parse(bytes, { password });
```
Decryption only: Ream never writes an encrypted package, so `convert` output is always in the clear. ## pdf → html / docx: read a PDF back [Section titled “pdf → html / docx: read a PDF back”](#pdf--html--docx-read-a-pdf-back) `Ream.parse` also accepts a **PDF** — including a modern compressed one (cross-reference streams, object streams) or an encrypted one. A tagged PDF (the ones Ream writes) is rebuilt from its structure tree — headings, paragraphs, tables, lists in reading order, through the role map a document names its own elements by, with an inline element (a span, a link, MathML) kept in its parent’s line; an untagged PDF is reconstructed heuristically from glyph positions — in the columns of prose the page was set in, breaking to the next column and balancing the last page where the page does, with a running head or foot kept out of the body and its page number written as a field — counted in the page’s own numerals, front matter in roman, and a foot to each side where a book signs its even and odd pages apart — a page ruled into a grid rebuilt as a table with its own columns and row heights, a table set across the columns read whole, a code listing kept line for line, a drawing kept with the labels set on it as one figure, a list’s items and an index’s hanging entries a paragraph apiece, a heading on a dark bar given the bar as its shading, a word the line broke in half put back together, and a bracketed block of rows and columns read as an OfficeMath matrix. A page that is not prose in columns is read ACROSS: an invoice sets its labels along the left and its figures against the right margin, and every one of those figures belongs to the line beside it. Blocks set SIDE BY SIDE are another matter: the same invoice stacks its dates and numbers beside the address it bills, each stack at a leading of its own, and read across, every line would catch a line of the other. Such a band comes back as the borderless table a writer would set it in, each block read down on its own, while blocks whose lines share their baselines stay one text. A gap no word space could be — or one that lands on a stop the lines around it share — comes back as a TAB standing on the stop the page set the piece after it at, consecutive lines broken at the SAME stops come back as a table, with a column of figures that end together set against its right edge, and a line the page drew between two blocks becomes the border of the paragraph it separates rather than a shape anchored where the words used to be. What a form writes — a button’s caption, a field’s value, a tick — stands where the page placed it, over the box it is written on, rather than joining the lines of the page. **Raster images, hyperlinks and the page’s artwork come back too** — images lifted out and sized from their placement (including the ones written into the content stream, stencil masks painted in the page’s own colour, a colour key leaving unpainted the samples it names, and a CMYK JPEG in the colours its inks paint rather than in Adobe’s inverted convention), link annotations re-attached to the text, filled paths, stroked lines — dashed and capped as the page draws them — and shading-pattern gradients turned into shapes, the clipping paths that limit them, tiling patterns (a hatch or a grid as the tone it gives the page), the opacity a fill or a stroke is painted at, the appearance an annotation carries — or one drawn from its properties where the file supplies none, a free-text note from its contents, and a form that asks for its appearances rebuilt showing its fields’ values — and the Type 3 glyphs that are drawings rather than letters. Colour comes back through whatever space states it: device, CIE (`CalGray`, `CalRGB`, `Lab`), an `/ICCBased` stream through the profile it carries, or a `Separation`/`DeviceN` run through its own tint transform — for an image as much as for a fill. A gradient the page paints with a bare `sh` is read too, function-based included, and words filled with one come back in its colours. The layers a file turns off stay off, and the box it says to show is the box you get. Type is read the way the font states it — the base encoding it declares, the built-in one a symbolic font carries (ZapfDingbats is a font of pictures and comes back as pictures), a predefined CMap it names instead of embedding — a ligature comes back as the letters it joins, punctuation a font names no character for is read off the shape the page draws, and a face that cannot be addressed by character at all is DRAWN from its outlines rather than guessed at. The result is an ordinary `FlowDoc`, so it converts onward like any other source. Written to `.docx`, a run names its face’s family — `Inter`, not `Inter-SemiBold`, a font no word processor has — and the face itself travels with the document: rebuilt as TrueType from the outlines the page drew, at the advances it set them at, with its kerning and the ligatures the page drew, and embedded where its licence lets it, so Word and LibreOffice break each line where the page broke it on a machine that has none of the document’s fonts. A word space TeX shrank to fit a line is written as narrow as TeX set it, a picture keeps its crop, its turn and its opacity, and a line its dash. A form or a drawing is not a reflowable document, though — its rules and boxes are placed absolutely, and a label an inch from the box it labels says nothing. **The file decides for itself**: a paper is mostly lines and is re-flowed, a form or a drawing is mostly marks and is kept as a page, with every line where its glyphs stand. There is nothing to configure — the reader records which reading it took, in the losses:
```ts
const doc = Ream.parse(pdfBytes);
const docx = await doc.convert('docx');
doc.losses.find((l) => /read as a/u.test(l.detail)); // …which reading it took
```
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(pdfBytes); // doc.format === 'pdf'
const html = await doc.convert('html'); // the PDF's text as flowed HTML
const docx = await doc.convert('docx'); // …or an editable Word document
const { bytes, losses } = await doc.convertWithReport('html');
// losses note the untagged-heuristic degradation and any unread vector art.
```
### Encrypted PDFs [Section titled “Encrypted PDFs”](#encrypted-pdfs) A locked PDF opens with its password — the **user** password, or the **owner’s**, which opens it as well. The empty-string default unlocks the common permissions-only encryption (where the owner set restrictions but no open password), so most encrypted PDFs need no password at all:
```ts
const doc = Ream.parse(pdfBytes, { password: 'letmein' });
```
Every revision of the PDF security handler stores a verifier, so a **wrong** password — or **none**, where one is needed — is refused rather than decrypted into rubbish, with the same `WrongPasswordError` an Office package throws:
```ts
import { Ream, WrongPasswordError } from 'reamkit';
try {
Ream.parse(lockedPdf); // no password
} catch (err) {
if (err instanceof WrongPasswordError) {
err.message; // 'This PDF needs a password to open — pass it as `password`'
}
}
```
A file locked by a security handler Ream does not implement is not a password problem: it parses, and what could not be decrypted is a read-time **loss**. In **strict** mode that loss throws a `ConversionLossError`, with the offending `Loss` on its `.loss` property:
```ts
import { Ream, ConversionLossError } from 'reamkit';
try {
await Ream.parse(otherHandlerPdf).convert('html', { strict: true });
} catch (err) {
if (err instanceof ConversionLossError) {
err.loss.detail; // 'encrypted PDF — its security handler is not supported, …'
}
}
```
## A PDF whose streams use a filter Ream does not carry [Section titled “A PDF whose streams use a filter Ream does not carry”](#a-pdf-whose-streams-use-a-filter-ream-does-not-carry) §7.4 leaves the filter set open, and PDF 2.0 added Brotli. A stream Ream cannot decode is a stream it has not read — and when that stream is the cross-reference, the file has no pages at all. Supply the decoder and it does:
```ts
import brotliPromise from 'brotli-dec-wasm'; // ~200 KB wasm, browsers and workers
import { Ream } from 'reamkit';
const brotli = await brotliPromise;
const doc = Ream.parse(pdfBytes, {
filters: { BrotliDecode: (bytes) => brotli.decompress(bytes) },
});
```
Any Brotli implementation you already ship will do — on a server the runtime carries one, so `import { brotliDecompressSync } from 'node:zlib'` and pass that instead. Ream itself imports neither: a 122 KB static dictionary in every browser bundle, for a filter almost nothing produces, is not a cost the common case should pay. Without a decoder the loss report names the filter, so a document that comes back empty says why. ## pdf → pdf: a form keeps its form [Section titled “pdf → pdf: a form keeps its form”](#pdf--pdf-a-form-keeps-its-form) A paper reads back as a re-flowable document — paragraphs, columns and tables in reading order. A form is not that: its grid is painted at fixed coordinates, and text that flows beside the grid sits in none of its boxes. So a form is read as a page instead, every line standing where its glyphs stand — and the file, not the call, decides which of the two it gets:
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(pdfBytes);
const pdf = await doc.convert('pdf', { fonts });
```
The reader counts the marks against the baselines on the median page and records which reading it took and why, so a plan folded into a report does not make the report a plan. Worth knowing when the output is DOCX, Markdown or HTML: a file read as a page has no reading order, no paragraphs and no tables to give them. ## pptx → pdf: render a slide deck [Section titled “pptx → pdf: render a slide deck”](#pptx--pdf-render-a-slide-deck) `Ream.parse` also accepts a **PowerPoint** `.pptx`. Each slide becomes a page at the deck size, its shapes read as positioned content — text boxes, placeholders, pictures, shapes, tables, charts, embedded objects, groups and hyperlinks. What a deck states once reaches every slide that relies on it: the master’s and the layouts’ own decoration (drawn under the slide’s content), the background — solid, gradient, picture or a theme reference — the deck’s colour map, the text style its `p:defaultTextStyle` and `p:txStyles` set, and the table styles in `tableStyles.xml`. The result is an ordinary `FlowDoc`, so it converts onward like any other source:
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(pptxBytes); // doc.format === 'pptx'
const pdf = await doc.convert('pdf', { fonts }); // a page per slide
const html = await doc.convert('html'); // …or the slides as flowed HTML
```
## Word review comments [Section titled “Word review comments”](#word-review-comments) Review comments (`w:commentReference`) render as a bracketed superscript marker in the text and a “Comments” section after the body — author, date and content, with reply threads nested and resolved threads flagged, the commented range highlighted, and author identities resolved from `people.xml`. In PDF the marker is a clickable jump to the entry; pass `commentAnnotations: true` to *also* attach each comment as a native sticky-note annotation (interactive output only — suppressed under PDF/A and tagged):
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(docxBytes);
const pdf = await doc.convert('pdf', { fonts }); // markers + Comments section + highlights
const sticky = await doc.convert('pdf', { fonts, commentAnnotations: true }); // …plus /Text pop-ups
const html = await doc.convert('html'); // replies nested, resolved threads flagged
doc.flow.comments?.get('0'); // { content, author?, date?, authorId?, parentId?, done? }
```
Comments — threads and resolved flags included — also write back through `convert('docx')`. ## Legacy .doc / .xls / .ppt [Section titled “Legacy .doc / .xls / .ppt”](#legacy-doc--xls--ppt) The binary Office formats parse through the same entry point and the same interlayer — `Ream.parse(bytes)` sniffs OLE2/CFB and picks the reader, so every target and every option below works on them unchanged. A legacy deck brings its master’s decoration and background, the text its slide list holds with the sizes, colours, typefaces and bullets its master states, grouped shapes and tables, picture fills and the metafiles it draws with; a legacy workbook brings its styling, its drawings placed on the sheet’s own grid, its charts, its print model and its conditional formatting.
```ts
const doc = Ream.parse(bytes); // .doc / .xls / .ppt — sniffed like the rest
const pdf = await doc.convert('pdf');
const xlsx = await doc.convert('xlsx'); // a .xls re-writes as a modern workbook
```
## Excel pivot tables [Section titled “Excel pivot tables”](#excel-pivot-tables) A pivot table’s cached output renders as an ordinary grid; on top of that Ream applies the table’s named pivot style (`pivotTableStyleInfo`) — banded rows and a styled header — and emphasises the grand-total / subtotal rows and columns. Nothing is recomputed from the cache:
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(xlsxBytes);
const pdf = await doc.convert('pdf', { fonts });
const html = await doc.convert('html');
```
## Excel data validation [Section titled “Excel data validation”](#excel-data-validation) A `list` data validation (``) paints an in-cell dropdown affordance — a small button with a ▾ — on every cell of its range, in both PDF and HTML. The validation, its formulas and the input/error prompts also round-trip through `convert('xlsx')`:
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(xlsxBytes);
const pdf = await doc.convert('pdf', { fonts }); // list cells show a ▾ dropdown button
const html = await doc.convert('html');
const xlsx = await doc.convert('xlsx'); // the survive the round-trip
```
## Excel slicers [Section titled “Excel slicers”](#excel-slicers) A slicer (`xl/slicers` + `xl/slicerCaches`) renders as a captioned button box after the grid — the way a chart frame does. A native-table slicer fills its buttons from the referenced table column’s distinct values and highlights the ones the column’s autofilter keeps; an OLAP/pivot slicer whose items live in a pivot cache degrades to a caption-only box.
```ts
import { Ream } from 'reamkit';
const doc = Ream.parse(xlsxBytes);
const pdf = await doc.convert('pdf', { fonts }); // a button box per slicer, after the grid
const html = await doc.convert('html');
```
## SmartArt diagrams [Section titled “SmartArt diagrams”](#smartart-diagrams) SmartArt (DOCX and PPTX) renders either way round. Where the file caches a pre-rendered DrawingML drawing (`diagrams/drawing#.xml`) that is drawn directly; where it does not, the diagram is laid out from its own `data`, `layout`, `colors` and `quickStyle` parts — the algorithms (`lin`, `composite`, `cycle`, the hierarchy pair, `snake` and the rest), the constraint solver that sizes and spaces the boxes, and the colour and style parts that paint them. Scheme colours resolve through the document or deck theme, and box text is measured so a box grows to what it holds. Nothing special is needed to get it — it is part of the ordinary conversion:
```ts
import { Ream } from 'reamkit';
const { bytes, losses } = await Ream.parse(docxBytes).convertWithReport('pdf', { fonts });
// `losses` is where anything the file asks for and Ream cannot draw is reported.
```
## Browser: file input → PDF preview [Section titled “Browser: file input → PDF preview”](#browser-file-input--pdf-preview)
```ts
import { Ream } from 'reamkit';
input.addEventListener('change', async () => {
const bytes = new Uint8Array(await input.files![0].arrayBuffer());
const pdf = await Ream.parse(bytes).convert('pdf');
window.open(URL.createObjectURL(new Blob([pdf], { type: 'application/pdf' })));
});
```
## Node: file in, file out [Section titled “Node: file in, file out”](#node-file-in-file-out)
```ts
import { readFileSync, writeFileSync } from 'node:fs';
import { Ream } from 'reamkit';
const doc = Ream.parse(new Uint8Array(readFileSync('report.docx')));
writeFileSync('report.pdf', await doc.convert('pdf'));
```
## Archival PDF/A with the source embedded [Section titled “Archival PDF/A with the source embedded”](#archival-pdfa-with-the-source-embedded) The whole PDF/A family is supported (1a/1b, 2a/2b/2u, 3a/3b/3u). PDF/A-3 can carry the source document inside the PDF as an associated file:
```ts
const { bytes: pdfa, losses } = await doc.convertWithReport('pdf', {
fonts,
pdfA: 'PDF/A-3b',
embedSource: true, // .docx/.xlsx rides along as /AF with /AFRelationship /Source
});
```
`'PDF/A-1a'` / `'PDF/A-2a'` / `'PDF/A-3a'` additionally emit the tagged logical structure (headings, tables, lists, figure alt text). ## Accessible PDF/UA-1 [Section titled “Accessible PDF/UA-1”](#accessible-pdfua-1) `pdfUA: true` produces ISO 14289-1-conformant output — tagged structure, alternate descriptions on links, an always-announced document title. It combines with PDF/A in a single file (both veraPDF-validated):
```ts
const accessible = await doc.convert('pdf', { fonts, pdfUA: true });
const archival = await doc.convert('pdf', { fonts, pdfA: 'PDF/A-2a', pdfUA: true });
```
## PDF bookmarks [Section titled “PDF bookmarks”](#pdf-bookmarks) A PDF opens with an outline (ISO 32000 §12.3.3), the reader’s bookmarks panel. It is built from a Word document’s headings, a workbook’s printed sheets, a deck’s slides, or a source PDF’s own bookmarks, and it is on by default:
```ts
const pdf = await doc.convert('pdf', { fonts }); // outline from the headings
const toc = await doc.convert('pdf', {
fonts,
outline: { maxLevel: 3, openPanel: true }, // Heading 1–3, panel open on load
});
const bare = await doc.convert('pdf', { fonts, outline: false }); // no outline
```
In tagged output each entry also names its heading’s structure element, so assistive technology can go from a bookmark to the heading itself. ## Digital signature [Section titled “Digital signature”](#digital-signature) PKCS#7 detached (ISO 32000 §12.8, `adbe.pkcs7.detached` over SHA-256) via WebCrypto — RSA or ECDSA — in an invisible signature field:
```ts
const signed = await doc.convert('pdf', {
fonts,
signature: {
certificate: certificateDer, // Uint8Array, DER — the signer's X.509 certificate
privateKey: cryptoKey, // WebCrypto CryptoKey
// Everything below is optional.
algorithm: 'ecdsa', // 'rsa' (default: RSASSA-PKCS1-v1_5) or 'ecdsa' (P-256/384/521)
extraCertificates: [caDer], // intermediate CA certificates (DER), embedded with the signer's
signingTime: new Date(), // /M and the CMS signingTime (without it the CMS takes now)
reason: 'Approved', // /Reason
location: 'Head office', // /Location
name: 'A. Signer', // /Name
contactInfo: '+1 555 0100', // /ContactInfo
fieldName: 'Approval', // the signature field's name (default 'Signature1')
reserveBytes: 16384, // room for the CMS in /Contents (default 8192)
},
});
```
The key’s algorithm must match `algorithm`, and an RSA key is imported with `hash: 'SHA-256'`. The signing time is the one the signer states; no timestamp authority is asked. Sign last: anything that rewrites the bytes afterwards breaks the signature, and a long certificate chain that outgrows `reserveBytes` throws. ## Font resolution chain [Section titled “Font resolution chain”](#font-resolution-chain) Chain providers. The chain is asked for the document’s default faces, then for each family the document names, then for the face of each writing system its text holds (`FontRequest.script`); the first provider to answer a request wins it. A remote or local winner is recorded as a `substituted` loss:
```ts
import { Ream, localFontProvider, remoteFontProvider } from 'reamkit';
const { bytes, losses } = await doc.convertWithReport('pdf', {
fontProviders: [
localFontProvider(), // the family installed on this machine (Chromium Local
// Font Access; embedding-restricted fonts are never used)
remoteFontProvider(), // else its open substitute, and the Noto face of a script
],
});
// losses → { severity: 'substituted', feature: 'fonts.substitution',
// detail: 'Calibri rendered with Calibri (provider: local)' }, …
```
`callerFontProvider(myFonts)` answers every request with your bytes, so no provider after it is ever asked: put it last (`[localFontProvider(), callerFontProvider(myFonts)]`). A chain that answers no default faces, such as `[localFontProvider()]` alone, keeps the installed families and downloads the rest as it would without a chain. Fonts embedded in the document itself (`w:embed`, including obfuscated `.odttf`, and a deck’s `p:embeddedFontLst`) always win — glyph-exact, no substitution. A `w:rFonts` that names a **theme** slot rather than a family resolves through the theme’s major / minor fonts before any of this runs. A face the network fails to deliver is not remembered as failed: the next conversion asks for it again, so a server that builds its provider chain once and reuses it keeps working after a dropped connection. A required face that cannot be fetched still throws, with the network’s error as its `cause`. The substitute set is Latin, so a document holding another writing system is served separately: a Noto face is fetched per SCRIPT — Japanese, Korean, Chinese, Arabic, Hebrew, Thai, geometric symbols — and only for the scripts the document actually contains. It is chosen per character, so a paragraph that mixes Latin and Arabic is drawn in both faces rather than in one with holes:
```ts
// A sheet of Korean: NotoSansKR is fetched, in the regular weight only.
// The same call on a Latin-only document downloads nothing extra.
const pdf = await Ream.parse(bytes).convert('pdf');
```
## Renderer parity [Section titled “Renderer parity”](#renderer-parity) Ream is a correct typesetter: it lays out faithfully for the font you give it, and a document Word sets — a `.docx` or a `.doc` — stands its lines as Word sets them, by rules measured in Word. For closer *visual parity* with a specific renderer, pass a `layoutProfile` — it switches how text is measured, broken into lines and stacked to match that tool. Paired with the metric-compatible substitutes above (so the same glyph advances are in play), the page geometry tracks the target closely:
```ts
const pdf = await doc.convert('pdf', { fonts, layoutProfile: 'libreoffice' });
// 'word' targets Microsoft Word; 'ream' (the default) is Ream's own typesetter.
```
`'libreoffice'` breaks lines greedily (first-fit) and takes each line from the face in hand — its hhea line, or its OS/2 typo line where the face asks for that; `'word'` measures without kerning (Word’s default), breaks first-fit and stands every line as Word sets it, whatever the document. The profile applies to flowing text (DOCX/PPTX); spreadsheet geometry follows Excel’s row model regardless. ## Strict mode (compliance flows) [Section titled “Strict mode (compliance flows)”](#strict-mode-compliance-flows) Make any loss fatal instead of reported:
```ts
import { ConversionLossError } from 'reamkit';
try {
await doc.convert('pdf', { fonts, strict: true });
} catch (e) {
if (e instanceof ConversionLossError) {
// e.loss — what exactly would have been dropped/degraded/substituted
}
}
```
## Inspect the interlayer [Section titled “Inspect the interlayer”](#inspect-the-interlayer) `parse` produces a format-neutral tree before any rendering:
```ts
const doc = Ream.parse(bytes);
doc.format; // 'docx' | 'xlsx'
doc.losses; // read-time losses
for (const el of doc.flow.body) {
// el.kind: 'paragraph' | 'table' | 'image' | 'chart' | 'shape'
}
```
## PDF metadata [Section titled “PDF metadata”](#pdf-metadata) `/Info` is read automatically from the document’s `docProps/core.xml`; caller values override it:
```ts
const pdf = await doc.convert('pdf', {
fonts,
info: { title: 'Q4 Report', author: 'Finance' },
});
```
## Hyphenation [Section titled “Hyphenation”](#hyphenation)
```ts
import { getHyphenator } from 'reamkit';
const hyphenator = await getHyphenator('en-us'); // or 'ru'
const pdf = await doc.convert('pdf', { fonts, hyphenator });
```
# Scope & limitations
> What Ream reads and writes today — DOCX, XLSX, PPTX, PDF and the legacy .doc, .xls and .ppt — feature by feature, and where its edges are.
The conversion core is broad and spec-driven, but ECMA-376 is vast and Ream does not implement all of it — this page is an honest map of what works and what doesn’t yet. ## Implemented [Section titled “Implemented”](#implemented) **Input** — Ream parses **Word (`.docx` and legacy `.doc`)**, **Excel (`.xlsx` and legacy `.xls`)**, **PowerPoint (`.pptx` and legacy `.ppt`)** and **PDF**, sniffed from the bytes. The legacy binary `.doc` / `.xls` / `.ppt` (the OLE2/CFB formats) are read through a shared container reader — see WordprocessingML / SpreadsheetML / PresentationML below. A **PowerPoint** deck becomes one page per slide at the deck size, its shapes read as positioned content: text boxes (run formatting and letter spacing, alignment, vertical anchor, bullets, indents, and boxes that don’t wrap), the text style the deck states once, layout/master placeholders and the decoration they carry, backgrounds (solid, gradient, picture or theme reference), pictures with their recolouring, shapes (geometry/fill/stroke/gradient), DrawingML tables with the style they name, embedded charts and objects, theme colours through the deck’s colour map, grouped shapes and run hyperlinks; text set to shrink is measured and shrunk to fit its box, and a SmartArt is laid out from its own parts whether or not the file cached a drawing. Not read (a graceful loss): alpha/roman list numbering. PDF input handles classic and modern compressed files (cross-reference streams, object streams) and encrypted files (RC4 / AES; the user or owner password is passed to `Ream.parse`, defaulting to the empty permissions-only case, and one that opens the file as neither is refused with `WrongPasswordError`). A **tagged** PDF (including the ones Ream writes) is rebuilt from its structure tree — headings, paragraphs, tables, list items, reading order, the elements a document names for itself followed through its `/RoleMap` to the standard ones they stand for, and an inline element (a span, a link, a formula set in a line, MathML) read as a stretch of its parent’s line rather than a block of its own (§14.8); an **untagged** PDF is reconstructed heuristically from glyph positions (lines by baseline, paragraphs by spacing and by the indent the page set them with, headings by relative font size, a word the line broke in half put back together, and the page read for its own gutters: as many columns of PROSE as it was set in — a page of labels with figures against the right margin breaks a dozen lines at the same x and is not two columns, so it is read across and each label keeps its figure — blocks set SIDE BY SIDE, each at a leading of its own, set as the borderless table a writer sets them in and each read down on its own (an invoice’s stack of dates and numbers beside the address it bills; blocks whose lines share their baselines stay one text, read across on its stops), a page RULED into a grid rebuilt as a table with its measured columns and rows, a gap written as a TAB with the stop the page set the piece after it at, where no word space could make it or where it lands on a stop the lines around it share, consecutive lines standing on the SAME stops rebuilt as a table of their own, with a column whose figures end together set against its right edge, a line drawn between two blocks given to the block it separates as that paragraph’s border, a rule typed out of hyphens left on the line of its own it was written on, a band repeated at the top or bottom of every sheet as a running head or foot with its regions and its page number as a field, and a bracketed block of rows and columns as an OfficeMath matrix), which is approximate. A page in columns is read down them: a gutter is the white between two columns, not where most of a ragged column’s lines end; a JUSTIFIED column, flush on both sides, is prose as surely as a ragged one; and a column a few ems wide beside a gap the page’s lines run across is a table’s. A page that turns to its next column short of the foot breaks there, and a last page set in balanced columns ends their section on that page. A line set wholly in a typewriter face is CODE, a listing kept line for line with its comments on the stops the page set them at; a row of four cells and more is a TABLE’s, read whole where it reaches across the gutter, the line over it its heading, a rule across it the border of the row under it and a rule drawn down it the division between two of its columns; a drawing and the words set on it — boxes and arrows, a bar chart — are one FIGURE, set as an inline group in its column; a line that opens with a bullet or a hanging label opens a list item, and an INDEX’s entries hang, each a paragraph with the lines that carry it on. A box filled behind a single line — a heading on a dark bar — is that paragraph’s shading. A running band’s numeral that changes from page to page is the page’s NUMBER, counted in the numerals the page prints: front matter in roman starts a section of its own, a book that leaves its blank pages out is counted all the same, and a book that signs its even and odd pages at opposite edges gets a foot to each side (§17.10.1). A page whose words run down its sheet comes back as a section set that way (§17.6.20 `tbRl`). The margins are measured to the page’s INK — a blank is not ink, and a picture is: a sheet whose one line of text sits over a picture wider than that line keeps a measure the picture still fits. Text comes back via each font’s `/ToUnicode` map (a range of it judged code by code, §9.10.3), or — where a composite font ships none — from the reverse `cmap` of the program it embeds (§9.10.2), or — where a SIMPLE font ships none, which is every PDF from TeX — from the glyph NAMES its `/Encoding /Differences` states (§9.6.6.1) over the base encoding the font declares (Annex D.2 Standard, WinAnsi and MacRoman, or a symbolic font’s own built-in one — ZapfDingbats is a font of PICTURES and is read as pictures, Annex D.6), and a code the differences leave `.notdef` is no character at all. The names TeX gives its Greek and its mathematics — `alpha`, `epsilon1`, `asteriskmath` — are read like any other, and so are the Cyrillic names of the Adobe Glyph List — `afii10017`, `schwacyrillic`, `kadescendercyrillic` — every Turkic letter among them. A Latin schwa among Cyrillic letters, which is how Word, Excel and PowerPoint for Mac export a Kazakh ә set in Arial, Times New Roman or Courier New, is read as the Cyrillic one; a word of the Latin alphabet keeps its ə. An accent TeX strikes over a letter it has no glyph for is composed with that letter: “naïve”, not “na¨ıve”. A word space is read where the page STEPS one as wide as most of its face’s space as well as where it draws one, a dot stepped on after a word is the rest of an ellipsis, and a dash closed up to its word takes no space where a line breaks. A ligature comes back as the letters it joins — “first” is `first` to a search and to an edit — and a composite font the file names but does not embed, with `Identity-H` and no `/ToUnicode`, is read in the glyph order of the face it names where that is one of the Microsoft core faces (§9.7.4 — Arial, Times New Roman, Verdana and their like keep the Macintosh standard order for their first 258 glyphs). A face that cannot be addressed by character at all — a TrueType program with no usable `cmap` (§9.6.6.4) — is not guessed at: its codes are glyph indices, the text is marked unrecoverable and the glyphs are DRAWN from their outlines, a word at a time, as are the glyphs of a font that names them after nothing a reader knows (CFF charstrings run as the programs they are, `glyf` outlines and their composites, `post` names over the Macintosh standard order). Punctuation a font names no character for — a producer that maps every mark to U+0000 leaves an invoice with no hyphen, colon or bracket in its text — is read off the SHAPE the page draws, where that shape says one thing: a flat bar at the middle of the lower case is a dash, two stacked dots a colon, one small mark on the baseline a full stop or a comma. The predefined CMaps a file names instead of embedding are known (§9.7.5.2), including the vertical ones that advance the pen down the page. A run names its face’s FAMILY — `Inter` for `Inter-SemiBold`, without the producer’s debris (a `,Bold`, a `-Identity-H`, a serial number) — with the kind of face it is, so a program that lacks it substitutes one of the same kind. The weight and slant come from the `/FontDescriptor`, and where it states no weight from the header of the program itself; a face’s own name outweighs the flags that contradict it (a `-Light` face is not bold for a ForceBold hint), and a family the substitution tables know decides whether it is a serif, a sans or a typewriter face. The embedded font programs themselves are carried into the output, so a rebuilt page is set in the type it was set in. Written to `.docx`, each face the page drew with is rebuilt as TrueType — the outline of every character it drew, at the advance the page set it at, with its kerning pairs (GPOS `kern`) and the ligatures the page drew (GSUB `liga`) — and embedded where its licence (OS/2 `fsType`) lets it, and a word space TeX shrank to fit a line is written as narrow as TeX set it (§17.3.2.43 `w:w`): a re-set line breaks where the page broke it, on a machine that has none of the document’s fonts. **Raster images, hyperlinks and vector artwork** are lifted back out too (JPEG verbatim but for a baseline CMYK one, which every viewer reads in Adobe’s inverted convention and which is decoded instead, Adobe’s YCCK included, and given back in the colours its inks paint; other images re-encoded as PNG with soft-mask alpha — including JBIG2, the bilevel coding a scanner stores a page of text in (ISO/IEC 14492: generic, refinement, symbol-dictionary, text and halftone regions, arithmetic and Huffman, and a dictionary whose symbols are REFINEMENTS of the ones it already holds), and CCITT Group 3 two-dimensional, where every line begins with the bit that says how it is coded — `/Link` URIs re-attached to the text, filled paths, stroked lines — dashed in the page’s own pattern and capped as it caps them (§8.4.3.6 `d`, §8.4.3.3 `J`) — and shading-pattern gradients turned into shapes), colour set through a named space (§8.6.8 `cs` / `sc`, which is how every PDF a browser prints states it) — including the CIE spaces `CalGray` (§8.6.5.6), `CalRGB` (§8.6.5.7, gamma and matrix into XYZ, adapted onto D65 by Bradford) and `Lab` (§8.6.5.8), an `/ICCBased` stream decoded through the profile it carries (§8.6.5.5), and a `Separation` or `DeviceN` run through its own tint transform (§8.6.6.4/§8.6.6.5) — for an IMAGE as much as for a fill — which needs all four kinds of PDF function (§7.10: sampled, exponential, stitching, and the type-4 PostScript calculator) — along with clipping paths (§8.5.4 `W` / `W*`, applied to paths and pictures alike, and carried into a turned picture’s OWN axes), stencil image masks (§8.9.6.2, painted in the page’s non-stroking colour), colour-key masks (§8.9.6.4 — the samples a `/Mask` array names left unpainted, held against the samples before any `/Decode`), images written into the content stream (§8.9.7 `BI` … `EI`), tiling patterns (§8.7.3 — read as the pattern’s colour at the strength its tile covers where they fill type, and where they fill a shape with a tile drawn in lines and dots, a hatch or a grid, which comes back as the tone it gives the page rather than as the hatch itself; a tile that holds a picture is lifted as that picture; an uncoloured pattern, §8.7.3.3, takes the colour `scn` gives it), constant alpha (§11.6.4.4 — a fill’s `/ca` and a stroke’s `/CA` through the `gs` operator), Type 3 glyphs (§9.6.5 — content streams, drawn as the artwork they are in every reading: such a font has no program and no face, so its codes are never re-set in a substitute, which would draw the letter a second time), annotation appearance streams (§12.5.5, so a form field draws itself — inside its `/BBox`, which is its clip, and what it writes, a button’s caption or a field’s value, stands where the annotation stands, over the box it is written on, rather than being read into the page’s lines; a form that asks for its appearances rebuilt, §12.7.2 `/NeedAppearances`, shows its fields’ values rather than the stale text of the old appearance), the text render modes (§9.3.6 `Tr` — stroked type keeps its outline, and the invisible modes an OCR layer uses are marked rather than painted), the box a viewer shows (§14.11.2 `/CropBox` — which sizes the page AND clips the marks outside it; a media box with no area is the Letter sheet a page that states none gets) and the page’s own `/Rotate` (§14.11.1). A file’s optional content is honoured (§8.11 — the layers its default configuration turns off stay off, on `/OC … BDC` marked content and on an XObject’s own `/OC`, through an `/OCMD`‘s policies). An annotation the file gives no `/AP` is drawn from its own properties (§12.5.5 — Ink, Line, Square, Circle, Polygon, PolyLine, a text field’s `/V` set in its `/DA`, a free-text note’s `/Contents` set in its `/DA` (§12.5.6.6), and the text markups’ `QuadPoints` applied to the words they cover). The built-in metrics of the 14 standard fonts (§9.6.2.2) stand in where a file embeds neither the face nor a `/Widths` array. A gradient the page paints with a bare `sh` is read as the shape it covers (§8.7.4.5, function-based type 1 included), in the colour space the shading dictionary states; an axial one runs the way its matrix carries it onto the page, and a shape it fills shows the part of its axis the shape covers (§8.7.4.5.3) rather than the whole axis squeezed across it; text filled with one comes back in its colours rather than in black, and the loss report says where the gradient’s shape was flattened to a single colour. **Output** — `convert('pdf')`, `convert('svg')` (a page-stack preview), `convert('html')` (flowed, needs no fonts) — a workbook’s HTML is Excel’s window and its SVG a picture of each sheet, whole (SpreadsheetML below) — `convert('md')` (GitHub-Flavored Markdown), `convert('docx')` (write WordprocessingML back out) and `convert('xlsx')` (write SpreadsheetML back out — spreadsheet input only). The writers are for normalization, sanitization, in-browser editing, and round-tripping. The docx round-trip is semantic, not byte-exact, but complete — text, tables, images, lists, links, headers/footers, multi-section geometry, footnotes/endnotes, charts and OfficeMath all write back, and so do a paragraph’s tab stops (§17.3.1.38) and its own rules (§17.3.1.24 `w:pBdr`), and the page-number fields a running foot is written with (§17.16.19 `w:fldSimple` — `PAGE` and `NUMPAGES`, so the second sheet does not say it is the first). So do a paragraph’s shading (§17.3.1.31 `w:shd`) and how far its rules stand off it, its widow control and whether it keeps with the next paragraph or keeps its lines together (§17.3.1.44, §17.3.1.14–15); a run’s width and character spacing (§17.3.2.43 `w:w`, §17.3.2.35 `w:spacing`), its kerning and its ligatures (`w:kern`, `w14:ligatures`); a line break, as `w:br` rather than a newline inside the text; a line spaced in lines, in the 240ths `w:lineRule="auto"` counts; a table’s indent (§17.4.65 `w:tblInd`); a drawing group (`wpg:wgp`); and a section’s page-number numerals (§17.6.12 `w:pgNumType`) and the way its lines run (§17.6.20 `w:textDirection`). The document’s settings write back too — headers of its own for the even pages, a gutter at the head, `doNotExpandShiftReturn` and the compatibility mode (§17.15.1) — and the styles part states the defaults the writer leaves out, which Word would otherwise take from its own Normal template. A picture keeps how it is drawn into its frame — its crop (§20.1.8.55 `a:srcRect`), its turn and mirror (§20.1.7.6 `a:xfrm`) and its opacity (`a:alphaModFix`) — so a cropped picture read from Word and saved again no longer comes back whole and squeezed into the frame its crop was sized for; a fill and a line keep the opacity they are painted at (§20.1.2.3.1 `a:alpha`), and a line its own dash pattern (§20.1.8.21 `a:custDash`). A run names its font’s family, and the font table says what kind of face that is (§17.8.3), so a reader that lacks the family substitutes one of the same kind. A section states where it must OPEN as well as where it begins: a `w:type` of `oddPage` or `evenPage` (§17.6.22) survives the round trip and is laid out as Word lays it out, printing the blank sheet it implies — charged to the section that ends, not the one that starts. A drawing that states where on the page it belongs is written back as the `wp:anchor` that puts it there (§20.4.2.3) rather than flattened into the text flow. No image part the format cannot show goes into the package: JPEG 2000 is not among the parts §15.2.14 admits, and is dropped with a loss that names it rather than written as a hole. The xlsx round-trip preserves the whole grid surface — cells, styles, merges, the print model, conditional formatting, sparklines, tables and embedded charts — and is byte-stable across a read↔write loop. **Stream filters the reader does not implement (§7.4)** — a filter it cannot undo leaves that stream unread, and when the unread one is the cross-reference the whole document is missing. Rather than carry a decoder for every filter anyone might write, `Ream.parse(bytes, { filters })` takes one from the caller:
```ts
import brotliPromise from 'brotli-dec-wasm'; // ~200 KB wasm, browsers and workers
const brotli = await brotliPromise;
Ream.parse(pdf, { filters: { BrotliDecode: (b) => brotli.decompress(b) } });
```
On a server the runtime already carries one, so `brotliDecompressSync` from `node:zlib` goes in the same slot. Brotli is RFC 7932’s context-modelled Huffman scheme over a 122 KB static dictionary, and a filter almost nothing produces does not belong in every browser bundle — which is why this is a hook rather than a dependency. Absent, or throwing, the filter is reported unreadable by name rather than producing an empty document silently. FlateDecode, LZW, RunLength, ASCII85, ASCIIHex, CCITT, DCT, JPX and JBIG2 need nothing supplied. **The two PDF readings** — a conversion cannot have both readings at once: words that move cannot agree with rules that do not, so anchored artwork over reflowed text lines up with none of it. The FILE decides which it gets. A paper is mostly LINES with a rule or two between them and is read as a re-flowable document — paragraphs and tables in reading order, from the structure tree where the file has one, and where it has none, in the columns of PROSE the page was set in, with its running head and foot kept out of the body, its blocks set side by side read down each on its own, its ruled grids, its rows-on-the-same-stops and its tables across the columns rebuilt as tables, its listings kept line for line, its figures kept with their labels, and the lines it drew between blocks given to the paragraphs they separate; what a form field or a button writes still stands where the page placed it, over the box it is written on. A form or a drawing is mostly MARKS (one form sets 28 numbered rows in 355 ruled boxes) and is read as a page: every line stands where its glyphs stand, beside the artwork, with no reading order, no paragraphs and no tables. The marks are counted against the baselines on the MEDIAN page, so one plan folded into a report does not make the report a plan; the reader records which reading it took and why. There is no option to override it. A caller holding a `Uint8Array` cannot know whether it is a paper or a form, so asking it to choose only moved the guess outward — and left the choice the library actually makes untested, because everything that measured it pinned the other one. Markdown, which places nothing, reads a page kept only for its table’s rules — or for letters the file names no character for — as the document it is without them: a ruled estimate comes back as its rows, its sums whole. **Markdown (`convert('md')`)** — GitHub-Flavored Markdown, a flow medium like HTML: no pagination, no layout, no fonts, zero I/O. It keeps what a document *says* and drops how it *looks*. Kept: headings (Word’s built-in Heading styles known by their name, as Word knows them, and `w:outlineLvl`, falling back to a `Heading N` / `Title` style id), bold, italic, strikethrough, ordered and bullet lists with their real numbers and nesting, tables as GFM pipe tables with per-column alignment, hyperlinks (through the same scheme allowlist the HTML writer uses), pictures, footnotes and endnotes as GFM footnotes, review comments as footnotes attributed to their author, bookmarks as inline anchors, and the text inside shapes. A spreadsheet opens each sheet with a heading carrying its tab name — markdown has no pages to tell one sheet from the next by, so `{ sheetNames: false }` is there for the bare tables — and every cell whole and in its own column, however narrow the column a page cuts it to. Underline and super/subscript survive as `` / `` / ``, which GFM parses as inline html. Dropped, each reported once in the loss report rather than silently: alignment, indents, colour, font family and size, tab stops, page and column breaks, headers and footers, charts, shape geometry, and math. A page break can be kept instead — `{ pageBreaks: 'rule' }` writes the `---` thematic break a slide deck wants, since the `.pptx` and `.ppt` readers mark each slide boundary with one and it is the only structure a deck has. Merged cells flatten — markdown’s table is a plain grid — and a nested table flattens into the cell that holds it. Pictures are inlined as `data:` URIs by default; pass `{ images: 'link' }` to reference them under `./media/` and write the bytes yourself, or `{ images: 'drop' }` to omit them. **Password-protected packages (ECMA-376 §2.3, MS-OFFCRYPTO)** * An encrypted `.docx` / `.xlsx` / `.pptx` is not a zip at all: the whole OPC package is ciphertext inside an OLE container. Given the password (`Ream.parse(bytes, { password })`) it is decrypted and read like any other document. Both schemes in the wild are supported — the **standard** one (Office 2007 and LibreOffice: AES-ECB under a key spun from 50 000 SHA-1 rounds) and the **agile** one (Office 2010 and later: an XML descriptor naming its own hash and cipher, the package cut into 4096-byte segments with an IV each). `isEncryptedPackage(bytes)` says a file wants a password before the parse does, and each scheme carries a verifier, so a **wrong password is refused** (`WrongPasswordError`) rather than yielding rubbish. Decryption only — Ream never writes an encrypted package. **WordprocessingML (§17)** * Text, runs and the full style cascade (`docDefaults` → styles → direct formatting). * Tables — auto / fixed layout, §17.4 border-conflict resolution, cell shading, vertical merge and grid span, nested tables, **table styles** (`w:tblStyle` with conditional formats: banding, first/last row/column). A table’s own `w:tblBorders` overrides its style one side at a time. Columns are laid out from the cells’ widths (`w:tcW`) and the table’s own (`w:tblW`) as Word lays them out, not from the grid it last saved (`w:tblGrid`); a width may be written as a percentage (`"100%"`) or with a unit (`"2in"`). A table’s own cell margins beat its style’s, side by side. A table in a text box paints its shading and rules over the box’s fill. A row of exact height keeps it on every page and is never split. An “at least” row breaks only where its minimum fits, and its border takes room on top of that height, as in Word. Automatic text colour turns white over a dark background, as Word turns it: the run’s, the paragraph’s or the cell’s shading, or the text box’s fill, at Rec. 601 luma below 59.77 of 255. * Lists and numbering (`abstractNum`, level overrides), multi-level. A bullet set in a symbol face — Symbol, Wingdings — is the character the face draws; items that ask for contextual spacing (§17.3.1.9 `w:contextualSpacing`) stand line to line in the body, a table cell, a header or a footnote alike; and the tab after a marker, like any tab past a paragraph’s own stops, falls on the document’s grid (§17.15.1.25 `w:defaultTabStop`). * Sections — per-section page size and orientation, headers and footers (a pair for the even and the odd pages, `w:evenAndOddHeaders`, and a first page of its own), **multi-column layout** (`w:cols`), and **lines that run down the sheet** (§17.6.20 `w:textDirection` `tbRl` / `btLr` — the text turned a quarter, the header and footer left across the sheet, as Word sets them). * **Hyperlinks** — external (clickable PDF annotations + HTML ``, scheme-allowlisted) and internal: bookmarks become named destinations / `#`-anchors. A PDF link’s address is written as the 7-bit ASCII URI §12.6.4.7 asks for: an IDNA host and percent-encoded UTF-8. Its description reads as written, in any script and in right-to-left order. * **Fields** — `PAGE` / `NUMPAGES` render real page numbers in headers and footers, in the numerals the section names (§17.6.12 `w:pgNumType w:fmt` — front matter in roman, a body that starts again at 1). * **Laid out the way Word sets it** — each rule measured in Word for Mac. A line stands as tall as Word sets its faces: the face’s hhea line, or its typo line where it asks for that, the tallest ascent and the deepest descent on the line taken apart, a list marker adding its ascent, a picture standing on the baseline. Two paragraphs stand the larger of their spacings apart, not the sum, and a space before is dropped at the head of a page or column where Word drops it; automatic spacing is 14pt in every compatibility mode. A paragraph’s first and last lines never stand alone (§17.3.1.44 widow control), a heading goes to the next page with what it heads (`w:keepNext`), and a paragraph asked to stay whole does (`w:keepLines`). A table’s horizontal borders take the room they are wide, and a Word 2010 table (compatibility mode 14 and earlier) stands out by its first cell’s margin and reaches past the right one by its last cell’s. Each page sets its body below the header and above the footer it shows, and a page break typed on a line of its own stays on the page it ends. * **Footnotes and endnotes** — notes at the bottom of the referencing page behind Word’s separator rule; endnotes after the body. * **Review comments** (`w:commentReference`) — a bracketed superscript marker in the text and a “Comments” section after the body with each comment’s author, date and content (PDF and HTML). Reply threads and resolved state come from `commentsExtended.xml` (replies nest under their parent, resolved threads are flagged); the commented range (`w:commentRangeStart/End`) is highlighted; author identities resolve from `people.xml`. As an opt-in, comments can also be emitted as native PDF sticky-note annotations (`commentAnnotations`, interactive output only). * **SmartArt** — the diagram’s own parts (`data`, `layout`, `colors`, `quickStyle`) are laid out by the same engine the deck reader uses, so a document that cached no drawing renders rather than degrading; where a pre-rendered drawing (`diagrams/drawing#.xml`) is present it is used directly. * Inline and floating images (PNG / JPEG / JPEG2000 / GIF / **TIFF** / **BMP** — baseline TIFF 6.0 and Windows bitmaps are decoded to samples, since PDF has no filter that carries either; a BMP is read at every depth from one bit to thirty-two, run-length and bit-field forms included), including **legacy VML pictures** (`` / `` — ActiveX and OLE-object previews, images from older Word); floating drawings (`wp:anchor`) render outside the text flow — wrap-none (incl. `behindDoc`, which Word reads beside no other wrap) for watermarks/stamps/text boxes, and side wrapping (`square`/`tight`/`through`) where the body text flows around the exclusion area, on **both sides** of it where the drawing leaves room, each line holding what its indents and the drawing’s stand-off leave. A drawing anchored to a paragraph that breaks to a new page goes with it. A drawing **anchored inside a table cell** is placed against the cell (or against the page, where `layoutInCell` is off), and a picture’s **washout** (`@gain`/`@blacklevel`) prints as the contrast and brightness it asks for. A header’s or footer’s drawing is placed as a body drawing is, against what its anchor names: the page, the margin, or the inside or outside margin by the sheet’s parity. * **Metafiles** — EMF (MS-EMF) and WMF (MS-WMF), the format Word writes for anything it draws itself: an embedded workbook’s preview, a legacy clipart, an ActiveX control’s face, an equation. The records are played through their own device context — pen, brush, font, current point, window/viewport and world transform — and drawn as paths and text: lines, polygons, polylines, Béziers, rectangles, ellipses, path brackets, brush blits and both text records. In the flow, floating, in a header, inside a cell, or inline in a line of text. * **Text boxes chained** with `wps:linkedTxbx`: what overruns one box continues in the next of its chain. * Tracked changes (`w:ins` / `w:del`). * Reads both **Transitional and Strict** (ISO 29500) packages; block-level content controls (`w:sdt`) flow through. * **Legacy `.doc`** (Word 97–2003) — the binary `WordDocument` stream inside the OLE2/CFB container is read for its **text and formatting**: the FIB locates the piece table (the CLX), whose pieces — 16-bit Unicode or 8-bit Windows-1252 (“compressed”) — are stitched back into the document text and split into paragraphs, while the CHPX and PAPX runs (located through the `PlcfBteChpx` / `PlcfBtePapx` bin tables and decoded from their sprms) carry **bold / italic / underline / font size / font** onto each run and **alignment / indentation / spacing / keeps / tab stops** onto each paragraph, over what their **styles** give them (the STSH: paragraph and character styles along their bases, down to the default fonts the document names; the fonts by name from the `SttbfFfn`, slot by slot). **Page, column and line breaks** and a paragraph set to start a page break where Word breaks them. **Sections** come from the `PlcfSed`: each starts where it says — a new page, an odd or even one, or the page in hand — on its own paper size, inside its own margins and gutter. **Tables** are reconstructed too — the in-table paragraphs (marked by the `fInTable` / `fTtp` PAPX flags, cells delimited by the `0x07` cell mark) become a row-and-cell grid, with per-column widths, **per-cell borders and vertical merges** (the table definition’s `TC80` array) and **per-cell background shading** (`sprmTDefTableShd`‘s `cvBack` fill) — and **inline images** are extracted (the picture character’s CHPX points at a PICF in the `Data` stream; the raster blip is pulled out and sized from the PICF). **Fields** resolve to their cached result — the field code (`REF`, `DATE`, …) is dropped and the stored result text kept — but for `PAGE` and `NUMPAGES` in a header or footer, which count the pages, restarting and in the numerals each section asks for. Each section’s **headers and footers** are lifted from the `PlcfHdd` stories — a first page’s own, even pages’ own, and “same as previous” taken from the section before. **List items** (`sprmPIlfo` / `sprmPIlvl`) render with their resolved **number format** — a real “1.” / “a)” / “iii.” or the bullet glyph, from the `LST` / `LVL` / `LFO` tables — ended by the tab, space or nothing their level asks for. So an old `.doc` renders to PDF/SVG/HTML and re-writes to `.docx`. Legacy drawing shapes / text boxes and comments are not read (re-save as `.docx` for full fidelity); an encrypted `.doc` yields no text — the binary formats lock themselves with the older RC4 scheme, which is not the OOXML one above. The shared CFB reader (`src/core/ole`) is the same keystone `.xls` uses. **SpreadsheetML (§18)** * Grids, shared strings, number formats and dates (incl. the 1904 date system). * **Measured against Excel itself** — its own PDF of a probe workbook built for each question, and the absolute positions it writes beside every anchored drawing. Columns are counted in the Normal font’s digit as Excel counts it: a Chinese, Japanese or Korean face’s is a pixel more than its half-width figure (宋体 12 is 9px). A column no `