.pdf (@awacloud/pdf's pdf.read() result) → oconv-ir/v2 — tier 1, text-first only.

Module oconvPdfToIr (oconvPdfToIr) | Source packages/front/office/oconv/src/read/pdf-to-ir.js | Deps oconvIr, oconvPdfTextExtract, oconvPdfStruct | Worker-safe yes

Pure transformation over the parsed pdf.read(bytes) structure plus on-demand content-stream decode through oconvPdfTextExtract/oconvPdfStruct. Real text is extracted through a font's ToUnicode CMap, the encoding-table + AGL hop, or (composite fonts only) a Unicode-coded predefined CMap; scanned/OCR is permanently out, and there is no layout inference beyond text-positioning heuristics.

Resolve

import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/oconv';

const runtime = new ModuleRuntime();
runtime.registerAll(fw_require);
runtime.registerAll(modules);
const pdf = runtime.resolve('pdf');
const { pdfToIr } = runtime.resolve('oconvPdfToIr');

API

Member Signature Returns Throws
pdfToIr (readResult: object, opts?: {formOpBudget?: number, infer?: string[], declare?: string[], include?: string[], lineHyphens?: string}) => {ir, losses, coverage} ir — an oconv-ir/v2 document; losses — {code, detail}[]; coverage — {pages: object[], total: {operators, decoded, undecodable}, tagged: boolean} oconv: bad form op budget; oconv: bad pdf infer; oconv: bad pdf declare; oconv: bad pdf include; oconv: bad pdf line hyphens

Examples

Convert a .pdf read result to IR

const { ir, losses, coverage } = pdfToIr(pdf.read(bytes));
ir.kind;             // 'document'
coverage.tagged;     // false when the document has no /StructTreeRoot
// measured on the vendored facturx-minimum-sample.pdf fixture:
// coverage.total → {operators: 3585, decoded: 4128, undecodable: 0}

Notes

  • Two paths: a tagged fast path (/StructTreeRoot present) derives structure from the logical tree, walked in /K order with its tags mapped through the /RoleMap, keyed to text through marked-content ids: H1..H6 struct elements become IR headings; an inline element (Span, Link, Note, Reference, BibEntry, Code, Quote, Annot, Ruby, Warichu, Sub, Em, Strong, a Lbl outside a list) joins the enclosing block's text in order; any other element gives its inline content as paragraphs between its block children (a list's lead-in stays before the list). All the pieces of one block are joined by the untagged path's paragraph rule below (a line wrap is one space, a same-line gap over 0.15 em too, a word split across two ids none; a soft hyphen ending a line joins the word without it, a hyphen only under opts.lineHyphens, below). An L becomes an IR list: each LI an item holding its LBody's blocks (a nested L included, an L straight inside an L joining the previous item); a numeric Lbl makes the list ordered; a marker Lbl — a bullet, or a number, letter or roman numeral with its punctuation — is dropped (markdown writes the marker), another label starts the item's text. A Table becomes an IR table: TR rows, directly or through THead / TBody / TFoot, TH / TD cells holding their blocks, a THead row or a row of TH cells only a header row, the table's Caption a paragraph before (or after) it. A Table without a TR is flattened (loss struct/dropped). An untagged fall-back groups content-stream text pieces into lines and paragraphs by vertical position, inferring headings and tables by default (see opts.infer below); within a line it inserts one space where the horizontal gap between a piece's end and the next piece's start exceeds 0.15 em (never doubling an existing space, never on a line whose pieces go backwards). A piece that exactly repeats the previous piece of its line — same text, within 0.5 pt in x and in y — is dropped first. A piece that starts left of the previous piece's end (an overlap) gets one space iff the overlap exceeds the same 0.15 em — so a kerned apostrophe or a syllable split across two shows stays joined.
  • Page boundaries become IR hr nodes in both paths — the frozen vocabulary has no section node.
  • coverage is reported, never assumed: per-page and total {operators, decoded, undecodable} counts, honest-loss-matrix discipline (never claim zero loss from an unmeasured decode).
  • Loss codes this module and its dependencies emit: text/undecodable (≥1 char code resolved to no Unicode), text/font-unresolved (a show op ran with no resolvable current font), text/width-approximated (a font's glyph widths fell back to a declared width — once per font resource per page), image/dropped (an image XObject or inline image, inside a Form XObject too — tier 1 keeps none; under opts.include: ['images'], every picture but a placed one; one entry per draw, its detail the picture: <name> (<num> <gen> R, <w>x<h>) — the resource name, the object, the /Width × /Height (a direct object without the reference, the size left out when not integers) — inline (<w>x<h>) or inline for an inline image, xobject for a Do without a name operand, the bare name when the resources lack it or it is no image, so two pictures sharing a name stay apart when frontMatter: 'compact' counts the ledger), image/mask-dropped (under opts.include: ['images'] only — a placed picture's soft mask or mask, not applied; detail = the asset name), xobject/form-dropped (a Form XObject whose stream cannot be used — detail names the reason; a usable form is executed and its text extracted), xobject/form-cycle / xobject/form-depth / xobject/form-budget (a Form XObject not executed by a guard: drawn from inside itself, nested deeper than 12, or past a budget of formOpBudget form operators on the page, default 1,000,000), content/undecodable (a content stream failed to decode/parse — detail stream <objNum>: <cause>, the thrown error's message), struct/dropped (tagged path, a Table without a TR row, flattened), text/running-dropped (untagged path, under opts.infer: ['running'] only — a running header or footer line left out of every page; detail its pattern), struct/positional (untagged path, under opts.declare: ['positional'] only — the structure built from positioning, once per document). First in the ledger, the read document's own records (readResult.losses, read after the extraction): pdf/document/xref-rebuilt, pdf/document/xref-tolerated, pdf/document/free-entry-fallback, pdf/document/free-object, pdf/document/reference-cycle (each with its detail, as the profile lists it) and pdf/opened-with-empty-user-password (pdf's pdf/document/opened-with-empty-password, detail permissions <P>).
  • The pdf document's own losses (doc.losses: a cross-reference shape tolerated, a chain rebuilt, a free entry resolved or read as null) are not read: this module's ledger holds the codes above only, so a repaired file converts with no record of the repair (a known silent case, see the loss matrix).
  • opts.formOpBudget: absent (undefined) resolves to the default (1,000,000); present, it must satisfy Number.isSafeInteger(v) && v >= 1, else pdfToIr throws oconv: bad form op budget — checked at entry, before the first page is extracted, so a zero-page document still refuses a bad value. The option is forwarded to every page's oconvPdfTextExtract.extractPage call, which applies the identical rule.
  • opts.infer (the untagged path only; a tagged document's structure wins): a list of inference names; absent, ['headings', 'tables'] (since 2.0.0, so a read chain composed without toMd infers as toMd does), and [] the text-first read of 1.x; anything else than distinct known names throws oconv: bad pdf infer, checked at entry. 'headings': the body size is the font size, rounded to 0.5 pt, that carries the most characters over the document; a piece is heading-sized at ≥ 1.15 × the body size; on each page the pieces are cut into runs at each change of class (heading-sized or not) and, inside the heading-sized class, of rounded size; each run is grouped by the paragraph rule above; a paragraph of a heading-sized run with at most 150 characters and a letter becomes an IR heading; on one line, every heading-sized piece takes the line's largest heading size (a small-caps title set at two sizes is one heading); its level the rank of its run's size among the document's heading sizes (the largest 1, capped at 6). The thresholds are measured on opendataloader-bench (1.1, 1.2, 1.3 × and 80, 250 characters score lower); the result is an inference, not a structure the file states. By weight too: the pieces are taken by line (the paragraph rule's first pass); a line is bold when every piece of it is (bold, from pdfFontDecoder); the runs are also cut where a body-sized line's boldness changes; a paragraph of a bold run with at most 80 characters and a letter is a heading, its level after the size-ranked ones (their count + 1, capped at 6). A bold word inside a body line changes nothing. A figure or table caption is no heading, by size or by weight: a paragraph starting with Figure, Fig., Table, Chart, Graph, Exhibit, Map, Box, Plate or Diagram (any case), then a digit, stays a paragraph. Measured with URW's bold read as bold and the table-of-contents rule below: opendataloader-bench 0.7949 → 0.8176. 'tables': a line's cells are its pieces left to right, a new cell where a piece starts more than 0.8 em right of the previous piece's end; a run of two or more consecutive lines of two or more cells is a candidate; its sorted cell starts give the column anchors (a new anchor more than 1.5 em past the last); the columns are the anchors two rows or more use; with two columns or more and no cell over 40 characters (body text set in columns is not a table; with 3 columns or more, one column other than the first may hold cells of up to 120 characters), the run becomes an IR table — one row per line, each cell in its nearest column, the first row a header — unless it is a table of contents (2 columns, 3 rows or more, each row's first cell holding a letter and its last a page number of 1–4 digits or a roman numeral of up to 7 letters, the numbers not decreasing), which stays text; a table stands where its first line was, its lines out of the text flow (measured: 0.8 em against 1.0 / 1.2, 1.5 em against 0.8 / 1.0, 40 characters against 25–50). Ruled tables come first: under 'tables' the pages' rules are asked of oconvPdfTextExtract (opts.rules); a horizontal and a vertical rule cross when each reaches the other within 2 units, and two segments of one rule line (one x, or one y, within 2) whose ranges touch within 2 are one line, as when a vertical is cut at every row border; a component of crossing rules with at least 2 of each, whose distinct ys and xs (clustered within 2) are at least 3 each, is a grid; each text piece goes to the cell its start lies in; the grid is an IR table when its text reaches at least 2 rows, 2 columns and 30 % of its cells (rows without text left out, the first row a header), standing where its first piece was, unless the aligned-text rule, run on the grid's own pieces by line, finds more rows than the grid has (no rule between its body rows), in which case its pieces stay for that rule; its pieces leave the flow, and the aligned-text rule runs on the lines that remain (measured, segments and that guard: opendataloader-bench 0.8313 → 0.8367, 3 documents up and none down). On an untagged document, 'tables' also asks for oconvPdfTextExtract's cellKerns, so a table row drawn as one TJ (its column gaps as kerns of more than 1 em, 2 of them or more) comes as one piece per cell (measured: opendataloader-bench 0.8176 → 0.8239). Then, on the lines no table holds, rows on several baselines are read: where the content order goes back up between two lines by more than 0.5 em and at most 2.5 em (a row drawn cell by cell, or a cell centred against a two-line neighbour), the region, grown to the lines whose baselines lie within its own (±0.75 em), is re-cut by baseline; baselines closer than 0.75 em are one row, and a row's fragments starting at one column (within 1.5 em) are one cell, joined top down, the 40-character cap applying to each fragment; such a table needs 3 rows or more, its pieces one size within 0.5 pt (an equation's subscripts stay text), and it takes whole content lines (measured: opendataloader-bench 0.8239 → 0.8313, 4 documents up and none down, the same over 0.75–1.0 em and 2.5–3.5 em). 'running': on a document of 3 pages or more, a line (a page's pieces within 1 pt of one height, in content order) in the top or the bottom 12 % of its page's /MediaBox is a running header or footer when its pattern (its text, each run of digits read as #, spaces collapsed) recurs within 2 pt of the same height on at least half the pages and 3; its pieces leave the page before any block is built, and one loss text/running-dropped per pattern and height records the pattern (measured on pypdf-benchmarks' 14 documents: 0.9287 → 0.9300, 10 up and 2 slightly down).
  • Line-end hyphens: the paragraph rule joins two lines with one space, except a soft hyphen (U+00AD) ending a line after a letter, the next starting with a letter: it is dropped and the word joined, always. opts.lineHyphens (opt-in) joins a hyphen (U+002D, U+2010) after a letter, the next line starting with a lowercase letter: 'drop' without the hyphen (infor- + mation → information; a compound cut at its own hyphen loses it), 'keep' with it (infor-mation, well-known), on every paragraph the rule builds — both paths, inferred headings and ruled-table cells included. undefined reads as without it; another value throws oconv: bad pdf line hyphens. Measured on opendataloader-bench (374 such wraps): its ground truth mostly keeps the line break with its hyphen, so the default scores highest (0.5753), 'keep' 0.5751, 'drop' 0.5749.
  • opts.declare (opt-in): a list of names recording a case the reader otherwise passes over in silence, undefined or [] reading as without it; anything else than distinct known names throws oconv: bad pdf declare, checked at entry. 'positional': a document read on the untagged path whose IR holds at least one paragraph, heading or table records one loss struct/positional, after the extraction's losses, its detail naming what was built from positioning — paragraphs, then headings and tables when opts.infer asked for them (paragraphs, headings, tables). A tagged document, or an untagged one with no text, records nothing.
  • opts.include (opt-in): a list of parts tier 1 otherwise drops, undefined or [] reading as without it; anything else than distinct known names throws oconv: bad pdf include, checked at entry. 'images': a placeable picture (an indirect image XObject drawn by Do, inside a form too, not an /ImageMask, whose last filter is DCTDecode or JPXDecode and no earlier one, with a default /Decode, whose decoded bytes are a JPEG file or a JP2 file, or a raw-pixel picture oconvPdfImagePng writes as a PNG — see oconvPdfTextExtract's opts.images) becomes a block IR image: name image-<obj>.jpg, .jp2 or .png (-<gen> before the extension when the generation is not 0), alt '', and escapes.pdf = { bytes, contentType } (image/jpeg, image/jp2, image/png), which the writers read after escapes.docx and escapes.odt. On the untagged path a page's items are cut at each such picture: each text part goes through the paragraph rule (and opts.infer's headings and tables), the picture stands between them, in content order. On the tagged path a picture is placed with the struct element that lists its marked-content id, after that element's text; a picture no element lists, or drawn outside marked content, records image/dropped (detail the picture, as for a draw). A placed picture whose /SMask or /Mask was not applied records image/mask-dropped: it is kept without its mask (a JPEG or JPX picture's mask always; a PNG takes a same-size soft mask or a colour-key array as its alpha). A picture drawn twice is placed twice (one asset in toMd). Every other picture — CMYK, Lab, Separation or DeviceN samples, CCITT, JBIG2, a raw JPEG 2000 codestream, a JPEG with a non-default /Decode, an image mask, an inline image — keeps its image/dropped.

See also