docling_core/document.rs
1//! The unified document representation.
2
3use crate::markdown::{to_markdown, to_markdown_images};
4use crate::ImageMode;
5
6/// The unified, format-agnostic document produced by every backend.
7///
8/// This is the heart of docling: backends parse their source format into a
9/// `DoclingDocument`, and serializers turn it back into Markdown, HTML, JSON,
10/// etc. Phase 0 uses a flat sequence of [`Node`]s; the production schema will
11/// match docling-core's body-tree-with-references layout.
12#[derive(Debug, Clone, PartialEq)]
13pub struct DoclingDocument {
14 /// Logical document name (usually the input file stem).
15 pub name: String,
16 /// Top-level content, in reading order.
17 pub nodes: Vec<Node>,
18 /// Default Markdown export mode for [`Self::export_to_markdown`]. `false`
19 /// (the default) reproduces docling's legacy output byte-for-byte; `true`
20 /// emits cleaner, more conformant Markdown. Set by `DocumentConverter`.
21 pub strict_markdown: bool,
22 /// Emit tables in the compact `| a | b |` / `| - | - |` form rather than
23 /// docling-core's width-padded GitHub serializer. The PDF backend sets this
24 /// (its committed groundtruth corpus predates the padded serializer); DOCX/HTML
25 /// leave it `false` to match current published docling.
26 pub compact_tables: bool,
27 /// Render a picture's author-written alt text (#676: the `descr` /
28 /// `title` of an OOXML picture's non-visual properties, carried as a
29 /// [`PictureDescription`] whose provenance is
30 /// [`PictureDescription::ALT_TEXT`]) in the Markdown and HTML exports
31 /// (the `` of an image line or the line above a placeholder;
32 /// the `<img alt>` and the description text). `false` (the default)
33 /// keeps it to the JSON (and DCLX) output, so the default Markdown and
34 /// HTML stay byte-for-byte docling's; strict Markdown renders it
35 /// regardless. Set by `DocumentConverter::picture_alt_text`.
36 pub picture_alt_text: bool,
37 /// What the file says about itself (#679): an EPUB's Dublin Core, an
38 /// Office package's properties, a photo's EXIF, an audio file's tags —
39 /// see [`crate::metadata`]. Read by the converter when
40 /// [`metadata_output`](Self::metadata_output) asks for it (a document
41 /// read from docling JSON keeps the `metadata` the JSON carried).
42 pub metadata: crate::metadata::DocumentMetadata,
43 /// Where [`metadata`](Self::metadata) goes in the exports: nowhere (the
44 /// default — every export stays docling's), the JSON's `metadata`
45 /// object, or that and YAML front matter at the top of the Markdown.
46 /// Set by `DocumentConverter::metadata_output`.
47 pub metadata_output: crate::metadata::MetadataOutput,
48 /// Text the Markdown export inserts between two pages — docling-core's
49 /// `MarkdownParams.page_break_placeholder` (e.g. `"<!-- page break -->"`).
50 /// `None` (the default) omits page breaks from Markdown, as docling does.
51 /// Set by `DocumentConverter::page_break_placeholder`. See
52 /// [`crate::markdown`] for where a break lands (only between two rendered
53 /// blocks that sit on different pages, never leading or trailing).
54 pub page_break_placeholder: Option<String>,
55 /// Hyperlinks recovered from the source, as `(anchor_text, href)` pairs in
56 /// document order. docling's standard pipeline drops PDF link annotations, so
57 /// these are rendered as Markdown `[anchor](href)` **only in strict mode**
58 /// (legacy/docling output is left byte-for-byte unchanged). The PDF backend
59 /// populates this from pdfium link annotations; other backends leave it empty.
60 pub links: Vec<(String, String)>,
61 /// Conversion-confidence report (#183), populated by the PDF/image ML
62 /// pipeline; `None` for declarative conversions. Deliberately **not**
63 /// part of any document export (docling keeps it on the conversion
64 /// result, outside the document schema) — docling-serve surfaces it in
65 /// the HTTP response instead.
66 pub confidence: Option<crate::confidence::ConfidenceReport>,
67 /// docling's item tree, when the backend built one (the HTML backend
68 /// does): the JSON export serializes it instead of deriving a tree from
69 /// `nodes`, so the JSON carries upstream's exact parent/child structure,
70 /// item numbering, inline groups, formatting and content layers. Every
71 /// other serializer reads `nodes`. See [`crate::tree`].
72 pub tree: Option<crate::tree::ItemTree>,
73 /// Rendered page images by 1-based page number — docling's
74 /// `PageItem.image`, filled by the PDF/image pipeline only when page
75 /// images are requested (docling's `generate_page_images`, #520). The
76 /// JSON export writes each as the page's `image`, so docling-core's
77 /// `TableItem.get_image` / `FormulaItem.get_image` can crop from it.
78 /// Empty otherwise; no other export reads it.
79 pub page_images: std::collections::BTreeMap<usize, PictureImage>,
80 /// What the reader ran into and read around (#912): a limit it hit —
81 /// an HTML page nested past `DOCLING_RS_MAX_HTML_DEPTH`, read as flat
82 /// text with no item tree and no source blocks — named, with the
83 /// effective limit, so a caller sees why the document lacks what it
84 /// lacks instead of an unexplained success. The converter reports each
85 /// as a `partial_success` error item.
86 pub notices: Vec<Notice>,
87}
88
89/// Something the reader did instead of what it does by default (#912),
90/// with the reason — see [`DoclingDocument::notices`].
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct Notice {
93 pub kind: NoticeKind,
94 /// One line: what was hit, the effective limit, what the document
95 /// lacks because of it.
96 pub message: String,
97}
98
99/// What a [`Notice`] is about.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub enum NoticeKind {
102 /// The source nests deeper than the cap `variable` sets (its effective
103 /// value `limit`): it was read as flat text — the content is there,
104 /// the item tree and the source blocks are not.
105 DepthLimit {
106 /// The environment variable that sets the cap.
107 variable: &'static str,
108 limit: usize,
109 },
110}
111
112impl Notice {
113 /// A [`NoticeKind::DepthLimit`] notice for `what` (the format read).
114 pub fn depth_limit(what: &str, variable: &'static str, limit: usize) -> Self {
115 Notice {
116 kind: NoticeKind::DepthLimit { variable, limit },
117 message: format!(
118 "{what} nested deeper than {limit} elements ({variable}): read as flat text, \
119 without the item tree and the source blocks"
120 ),
121 }
122 }
123}
124
125/// A single piece of document content.
126#[derive(Debug, Clone, PartialEq)]
127pub enum Node {
128 /// A heading. `level` is 1-6.
129 Heading { level: u8, text: String },
130 /// A run of body text.
131 Paragraph { text: String },
132 /// A form checkbox (docling's `checkbox_selected`/`checkbox_unselected`): its
133 /// clean label `text` with the checked state. DocLang emits a `<checkbox>`
134 /// element head; Markdown/JSON render the task-list form (`- [x] `/`- [ ] `).
135 CheckboxItem { checked: bool, text: String },
136 /// A single list item at the given nesting `level` (0 = top). For ordered
137 /// items, `number` is the display number (honoring the list's `start`); it
138 /// is unused for unordered items. `first_in_list` marks the first item of a
139 /// list so the serializer can blank-line-separate adjacent sibling lists.
140 ///
141 /// `marker` is the DocLang enumeration marker (`"1."`, `"1.1."`, …) when the
142 /// backend provides one — HTML and DOCX set it for enumerated items, so
143 /// DocLang emits `<ldiv><marker>…</marker></ldiv>`; Markdown and the other
144 /// declarative backends leave it `None`, giving a bare `<ldiv/>` (matching
145 /// docling, whose Markdown backend passes no marker).
146 ListItem {
147 ordered: bool,
148 number: u64,
149 first_in_list: bool,
150 text: String,
151 level: u8,
152 marker: Option<String>,
153 /// Optional layout provenance (`x0,y0,x1,y1`, normalized to 0–511): the
154 /// four DocLang `<location>` values emitted inside the `<list>` right
155 /// after the item's `<ldiv>`. Set only by backends with real geometry
156 /// (e.g. PPTX shapes); `None` for the declarative backends. Kept on the
157 /// item itself (rather than a [`Node::Located`] wrapper) so consecutive
158 /// items still group into one `<list>`.
159 location: Option<[u16; 4]>,
160 /// DocLang-only override for items whose DocLang form diverges from their
161 /// flat Markdown `text`. Markdown/JSON always render the fields above; the
162 /// DocLang serializer, when this is `Some`, takes the list kind, marker,
163 /// and content from here instead. Used for docx multilevel numbering
164 /// (Markdown shows `- 1.1. x`, DocLang an ordered `<marker>1.1.</marker>`
165 /// with clean text) and inline equations/formatting in list items.
166 dclx: Option<ListItemDclx>,
167 /// JSON-only: the item as docling's `ListItemMarkerProcessor` leaves
168 /// it on a page pipeline (PDF) — `orig` with the marker, `text`
169 /// without it, the marker itself and whether it enumerates. Markdown
170 /// and DocLang keep reading the fields above, whose spelling follows
171 /// docling-core's serializers (`- [3] text` is a bullet item there).
172 /// `None` for every other backend: the JSON then writes `text` twice
173 /// and `-` or `N.` as before.
174 split: Option<Box<ListItemSplit>>,
175 /// The item's hyperlink target, when its content is a link — docling's
176 /// HTML backend emits it as an `<href uri=…/>` in the item head, and the
177 /// anchor's Markdown link markup is stripped from the rendered content.
178 /// `None` for a plain item; ignored by Markdown/JSON.
179 href: Option<String>,
180 /// Non-body content layer (docling's HTML site chrome before the first
181 /// heading → `furniture`). DocLang emits a `<layer value=…/>` in the item
182 /// head; Markdown/JSON drop a non-body item entirely.
183 layer: Option<ContentLayer>,
184 },
185 /// A fenced code block.
186 Code {
187 language: Option<String>,
188 text: String,
189 /// The original (pre-enrichment) text when the CodeFormula model
190 /// rewrote `text`: docling keeps the raw extraction in the JSON `orig`
191 /// field while `text` carries the model output. `None` → `orig == text`.
192 orig: Option<String>,
193 /// A line-preserving rendering, when the backend can reconstruct one
194 /// but docling's own output for the format cannot. The PDF pipeline
195 /// sets it (docling-parse joins code lines with single spaces, so
196 /// `text` carries that flat docling-parity form): **strict** Markdown
197 /// prefers `pretty`, every byte-conformance surface (legacy Markdown,
198 /// JSON, DocLang, chunks) serializes `text`.
199 pretty: Option<String>,
200 },
201 /// A table. The first row is treated as the header.
202 Table(Table),
203 /// A picture/figure, with an optional caption and (when a backend extracts
204 /// it) the embedded image itself.
205 Picture {
206 caption: Option<String>,
207 /// Hyperlink annotation on the caption (docling's caption text item
208 /// `hyperlink`): the HTML backend sets it when an `<a href>` wraps the
209 /// image whose `alt` became the caption. DocLang emits the block-form
210 /// `<caption>` with an `<href uri=…/>` head; JSON puts `hyperlink` on
211 /// the caption item; Markdown and LaTeX print the plain caption text,
212 /// as docling does.
213 caption_href: Option<String>,
214 image: Option<PictureImage>,
215 /// DocumentPictureClassifier predictions (all classes, descending
216 /// confidence), when the picture-classification enrichment ran.
217 /// Serialized as docling's `classification` annotation + `meta` field
218 /// on the JSON picture item; Markdown/DocLang output is unaffected.
219 classification: Option<Vec<PictureClass>>,
220 /// Text read off the embedded image by the picture-OCR enrichment
221 /// (#645) — docling's `PictureDescriptionData` annotation /
222 /// `meta.description`, which is where upstream's picture-description
223 /// models (VLM captioning) put their text too. JSON and DCLX carry it
224 /// structurally; Markdown prints it between the caption and the
225 /// image placeholder, where docling's picture serializer renders
226 /// annotations. `None` when the enrichment did not run or read no
227 /// text, so every default export stays unchanged.
228 description: Option<PictureDescription>,
229 /// Where the caption item hangs in the JSON tree (#390); see
230 /// [`CaptionParent`]. Markdown, DocLang and LaTeX ignore it.
231 caption_parent: CaptionParent,
232 /// The caption's own box on the picture's page (0–511 grid, like
233 /// [`Node::Located`]) — the PDF pipeline's caption layout region. The
234 /// JSON export writes it as the caption item's `prov` (#609), as
235 /// docling's `ReadingOrderModel._add_caption_or_footnote` does; `None`
236 /// (every declarative backend) leaves the caption without one.
237 caption_location: Option<[u16; 4]>,
238 },
239 /// A display-math formula item decoded by the CodeFormula enrichment:
240 /// `latex` is the model's LaTeX (no `$$` wrapping), `orig` the raw glyph
241 /// text extracted from the PDF. Markdown renders `$$latex$$`; JSON emits a
242 /// `formula` text item (docling's un-enriched pipeline instead emits a
243 /// placeholder paragraph — see the PDF assembler).
244 Formula {
245 latex: String,
246 orig: String,
247 location: Option<[u16; 4]>,
248 },
249 /// A standalone caption item (docling's `DocItemLabel.CAPTION` text that
250 /// no picture or table claims): the HTML backend emits a `<figure>`'s
251 /// `<figcaption>` this way when the figure produced no picture and its
252 /// first item is not a table (docling#4050). `href` is the caption's
253 /// hyperlink annotation (the first link inside the figcaption); Markdown
254 /// renders it as `[text](href)`, JSON puts `hyperlink` on the caption
255 /// item, DocLang emits the block-form `<caption>` with an `<href>` head.
256 Caption { text: String, href: Option<String> },
257 /// A body text item with a docling label of its own and an optional
258 /// hyperlink — the PDF pipeline's `footnote` regions, whose item docling
259 /// keeps as a `footnote` text with the link annotation covering it as its
260 /// `hyperlink` (`PageAssembleModel._match_hyperlink`). The JSON writes
261 /// exactly that (label, raw text, `hyperlink`); every other serializer
262 /// renders it as the paragraph [`Self::labeled_markdown`] spells —
263 /// docling's Markdown wraps a linked item's whole text, `[text](uri)`.
264 LabeledText {
265 label: String,
266 text: String,
267 href: Option<String>,
268 },
269 /// A chart (docling's `PictureItem` classified as a chart, carrying a
270 /// `PictureTabularChartData` annotation). Markdown and JSON render it exactly
271 /// like a [`Node::Picture`] placeholder (an `<!-- image -->` / `picture`
272 /// item); the DocLang serializer emits `<picture class="chart">` with a
273 /// `<label value="{kind}"/>` and the data `table` as a `<tabular>`.
274 Chart {
275 /// docling's classification label, e.g. `bar_chart`, `line_chart`.
276 kind: String,
277 /// The chart's data grid (row 0 is the header band).
278 table: Table,
279 /// The chart title (docling's caption item on the picture).
280 caption: Option<String>,
281 /// DocLang `<location>` provenance for the picture element.
282 location: Option<[u16; 4]>,
283 },
284 /// A logical grouping of child nodes (e.g. a list, a section, a spreadsheet
285 /// sheet). `name` is docling's group name when it differs from the label —
286 /// an xlsx sheet group is `label: "sheet"`, `name: Some("Sheet1")`. `layer`
287 /// puts the group *and* everything it contains on a non-body content layer
288 /// (a hidden sheet is `invisible`), which is how the serializers that only
289 /// render body content know to skip it; DocLang stamps each child with the
290 /// layer token, exactly as a [`Node::Furniture`] wrapper on each would.
291 /// DocLang has no group element, so a group is transparent there.
292 Group {
293 label: String,
294 name: Option<String>,
295 layer: Option<ContentLayer>,
296 children: Vec<Node>,
297 },
298 /// A form key-value region (docling's `field_region`): a set of form fields,
299 /// each pairing an optional marker, key, and value. Backends detect these
300 /// from form structure (e.g. HTML's `keyN` / `keyN_valueM` / `keyN_marker`
301 /// `id`-convention); the serializers render each item's parts as separate
302 /// labelled texts (`marker` / `field_key` / `field_value`).
303 FieldRegion { items: Vec<FieldItem> },
304 /// docling's `KeyValueItem`: a graph of key and value cells and the links
305 /// between them (docling-core's `GraphData`). The XBRL backend builds one
306 /// from an instance's numeric facts and the presentation and calculation
307 /// hierarchies of its taxonomy. Only the JSON export carries the graph:
308 /// docling's Markdown serializer has no rendering for the item and writes
309 /// its `<!-- missing-key-value-item -->` placeholder, which the Markdown
310 /// export reproduces; the other serializers omit it.
311 KeyValueGraph {
312 cells: Vec<GraphCell>,
313 links: Vec<GraphLink>,
314 },
315 /// Rich inline content — docling's `InlineGroup`: a run of styled text
316 /// segments that a backend captured with formatting (`<bold>`, `<italic>`,
317 /// `<underline>`, `<strikethrough>`, sub/superscript, inline `<code>`) the
318 /// flat Markdown text cannot represent. Markdown/JSON render this exactly
319 /// like `Paragraph { text: md_text }` (so their output is unchanged); the
320 /// DocLang serializer uses the structured `runs`. `unwrapped` is set when the
321 /// group's docling parent is a heading/text (no enclosing `<text>` wrapper).
322 InlineGroup {
323 unwrapped: bool,
324 runs: Vec<InlineRun>,
325 md_text: String,
326 },
327 /// A PDF text item whose superscripts and subscripts the opt-in
328 /// script-position stage marked (#1005, docling's `ScriptPositionModel`,
329 /// `script_position_options.enabled`). `inner` is the item — a paragraph
330 /// or a footnote — with its text already the runs' joined text (Markdown-
331 /// escaped, `E = mc2 in 1905.`): every serializer but JSON and DocLang
332 /// renders it as it is. The JSON writes docling's shape — the item with
333 /// an empty `text`, holding an inline group of the runs, each a text item
334 /// with `formatting.script` and the box of its own characters — and
335 /// DocLang writes the runs as an inline group.
336 ScriptText {
337 inner: Box<Node>,
338 runs: Vec<ScriptRun>,
339 },
340 /// A node in a non-body content layer — `furniture` (page headers/footers,
341 /// the HTML `<title>`, site navigation/chrome) or `notes` (docx comments).
342 /// Markdown and JSON omit these layers by default; DocLang renders the wrapped
343 /// node with a `<layer value="{layer}"/>` head.
344 Furniture {
345 layer: ContentLayer,
346 inner: Box<Node>,
347 },
348 /// One reviewer comment: docling's notes-layer `comment_section` group
349 /// holding a single text item. `name` is docling's own — `comment-{id}` for
350 /// a docx `w:comment`, `comment-{sheet}-{cell}` for a spreadsheet cell note.
351 /// JSON emits the group plus its notes-layer text; DocLang emits the flat
352 /// `<text><layer value="notes"/>…</text>` upstream writes (its DocLang
353 /// carries no group for comments); Markdown and LaTeX omit the notes layer.
354 ///
355 /// `refs_note_text` picks what a [`Node::Commented`] annotation points at,
356 /// mirroring an upstream asymmetry: docling-core's `add_comment` appends the
357 /// **note text**'s ref to each target (which is what the xlsx backend gets),
358 /// while the docx backend overwrites that with the **group**'s ref so a
359 /// comment's replies group together.
360 ///
361 /// `grouped` is whether docling wraps the note in a `comment_section`
362 /// group at all: the docx and spreadsheet backends do, while backends that
363 /// call docling-core's `add_comment` directly (Pages, #383) get a bare
364 /// notes-layer text item under the body — JSON then emits no group and
365 /// `name` is unused.
366 CommentSection {
367 name: String,
368 text: String,
369 refs_note_text: bool,
370 grouped: bool,
371 },
372 /// A body item annotated by reviewer comments: `comments` are indices into
373 /// the document's [`Node::CommentSection`] nodes, in document order. JSON
374 /// emits docling's `comments: [{"$ref": …}]` on the item, each ref pointing
375 /// where the section says (see [`Node::CommentSection::refs_note_text`]);
376 /// every other serializer renders `inner` unchanged.
377 Commented {
378 comments: Vec<usize>,
379 inner: Box<Node>,
380 },
381 /// A text node taken from a time-based track — an ASR segment (#614):
382 /// A link destination (#852: a `.doc` bookmark; the DOCX item tree
383 /// keeps its own, #849): the identifier the document's internal links
384 /// (`#id`) point at. Rendered by nothing but the JSON builder, which
385 /// hands it to the next text item for the Pandoc AST (`_anchors`).
386 Anchor { id: String },
387 /// docling's `TrackSource`. The JSON writes docling's ASR text item — `cue`
388 /// (the segment's words) as its text, `track` as its `source: [{"kind":
389 /// "track", …}]` — which the WebVTT export makes a cue of; every other
390 /// serializer renders `inner` (the `[time: start-end] words` paragraph)
391 /// unchanged.
392 Track {
393 track: crate::tree::TreeTrack,
394 cue: String,
395 inner: Box<Node>,
396 },
397 /// A node carrying layout provenance — the four DocLang `<location>` values
398 /// (`x0,y0,x1,y1`, normalized to 0–511) docling attaches to elements from
399 /// backends with real geometry (e.g. the slide shapes in PPTX). Markdown and
400 /// JSON render the wrapped node unchanged; DocLang emits the `<location>`
401 /// tokens as the element's first children.
402 Located {
403 location: [u16; 4],
404 inner: Box<Node>,
405 },
406 /// Exact page provenance for a backend whose geometry already *is* the
407 /// page's coordinate system — an XLSX item's cell-index box on its sheet,
408 /// which docling writes verbatim (`bbox` in a top-left origin, the
409 /// `charspan` the backend chose) and sizes the page from. The 0–511 grid
410 /// of a [`Node::Located`] cannot round-trip such integers exactly, so the
411 /// JSON export reads this wrapper; every other serializer renders `inner`
412 /// unchanged (DocLang keeps taking its `<location>` tokens from the grid).
413 Prov {
414 page_no: usize,
415 /// `[l, t, r, b]`, page units, top-left origin.
416 bbox: [f32; 4],
417 /// docling's `charspan` for the item (`[0, 0]` for an XLSX table).
418 charspan: [usize; 2],
419 /// The bbox's origin: docling's `BOTTOMLEFT` (a PDF page's
420 /// provenance, as a docling-JSON input carries it — #899) or
421 /// `TOPLEFT` (an XLSX sheet's cell box).
422 bottom_left: bool,
423 /// The item's creation rank among its siblings, when that differs
424 /// from the node order: docling numbers `#/tables/N` / `#/texts/N` /
425 /// `#/pictures/N` in the order it *creates* items (a sheet's tables,
426 /// then its images, then its charts) and only afterwards sorts the
427 /// container's children by position. The JSON export adds siblings in
428 /// this order and lays their refs out in node order; `None` when the
429 /// two orders coincide.
430 seq: Option<usize>,
431 inner: Box<Node>,
432 },
433 /// A PDF page header or footer (docling's `page_header`/`page_footer`
434 /// furniture): DocLang emits `<page_header>`/`<page_footer>` with a
435 /// `<layer value="furniture"/>` head, the four `<location>` tokens, then the
436 /// text. The JSON writes it as a body-parented `page_header`/`page_footer`
437 /// text item on the furniture layer; Markdown omits it.
438 PageFurniture {
439 footer: bool,
440 location: [u16; 4],
441 text: String,
442 },
443 /// A furniture-layer text item with an explicit docling label — a page
444 /// header / footer paragraph (`page_header` / `page_footer`) or a note
445 /// body (`footnote`) from a backend that builds no item tree (#535: the
446 /// Word 97 `.doc` stories). The JSON writes a body-parented item of that
447 /// label on the furniture layer; DocLang `<{label}>` with a `<layer
448 /// value="furniture"/>` head (docling-core's own shape); Markdown, LaTeX
449 /// and the chunker leave it out like any furniture.
450 FurnitureText { label: String, text: String },
451 /// The text a PDF picture contains, kept the way docling keeps it: every
452 /// regular layout cluster > 80 % inside a picture cluster is that
453 /// `PictureItem`'s child (`LayoutPostprocessor._set_cluster_children`,
454 /// `ReadingOrderModel._add_child_elements`). Emitted right after its
455 /// picture node. The JSON export writes these nodes as items parented to
456 /// that picture, after its caption; docling's Markdown and LaTeX picture
457 /// serializers print only the caption and the image, so every other
458 /// serializer skips it — except the Markdown export asked to
459 /// `traverse_pictures` ([`MarkdownExportOptions`], #599), which renders
460 /// them after the picture like upstream's item walk does.
461 PictureChildren(Vec<Node>),
462 /// A page boundary — docling's implicit page break between pages. The PPTX
463 /// backend emits one between consecutive slides. DocLang renders it as
464 /// `<page_break/>`; Markdown and JSON omit it (matching docling's default
465 /// exports, which carry page breaks only in the document model).
466 PageBreak,
467 /// A text item docling hangs in a *list group*, after the item before it
468 /// (an AsciiDoc paragraph still pending when a list opened is flushed into
469 /// the list's group): docling-core's list serializer prints it as one more
470 /// line of the list, indented to the group's depth `level` — or, `glue`,
471 /// when it is an inline group, appended to the line before it with no
472 /// separator at all. `text` is Markdown, like a paragraph's. Every other
473 /// serializer reads it as a paragraph.
474 ListText { level: u8, text: String, glue: bool },
475 /// An invisible page marker — the first node of every page the PDF paths
476 /// assemble: the 1-based page number and the page size in PDF points. It
477 /// carries exactly what the JSON export needs to populate docling's
478 /// `pages` map and to denormalize the 0–511 `<location>` grid back into
479 /// BOTTOMLEFT point bboxes for per-item `prov` (#171). Every other
480 /// serializer skips it, so Markdown / DocLang / DocTags output is
481 /// byte-for-byte unchanged.
482 PageInfo {
483 /// 1-based page number (0 = "not yet numbered": the assembler emits
484 /// the marker, the document-level collector stamps the real number).
485 page_no: usize,
486 /// Page width in PDF points.
487 width: f32,
488 /// Page height in PDF points.
489 height: f32,
490 },
491 /// A node docling keeps in the document model (and DocLang) but leaves out
492 /// of the Markdown and JSON exports — e.g. an ODF *presentation*'s pictures
493 /// and charts, which appear in the `.dclx` body but not in its `.md`/`.json`.
494 /// DocLang renders the wrapped node in place; Markdown and JSON skip it.
495 DoclangOnly(Box<Node>),
496 /// A verbatim plain-text dump: one text item holding text whose line
497 /// breaks are content (a nested table flattened to its cells' text, an
498 /// ODF text box's raw text). Markdown/JSON render it as one text block,
499 /// DocLang as one `<text>` whose `<content>` keeps the breaks.
500 TextDump(String),
501}
502
503/// One run of a [`Node::ScriptText`]: a piece of the item's text at one
504/// script position, with its provenance — one entry per page it is on.
505#[derive(Debug, Clone, PartialEq)]
506pub struct ScriptRun {
507 /// The run's raw text (not Markdown-escaped), its spaces included:
508 /// serializers join runs with nothing.
509 pub text: String,
510 pub script: Script,
511 /// The run's provenance, one per page, in text order.
512 pub prov: Vec<ScriptRunProv>,
513 /// The item's link, on its baseline runs (each linked run exports as a
514 /// link of its own, so a marker stays out of it).
515 pub hyperlink: Option<String>,
516}
517
518/// Where a [`ScriptRun`] sits on one page: docling's `ProvenanceItem` with a
519/// bottom-left-origin box.
520#[derive(Debug, Clone, Copy, PartialEq)]
521pub struct ScriptRunProv {
522 /// 1-based page number.
523 pub page_no: usize,
524 /// `[l, t, r, b]`, PDF points, bottom-left origin (`t > b`).
525 pub bbox: [f32; 4],
526 /// The run's characters on this page, as a span of its `text`.
527 pub charspan: [usize; 2],
528}
529
530/// Vertical text position of an [`InlineRun`] — docling's `Script`.
531#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
532pub enum Script {
533 #[default]
534 Baseline,
535 Sub,
536 Super,
537}
538
539/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
540/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
541/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
542/// source text node). A hyperlink is intentionally not stored: DocLang drops the
543/// target inside inline scope, keeping only the anchor text.
544#[derive(Debug, Clone, PartialEq, Eq, Default)]
545pub struct InlineRun {
546 pub text: String,
547 pub bold: bool,
548 pub italic: bool,
549 pub underline: bool,
550 pub strike: bool,
551 pub script: Script,
552 pub code: bool,
553 /// An inline equation (`text` holds LaTeX): DocLang renders `<formula>…`,
554 /// Markdown/JSON keep the `$…$` already baked into the group's `md_text`.
555 pub formula: bool,
556}
557
558/// A DocLang content layer other than the default `body` (see [`Node::Furniture`]).
559#[derive(Debug, Clone, Copy, PartialEq, Eq)]
560pub enum ContentLayer {
561 /// Page headers/footers, HTML `<title>`, site navigation/chrome.
562 Furniture,
563 /// Editorial notes (docx reviewer comments).
564 Notes,
565 /// Invisible content (hidden spreadsheet sheets).
566 Invisible,
567 /// Background content (watermarks): docling-core 2.99's `background`
568 /// layer, which DocLang has and an `invisible` item is written to
569 /// (docling-core#800) — read back from a DocLang document.
570 Background,
571}
572
573impl ContentLayer {
574 /// The `<layer value="…"/>` token value.
575 pub fn value(self) -> &'static str {
576 match self {
577 ContentLayer::Furniture => "furniture",
578 ContentLayer::Notes => "notes",
579 ContentLayer::Invisible => "invisible",
580 ContentLayer::Background => "background",
581 }
582 }
583}
584
585/// A set of content layers, `body` included — docling-core's
586/// `set[ContentLayer]` (`HTMLParams.layers`,
587/// `export_to_html(included_content_layers=…)`), where `body` is a member
588/// like any other. [`Default`] is docling's `DEFAULT_CONTENT_LAYERS`: body
589/// only, so an export built with it is unchanged from before layers could
590/// be chosen (#499).
591#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
592pub struct ContentLayers {
593 /// The main content (items without an explicit layer).
594 pub body: bool,
595 /// [`ContentLayer::Furniture`]: page headers/footers, navigation chrome.
596 pub furniture: bool,
597 /// [`ContentLayer::Notes`]: reviewer comments and other editorial notes.
598 pub notes: bool,
599 /// [`ContentLayer::Invisible`]: hidden content (hidden sheets, …).
600 pub invisible: bool,
601 /// [`ContentLayer::Background`]: background content (watermarks).
602 pub background: bool,
603}
604
605impl Default for ContentLayers {
606 fn default() -> Self {
607 Self::BODY
608 }
609}
610
611impl ContentLayers {
612 /// Body only — docling's `DEFAULT_CONTENT_LAYERS`.
613 pub const BODY: Self = Self {
614 body: true,
615 furniture: false,
616 notes: false,
617 invisible: false,
618 background: false,
619 };
620 /// Every layer — Python's `set(ContentLayer)`.
621 pub const ALL: Self = Self {
622 body: true,
623 furniture: true,
624 notes: true,
625 invisible: true,
626 background: true,
627 };
628 /// No layer at all (nothing renders); build a set from it with
629 /// [`with`](Self::with) / [`with_body`](Self::with_body).
630 pub const NONE: Self = Self {
631 body: false,
632 furniture: false,
633 notes: false,
634 invisible: false,
635 background: false,
636 };
637
638 /// The set plus `layer`.
639 pub const fn with(mut self, layer: ContentLayer) -> Self {
640 match layer {
641 ContentLayer::Furniture => self.furniture = true,
642 ContentLayer::Notes => self.notes = true,
643 ContentLayer::Invisible => self.invisible = true,
644 ContentLayer::Background => self.background = true,
645 }
646 self
647 }
648
649 /// The set plus the body layer.
650 pub const fn with_body(mut self) -> Self {
651 self.body = true;
652 self
653 }
654
655 /// Whether `layer` is in the set; `None` is the body layer.
656 pub fn contains(&self, layer: Option<ContentLayer>) -> bool {
657 match layer {
658 None => self.body,
659 Some(ContentLayer::Furniture) => self.furniture,
660 Some(ContentLayer::Notes) => self.notes,
661 Some(ContentLayer::Invisible) => self.invisible,
662 Some(ContentLayer::Background) => self.background,
663 }
664 }
665
666 /// Whether the layer spelled `name` (`body`, `furniture`, `notes`,
667 /// `invisible`, `background` — the JSON `content_layer` values) is in
668 /// the set; an unknown name is not.
669 pub fn contains_name(&self, name: &str) -> bool {
670 match name {
671 "body" => self.body,
672 "furniture" => self.furniture,
673 "notes" => self.notes,
674 "invisible" => self.invisible,
675 "background" => self.background,
676 _ => false,
677 }
678 }
679
680 /// Parse a comma-separated list of layer names (`body,furniture`;
681 /// whitespace around a name is ignored, `all` is every layer). An
682 /// unknown name is the error.
683 pub fn parse_list(list: &str) -> Result<Self, String> {
684 let mut set = Self::NONE;
685 for name in list.split(',').map(str::trim).filter(|n| !n.is_empty()) {
686 match name {
687 "body" => set.body = true,
688 "furniture" => set.furniture = true,
689 "notes" => set.notes = true,
690 "invisible" => set.invisible = true,
691 "background" => set.background = true,
692 "all" => set = Self::ALL,
693 other => {
694 return Err(format!(
695 "unknown content layer `{other}` (expected body, furniture, notes, invisible, background or all)"
696 ))
697 }
698 }
699 }
700 Ok(set)
701 }
702}
703
704/// Options of the HTML export ([`DoclingDocument::export_to_html_with`]):
705/// docling-core's `HTMLParams` subset the port honours. [`Default`] is
706/// upstream's default export — placeholder images, `artifacts` as the
707/// referenced-image directory, the body layer only.
708#[derive(Debug, Clone, PartialEq, Eq)]
709pub struct HtmlExportOptions {
710 /// How pictures render (`HTMLParams.image_mode`): nothing but captions
711 /// and meta for [`ImageMode::Placeholder`], `data:` URIs when embedded,
712 /// `<img src>` paths under [`artifacts_dir`](Self::artifacts_dir) when
713 /// referenced.
714 pub image_mode: ImageMode,
715 /// The directory referenced images are named under, the Markdown
716 /// export's convention (`<artifacts_dir>/image_NNNNNN.<ext>`).
717 pub artifacts_dir: String,
718 /// The content layers rendered (`HTMLParams.layers`, #499): an item on a
719 /// layer outside the set is skipped, its children still walked — exactly
720 /// how docling-core's `get_excluded_refs` reads the set.
721 pub layers: ContentLayers,
722}
723
724impl Default for HtmlExportOptions {
725 fn default() -> Self {
726 Self {
727 image_mode: ImageMode::Placeholder,
728 artifacts_dir: "artifacts".to_string(),
729 layers: ContentLayers::BODY,
730 }
731 }
732}
733
734/// Options of the Markdown export
735/// ([`DoclingDocument::export_to_markdown_with_options`], #599): the
736/// docling-core `MarkdownParams` the port honours beyond the image mode.
737/// [`Default`] is upstream's default export — placeholder images,
738/// `artifacts` as the referenced-image directory, the body layer only, no
739/// picture traversal, HTML and underscore escaping on, `<!-- image -->` —
740/// so a document exported with it is byte-identical to
741/// [`DoclingDocument::export_to_markdown`].
742#[derive(Debug, Clone, PartialEq, Eq)]
743pub struct MarkdownExportOptions {
744 /// How pictures render (`MarkdownParams.image_mode`): the placeholder,
745 /// `data:` URIs when embedded, ``
746 /// when referenced (the bytes come back for the caller to write).
747 pub image_mode: ImageMode,
748 /// The directory referenced images are named under.
749 pub artifacts_dir: String,
750 /// The content layers rendered (`MarkdownParams.layers`,
751 /// `export_to_markdown(included_content_layers=…)`): an item on a layer
752 /// outside the set is skipped, its children still walked. The default
753 /// body-only set drops page headers/footers (`furniture`), reviewer
754 /// comments (`notes`) and hidden sheets (`invisible`), as upstream does; a
755 /// scanned form's running header reads out with
756 /// `ContentLayers::BODY.with(ContentLayer::Furniture)`. The extra items
757 /// render through the body's serializers — a page header is a paragraph.
758 pub layers: ContentLayers,
759 /// `CommonParams.traverse_pictures`: render the text items nested in a
760 /// picture (the PDF pipeline's picture children — a bordered form laid
761 /// out as one picture holds every field as a child) after the picture's
762 /// own caption and image, as upstream yields them. Off, a picture prints
763 /// only its caption and image.
764 pub traverse_pictures: bool,
765 /// `MarkdownParams.escape_html`: `&`, `<` and `>` in text as `&`,
766 /// `<`, `>` (Python's `html.escape(quote=False)`). Off, `R&D` stays
767 /// `R&D`.
768 pub escape_html: bool,
769 /// `MarkdownParams.escape_underscores`: `_` in text as `\_`. Off, the
770 /// text keeps its underscores.
771 pub escape_underscores: bool,
772 /// `MarkdownParams.image_placeholder`: what a picture prints as when it
773 /// renders no image data (the placeholder mode, or a picture without a
774 /// payload); upstream's `<!-- image -->`.
775 pub image_placeholder: String,
776 /// docling-core's `PlainTextDocSerializer` (#613, `export_to_text`,
777 /// docling's `--to text`): the Markdown walk with the decoration turned
778 /// off — headings without `#`, bold/italic/strikethrough markers and
779 /// inline code backticks dropped, a hyperlink reduced to its label, code
780 /// blocks unfenced, no GFM hard line breaks. List bullets/numbers,
781 /// checkbox marks and table grids stay. [`Self::plain_text`] pairs it
782 /// with upstream's `PlainTextParams` (no escaping, an empty image
783 /// placeholder).
784 pub plain_text: bool,
785}
786
787impl MarkdownExportOptions {
788 /// docling-core's `PlainTextParams` defaults (#613): [`Self::plain_text`]
789 /// on, HTML and underscore escaping off, pictures print nothing (their
790 /// captions still do), body layer only, no picture traversal — what
791 /// `DoclingDocument.export_to_text()` and docling's `--to text` write.
792 pub fn plain_text() -> Self {
793 Self {
794 escape_html: false,
795 escape_underscores: false,
796 image_placeholder: String::new(),
797 plain_text: true,
798 ..Self::default()
799 }
800 }
801}
802
803impl Default for MarkdownExportOptions {
804 fn default() -> Self {
805 Self {
806 image_mode: ImageMode::Placeholder,
807 artifacts_dir: "artifacts".to_string(),
808 layers: ContentLayers::BODY,
809 traverse_pictures: false,
810 escape_html: true,
811 escape_underscores: true,
812 image_placeholder: "<!-- image -->".to_string(),
813 plain_text: false,
814 }
815 }
816}
817
818/// DocLang-only content for a [`Node::ListItem`] whose DocLang form differs from
819/// its flat Markdown `text` (see [`Node::ListItem::dclx`]). `ordered` picks the
820/// enclosing `<list>` kind, `marker` the `<ldiv><marker>`; content is `runs`
821/// (structured equations/formatting) when non-empty, else `text` re-parsed for
822/// inline markers.
823#[derive(Debug, Clone, PartialEq, Eq, Default)]
824pub struct ListItemDclx {
825 pub ordered: bool,
826 pub marker: Option<String>,
827 pub text: String,
828 pub runs: Vec<InlineRun>,
829}
830
831/// A page pipeline's list item as docling's `ListItemMarkerProcessor`
832/// exports it to JSON (see [`Node::ListItem::split`]): the source text
833/// (`orig`), the `marker` split off its head (empty when it has none), the
834/// `text` left, and `enumerated` for a numbered marker of any spelling (`1.`,
835/// `[1]`, `a)`, `iv.`). Plain text, not Markdown-escaped.
836#[derive(Debug, Clone, PartialEq, Eq, Default)]
837pub struct ListItemSplit {
838 pub orig: String,
839 pub marker: String,
840 pub text: String,
841 pub enumerated: bool,
842}
843
844impl Node {
845 /// The paragraph a [`Node::LabeledText`] renders as outside the JSON:
846 /// its text, wrapped as `[text](uri)` when it carries a hyperlink. Any
847 /// other node is returned unchanged.
848 pub fn labeled_as_paragraph(&self) -> std::borrow::Cow<'_, Node> {
849 match self {
850 Node::LabeledText { text, href, .. } => std::borrow::Cow::Owned(Node::Paragraph {
851 text: match href {
852 Some(uri) => crate::hyperlink::markdown_link(text, uri),
853 None => text.clone(),
854 },
855 }),
856 other => std::borrow::Cow::Borrowed(other),
857 }
858 }
859}
860
861impl InlineRun {
862 /// A run with no active formatting (renders as bare inline text).
863 pub fn is_plain(&self) -> bool {
864 !self.bold
865 && !self.italic
866 && !self.underline
867 && !self.strike
868 && !self.code
869 && !self.formula
870 && self.script == Script::Baseline
871 }
872}
873
874/// Build the [`Node`] for a paragraph of inline content from its structured
875/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
876///
877/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
878/// serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
879/// * a single uniformly-formatted run, or two or more runs → a
880/// [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
881/// heading, so no enclosing `<text>`) only applies to multi-run groups.
882///
883/// Markdown/JSON render the group's `md_text`, so their output is identical to
884/// emitting a `Paragraph` — the structured runs are DocLang-only.
885pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
886 let single_plain = runs.len() <= 1 && runs.first().is_none_or(|r| r.is_plain());
887 if single_plain {
888 Node::Paragraph { text: md_text }
889 } else {
890 Node::InlineGroup {
891 unwrapped: unwrapped && runs.len() >= 2,
892 runs,
893 md_text,
894 }
895 }
896}
897
898/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
899/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
900/// / `field_value` child texts.
901#[derive(Debug, Clone, PartialEq, Default)]
902pub struct FieldItem {
903 pub marker: Option<String>,
904 pub key: Option<String>,
905 pub value: Option<String>,
906 /// docling's `kind` on the `field_value` item — `read_only` or
907 /// `fillable` (the value is or holds a form control); JSON-only.
908 pub value_kind: Option<String>,
909}
910
911/// One node of a [`Node::KeyValueGraph`] — docling-core's `GraphCell`.
912#[derive(Debug, Clone, PartialEq)]
913pub struct GraphCell {
914 /// docling's `GraphCellLabel` value: `key` or `value` (it also knows
915 /// `unspecified` and `checkbox`).
916 pub label: String,
917 /// The cell's number within its graph, what the links refer to.
918 pub cell_id: usize,
919 pub text: String,
920 /// The text before any cleanup — for an XBRL fact key, the concept's
921 /// qualified name where `text` is its local name.
922 pub orig: String,
923}
924
925/// One edge of a [`Node::KeyValueGraph`] — docling-core's `GraphLink`.
926#[derive(Debug, Clone, PartialEq)]
927pub struct GraphLink {
928 /// docling's `GraphLinkLabel` value: `to_value`, `to_child`, `to_parent`
929 /// or `to_key`.
930 pub label: String,
931 pub source_cell_id: usize,
932 pub target_cell_id: usize,
933}
934
935/// One DocumentPictureClassifier prediction — docling-core's
936/// `PictureClassificationClass` (`class_name` + `confidence`).
937#[derive(Debug, Clone, PartialEq)]
938pub struct PictureClass {
939 /// e.g. `bar_chart`, `logo`, `signature` (the classifier's 26-label set).
940 pub class_name: String,
941 pub confidence: f32,
942}
943
944/// A picture's text annotation — docling-core's `PictureDescriptionData`
945/// (`text` + `provenance`), the one shape upstream uses for every model that
946/// writes prose about a picture. The picture-OCR enrichment (#645) fills it
947/// with the lines the OCR engine read off the image, `provenance` naming the
948/// engine (`ppocr` / `tesseract`) the way a VLM description names its model.
949#[derive(Debug, Clone, PartialEq, Eq)]
950pub struct PictureDescription {
951 pub text: String,
952 pub provenance: String,
953}
954
955impl PictureDescription {
956 /// The provenance of a picture's author-written alt text (#676): the
957 /// `descr` (else `title`) of an OOXML picture's non-visual properties
958 /// — what DOCX, PPTX and XLSX authors type into "Alt Text". JSON writes
959 /// it as `meta.description.created_by`; Markdown renders it under strict
960 /// Markdown or `DoclingDocument::picture_alt_text`, HTML under the latter.
961 pub const ALT_TEXT: &'static str = "alt_text";
962
963 /// An alt-text description, see [`Self::ALT_TEXT`].
964 pub fn alt_text(text: impl Into<String>) -> Self {
965 Self {
966 text: text.into(),
967 provenance: Self::ALT_TEXT.to_string(),
968 }
969 }
970
971 /// Whether this description is a picture's alt text.
972 pub fn is_alt_text(&self) -> bool {
973 self.provenance == Self::ALT_TEXT
974 }
975
976 /// The (empty) provenance of a description docling's backend writes
977 /// itself as `PictureMeta.description` — `text` only, no `created_by`
978 /// and no legacy `annotations` entry: the alt text of an XLSX image
979 /// placed in a cell (docling#5015). Unlike [`Self::ALT_TEXT`] it is
980 /// upstream's own output, so every format renders it unconditionally.
981 pub const DOCLING_META: &'static str = "";
982
983 /// A docling-native description, see [`Self::DOCLING_META`].
984 pub fn docling_meta(text: impl Into<String>) -> Self {
985 Self {
986 text: text.into(),
987 provenance: Self::DOCLING_META.to_string(),
988 }
989 }
990
991 /// Whether this is a docling-native description ([`Self::DOCLING_META`]).
992 pub fn is_docling_meta(&self) -> bool {
993 self.provenance == Self::DOCLING_META
994 }
995}
996
997/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
998/// the docling.rs analogue of docling-core's `ImageRef`.
999#[derive(Debug, Clone, PartialEq)]
1000pub struct PictureImage {
1001 /// e.g. `image/png`, `image/jpeg`.
1002 pub mimetype: String,
1003 pub width: u32,
1004 pub height: u32,
1005 /// The image file bytes, exactly as embedded (PNG/JPEG/…).
1006 pub data: Vec<u8>,
1007 /// Pixels per inch of the image relative to the page it came from —
1008 /// docling-core's `ImageRef.dpi`, which consumers use to map pixels back
1009 /// to points. A crop rendered from a PDF page at `s` px/pt is `72·s`
1010 /// (docling: `int(72 * images_scale)`, #519); an image embedded in an
1011 /// office file has no render scale and keeps docling's `72`
1012 /// ([`Self::DEFAULT_DPI`]).
1013 pub dpi: u32,
1014 /// The size the picture is *displayed* at in its document, in inches
1015 /// (`[width, height]`, #834): a DOCX drawing's `wp:extent`, an ODT
1016 /// frame's `svg:width` / `svg:height` — not the bitmap's pixel size
1017 /// above, which docling's `ImageRef.size` carries. `None` when the
1018 /// format has no such extent (a PDF crop, a standalone image). The
1019 /// Pandoc export writes it as the `Image`'s `width` / `height`
1020 /// attributes, as Pandoc's own readers do; docling's JSON has no field
1021 /// for it, so the JSON export leaves it out.
1022 pub display_size: Option<[f32; 2]>,
1023}
1024
1025impl PictureImage {
1026 /// docling's `ImageRef` default when no render scale applies.
1027 pub const DEFAULT_DPI: u32 = 72;
1028
1029 /// The `dpi` of an image rendered at `scale` pixels per PDF point
1030 /// (`72·scale`, rounded — `int()` would floor 143.99… to 143).
1031 pub fn dpi_for_scale(scale: f32) -> u32 {
1032 (72.0 * scale).round().max(1.0) as u32
1033 }
1034
1035 /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
1036 pub fn data_uri(&self) -> String {
1037 format!(
1038 "data:{};base64,{}",
1039 self.mimetype,
1040 crate::base64::encode(&self.data)
1041 )
1042 }
1043}
1044
1045/// One table cell as a first-class object (#240) — the Rust counterpart of
1046/// docling's `TableCell`: its text, page geometry, grid rectangle and header
1047/// roles. Produced by the PDF TableFormer paths from the predicted OTSL
1048/// structure; `bbox` is `[l, t, r, b]` in page points with a top-left origin.
1049#[derive(Debug, Clone, PartialEq)]
1050pub struct TableCell {
1051 pub text: String,
1052 /// `[l, t, r, b]`, page points, top-left origin; `None` without geometry.
1053 pub bbox: Option<[f32; 4]>,
1054 /// Anchor grid position (0-based row/column offsets).
1055 pub start_row: usize,
1056 pub start_col: usize,
1057 /// Span extents (≥ 1); the covered grid positions repeat the cell's text
1058 /// in [`Table::rows`].
1059 pub row_span: usize,
1060 pub col_span: usize,
1061 /// OTSL `ched` — a column-header cell.
1062 pub column_header: bool,
1063 /// OTSL `rhed` — a row-header cell.
1064 pub row_header: bool,
1065 /// OTSL `srow` — a section-row cell.
1066 pub row_section: bool,
1067}
1068
1069/// Where a picture's or table's caption text item hangs in the docling-JSON
1070/// tree (#390). docling's backends do not agree, and the JSON structure is
1071/// the only surface that shows it (Markdown, DocLang and LaTeX place a
1072/// caption by its item, whatever its parent): the PDF pipeline parents a
1073/// layout caption to the picture or table it belongs to, while every
1074/// declarative backend creates the caption with `doc.add_text(label=CAPTION)`
1075/// and no parent — the document body — even when the item itself sits in a
1076/// group or under a section header (JATS, LaTeX, HTML, Markdown, EPUB,
1077/// AsciiDoc all do). The office backends hang a chart's title caption off the
1078/// chart's container (the sheet group, the slide, docx's current parent,
1079/// docling#4190) — that is [`Node::Chart`]'s own path, not this choice. A
1080/// backend that adds a new captioned item picks the variant matching
1081/// upstream's `add_text` call for that format; the default is upstream's
1082/// default.
1083#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1084pub enum CaptionParent {
1085 /// `#/body`, listed after the enclosing top-level item — docling's
1086 /// `add_text` default, which every declarative backend leaves alone.
1087 #[default]
1088 Body,
1089 /// The item's own container (its `parent`), listed ahead of the item:
1090 /// the caption is created first, as docling's office backends do.
1091 Container,
1092 /// The item's own container, listed *after* the item: docling's HTML
1093 /// backend adds a `<figure>`-wrapped table, then its `<figcaption>` under
1094 /// `self.parents[self.level]` (docling#4050).
1095 ContainerAfter,
1096 /// The item itself — the caption is the picture's or table's first
1097 /// child, as docling's PDF pipeline attaches a layout caption.
1098 Item,
1099}
1100
1101/// A simple row-major table. By default `rows[0]` is the header row; a
1102/// [`TableStructure`] overlay overrides that and adds column spans.
1103#[derive(Debug, Clone, PartialEq, Default)]
1104pub struct Table {
1105 pub rows: Vec<Vec<String>>,
1106 /// Optional layout provenance: the four DocLang `<location>` values
1107 /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
1108 /// before the table's cells. Set only by backends with real geometry (e.g.
1109 /// the spreadsheet backend, whose cell grid yields a bounding box); left
1110 /// `None` by declarative backends, which have no coordinates.
1111 pub location: Option<[u16; 4]>,
1112 /// Optional OTSL structure overlay for backends that parse real table
1113 /// geometry (USPTO CALS): explicit header-row count and horizontal-span
1114 /// continuations. `None` → the default (row 0 is the header, no spans).
1115 /// `rows` still carries the full text grid (span text replicated) for
1116 /// Markdown/JSON; DocLang uses this overlay to emit `<ched/>`/`<lcel/>`.
1117 pub structure: Option<TableStructure>,
1118 /// Optional per-cell block content, parallel to `rows`. A *rich* cell (an
1119 /// ODF cell holding a list, several paragraphs, or a nested table) carries
1120 /// its DocLang blocks here; the DocLang serializer emits them after the
1121 /// cell token instead of the flat `rows` text. Markdown/JSON ignore this
1122 /// and render `rows`, so their output is unchanged. `None` (or an empty
1123 /// `Vec` for a given cell) → the flat text is used everywhere.
1124 pub cell_blocks: Option<Vec<Vec<Vec<Node>>>>,
1125 /// Optional caption (docling's `TableItem.captions`): the JATS
1126 /// `<table-wrap>` label+caption, an HTML `<caption>`, etc. Markdown renders
1127 /// it as a text line *before* the grid; JSON emits a caption text item the
1128 /// table references; DocLang emits a `<caption>` as the table's first child.
1129 /// `None` → the table has no caption.
1130 pub caption: Option<String>,
1131 /// Where the caption item hangs in the JSON tree (#390); see
1132 /// [`CaptionParent`]. Only the JSON export reads it.
1133 pub caption_parent: CaptionParent,
1134 /// The caption's own box on the table's page (0–511 grid) — the PDF
1135 /// pipeline's caption layout region, written as the caption item's
1136 /// `prov` (#609); see [`Node::Picture`]'s field of the same name.
1137 pub caption_location: Option<[u16; 4]>,
1138 /// The table's footnotes (docling's `TableItem.footnotes`, #1009): one
1139 /// text each, escaped like [`Self::caption`]. Markdown prints them after
1140 /// the grid, one paragraph each; JSON emits `footnote` text items under
1141 /// the table that its `footnotes` list references (docling-core#675).
1142 pub footnotes: Vec<String>,
1143 /// Optional per-cell bounding boxes, same shape as [`Self::rows`]: `[l, t,
1144 /// r, b]` in page points with a **top-left** origin (the PDF pipeline's
1145 /// native space). Set by the ML pipeline's TableFormer paths — a spanned
1146 /// cell repeats its anchor's box across the covered grid positions — and
1147 /// First-class cells (#240): the authoritative per-cell records —
1148 /// text, page geometry, spans and header roles — when the backend
1149 /// produces them (the PDF TableFormer paths do; declarative backends
1150 /// leave `None`). [`Self::rows`] stays the dense text grid every
1151 /// serializer renders (a spanning cell's text is replicated across its
1152 /// covered positions there); JSON serializes these cells verbatim when
1153 /// present, and the DocLang structure overlay is derived from them.
1154 pub cells: Option<Vec<TableCell>>,
1155 /// The table is a table of contents — docling's `document_index` label
1156 /// (#1091), which the PDF layout model gives a TOC region and docling
1157 /// keeps on the `TableItem`. Only the JSON export (and its read-back)
1158 /// tells it apart: every other serializer renders it as a table, as
1159 /// docling-core does.
1160 pub document_index: bool,
1161}
1162
1163impl Table {
1164 /// A cell's text at a grid position, `None` outside the grid.
1165 pub fn cell_text(&self, row: usize, col: usize) -> Option<&str> {
1166 self.rows.get(row)?.get(col).map(String::as_str)
1167 }
1168
1169 /// Replace the text at a grid position; `false` (and no change) outside
1170 /// the grid. When a first-class cell covers the position, the whole
1171 /// cell is updated: its record text and every grid position its span
1172 /// covers, so the repair shows once in Markdown, not once per covered
1173 /// column.
1174 pub fn set_cell_text(&mut self, row: usize, col: usize, text: impl Into<String>) -> bool {
1175 if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
1176 return false;
1177 }
1178 let text = text.into();
1179 let covering = self.cells.as_mut().and_then(|cells| {
1180 cells.iter_mut().find(|c| {
1181 (c.start_row..c.start_row + c.row_span).contains(&row)
1182 && (c.start_col..c.start_col + c.col_span).contains(&col)
1183 })
1184 });
1185 if let Some(cell) = covering {
1186 cell.text = text.clone();
1187 let (r0, r1) = (cell.start_row, cell.start_row + cell.row_span);
1188 let (c0, c1) = (cell.start_col, cell.start_col + cell.col_span);
1189 for r in self.rows.iter_mut().take(r1).skip(r0) {
1190 for slot in r.iter_mut().take(c1).skip(c0) {
1191 *slot = text.clone();
1192 }
1193 }
1194 } else {
1195 self.rows[row][col] = text;
1196 }
1197 true
1198 }
1199
1200 /// Derive first-class cells (#240) from the dense grid plus the
1201 /// [`TableStructure`] overlay — how declarative tables (DOCX/XLSX merged
1202 /// regions, HTML `th`/spans, ODF covered cells, USPTO CALS) get real
1203 /// `TableCell` records without page geometry. Anchors are the positions
1204 /// not marked as span continuations; extents scan the continuation grids
1205 /// right/down (matching the DocLang `lcel`/`ucel` reading). Header roles
1206 /// come from the per-cell `col_header`/`row_header` grids when present,
1207 /// else the `header_row` band, else docling's declarative default (row 0
1208 /// is the header). Without any overlay every position is a 1×1 cell.
1209 pub fn derive_cells(&self) -> Vec<TableCell> {
1210 let s = self.structure.as_ref();
1211 let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| {
1212 grid.and_then(|g| g.get(r))
1213 .and_then(|row| row.get(c))
1214 .copied()
1215 .unwrap_or(false)
1216 };
1217 let col_cont = |r: usize, c: usize| flag(s.map(|s| &s.col_continuation), r, c);
1218 let row_cont = |r: usize, c: usize| flag(s.map(|s| &s.row_continuation), r, c);
1219 let is_col_header = |r: usize, c: usize| match s {
1220 Some(st) if !st.col_header.is_empty() => flag(Some(&st.col_header), r, c),
1221 Some(st) if !st.header_row.is_empty() => st.header_row.get(r).copied().unwrap_or(false),
1222 _ => r == 0,
1223 };
1224 let mut cells = Vec::new();
1225 for (r, row) in self.rows.iter().enumerate() {
1226 for (c, text) in row.iter().enumerate() {
1227 if col_cont(r, c) || row_cont(r, c) {
1228 continue; // covered by a span anchor
1229 }
1230 let mut col_span = 1;
1231 while c + col_span < row.len() && col_cont(r, c + col_span) {
1232 col_span += 1;
1233 }
1234 let mut row_span = 1;
1235 while r + row_span < self.rows.len() && row_cont(r + row_span, c) {
1236 row_span += 1;
1237 }
1238 cells.push(TableCell {
1239 text: text.clone(),
1240 bbox: None,
1241 start_row: r,
1242 start_col: c,
1243 row_span,
1244 col_span,
1245 column_header: is_col_header(r, c),
1246 row_header: flag(s.map(|s| &s.row_header), r, c),
1247 row_section: false,
1248 });
1249 }
1250 }
1251 cells
1252 }
1253
1254 /// The number of leading grid rows that form the column header block —
1255 /// docling-core's `TableData._count_column_header_rows` (docling-core#767,
1256 /// 2.102, #778), shared by the Markdown serializer
1257 /// ([`Self::header_row_count`]) and the chunker's dataframe view, which
1258 /// must agree on where the header ends. Uses the first-class
1259 /// [`Self::cells`] when present (the PDF pipeline's TableFormer flags),
1260 /// else the cells derived from the structure overlay.
1261 ///
1262 /// - A row counts only when a `column_header` cell *starts* on it
1263 /// (docling-core#723): a header spanning several rows is replicated
1264 /// into each row it covers, and counting those would pull the data rows
1265 /// beneath it into the header block.
1266 /// - A row also stops the block when it *carries body text* (#604,
1267 /// docling-core#766): a cell starting on it that is not a column
1268 /// header, has non-blank text and does not start in the table's first
1269 /// column, which holds row labels left unmarked even on header rows. A
1270 /// scanned form flags its first-column labels `column_header` on every
1271 /// row; without the check each such row folded its values into the
1272 /// header.
1273 /// - Row 0 is exempt from that check — model-predicted header rows are
1274 /// often only partly flagged — unless a later row flags a cell starting
1275 /// in the first column: that marks a column of row headers, not a
1276 /// partly flagged header row.
1277 ///
1278 /// No fallback: a table without flags has no header rows here.
1279 pub fn column_header_row_count(&self) -> usize {
1280 if self.rows.is_empty() {
1281 return 0;
1282 }
1283 let derived;
1284 let cells: &[TableCell] = match &self.cells {
1285 Some(c) if !c.is_empty() => c,
1286 _ => {
1287 derived = self.derive_cells();
1288 &derived
1289 }
1290 };
1291 let num_rows = self.rows.len();
1292 let first_col = cells.iter().map(|c| c.start_col).min().unwrap_or(0);
1293 let leading_col_flagged_below = cells.iter().any(|c| {
1294 c.column_header && c.start_col == first_col && (1..num_rows).contains(&c.start_row)
1295 });
1296 let is_header_row = |r: usize| {
1297 let check_body = r > 0 || leading_col_flagged_below;
1298 let mut flagged = false;
1299 for c in cells.iter().filter(|c| c.start_row == r) {
1300 if c.column_header {
1301 flagged = true;
1302 } else if check_body && c.start_col != first_col && !c.text.trim().is_empty() {
1303 return false;
1304 }
1305 }
1306 flagged
1307 };
1308 (0..num_rows).take_while(|&r| is_header_row(r)).count()
1309 }
1310
1311 /// The number of leading grid rows the Markdown serializer renders as the
1312 /// header — docling-core's `_count_header_rows`:
1313 /// [`Self::column_header_row_count`], plus upstream's row-0 fallback for
1314 /// GFM, which needs a header row: `1` when no flag sits on any grid row
1315 /// below the first (a spanning header cell counts on every row it
1316 /// covers), so tables from backends that never set the flag keep row 0
1317 /// as the header. When flags exist but none makes a header row, the
1318 /// count is `0` and every row stays in the body under an empty header.
1319 pub fn header_row_count(&self) -> usize {
1320 let count = self.column_header_row_count();
1321 if count > 0 || self.rows.is_empty() {
1322 return count;
1323 }
1324 let derived;
1325 let cells: &[TableCell] = match &self.cells {
1326 Some(c) if !c.is_empty() => c,
1327 _ => {
1328 derived = self.derive_cells();
1329 &derived
1330 }
1331 };
1332 if cells
1333 .iter()
1334 .any(|c| c.column_header && c.start_row + c.row_span.max(1) > 1)
1335 {
1336 0
1337 } else {
1338 1
1339 }
1340 }
1341
1342 /// For every grid position, the position of the cell that covers it — its
1343 /// anchor (top-left start): itself for an unmerged position, the merge's
1344 /// start for one a spanning cell covers. Uses the first-class
1345 /// [`Self::cells`] when present, else the cells derived from the
1346 /// structure overlay. A rich cell's blocks ([`Self::cell_blocks`]) live on
1347 /// its anchor only, so a serializer that repeats a merged cell in every
1348 /// position it covers (docling-core#857) reads them through this.
1349 pub fn span_anchors(&self) -> Vec<Vec<(usize, usize)>> {
1350 let num_cols = self.rows.iter().map(Vec::len).max().unwrap_or(0);
1351 let mut anchors: Vec<Vec<(usize, usize)>> = (0..self.rows.len())
1352 .map(|r| (0..num_cols).map(|c| (r, c)).collect())
1353 .collect();
1354 let derived;
1355 let cells: &[TableCell] = match &self.cells {
1356 Some(c) if !c.is_empty() => c,
1357 _ => {
1358 derived = self.derive_cells();
1359 &derived
1360 }
1361 };
1362 for cell in cells {
1363 let rows = cell.start_row..cell.start_row + cell.row_span.max(1);
1364 for row in anchors.iter_mut().take(rows.end).skip(rows.start) {
1365 let cols = cell.start_col..cell.start_col + cell.col_span.max(1);
1366 for pos in row.iter_mut().take(cols.end).skip(cols.start) {
1367 *pos = (cell.start_row, cell.start_col);
1368 }
1369 }
1370 }
1371 anchors
1372 }
1373
1374 /// The first-class cell covering a grid position, if any.
1375 pub fn cell_at(&self, row: usize, col: usize) -> Option<&TableCell> {
1376 self.cells.as_ref()?.iter().find(|c| {
1377 (c.start_row..c.start_row + c.row_span).contains(&row)
1378 && (c.start_col..c.start_col + c.col_span).contains(&col)
1379 })
1380 }
1381
1382 /// A cell's bounding box (`[l, t, r, b]`, page points, top-left origin);
1383 /// `None` when no cell with geometry covers the position.
1384 pub fn cell_bbox(&self, row: usize, col: usize) -> Option<[f32; 4]> {
1385 self.cell_at(row, col)?.bbox
1386 }
1387
1388 /// Set (or replace) the bounding box of the cell covering a grid
1389 /// position; `false` outside the text grid. A table without first-class
1390 /// cells materializes them first (one 1×1 cell per grid position, texts
1391 /// from the grid), so declarative tables can be annotated too.
1392 pub fn set_cell_bbox(&mut self, row: usize, col: usize, bbox: [f32; 4]) -> bool {
1393 if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
1394 return false;
1395 }
1396 let rows = &self.rows;
1397 let cells = self.cells.get_or_insert_with(|| {
1398 rows.iter()
1399 .enumerate()
1400 .flat_map(|(r, cols)| {
1401 cols.iter().enumerate().map(move |(c, text)| TableCell {
1402 text: text.clone(),
1403 bbox: None,
1404 start_row: r,
1405 start_col: c,
1406 row_span: 1,
1407 col_span: 1,
1408 column_header: false,
1409 row_header: false,
1410 row_section: false,
1411 })
1412 })
1413 .collect()
1414 });
1415 match cells.iter_mut().find(|c| {
1416 (c.start_row..c.start_row + c.row_span).contains(&row)
1417 && (c.start_col..c.start_col + c.col_span).contains(&col)
1418 }) {
1419 Some(cell) => {
1420 cell.bbox = Some(bbox);
1421 true
1422 }
1423 None => {
1424 cells.push(TableCell {
1425 text: self.rows[row][col].clone(),
1426 bbox: Some(bbox),
1427 start_row: row,
1428 start_col: col,
1429 row_span: 1,
1430 col_span: 1,
1431 column_header: false,
1432 row_header: false,
1433 row_section: false,
1434 });
1435 true
1436 }
1437 }
1438 }
1439
1440 /// The anchor position of the cell whose box overlaps `bbox` best
1441 /// (largest intersection-over-union), ties resolved in cell order.
1442 /// `None` when nothing overlaps or the table carries no geometry. This
1443 /// is the lookup half of the repair workflow: find the cell an external
1444 /// OCR box refers to, then [`Self::set_cell_text`] it.
1445 pub fn find_cell_by_bbox(&self, bbox: [f32; 4]) -> Option<(usize, usize)> {
1446 let area = |b: &[f32; 4]| ((b[2] - b[0]) * (b[3] - b[1])).max(0.0);
1447 let mut best: Option<(f32, (usize, usize))> = None;
1448 for cell in self.cells.as_deref()?.iter() {
1449 let Some(cb) = cell.bbox else { continue };
1450 let iw = (bbox[2].min(cb[2]) - bbox[0].max(cb[0])).max(0.0);
1451 let ih = (bbox[3].min(cb[3]) - bbox[1].max(cb[1])).max(0.0);
1452 let inter = iw * ih;
1453 if inter <= 0.0 {
1454 continue;
1455 }
1456 let iou = inter / (area(&bbox) + area(&cb) - inter).max(f32::EPSILON);
1457 if best.is_none_or(|(b, _)| iou > b) {
1458 best = Some((iou, (cell.start_row, cell.start_col)));
1459 }
1460 }
1461 best.map(|(_, pos)| pos)
1462 }
1463
1464 /// Locate the cell overlapping `bbox` best and replace its text — the
1465 /// one-call form of the OCR-repair loop. Returns the updated anchor.
1466 pub fn update_cell_by_bbox(
1467 &mut self,
1468 bbox: [f32; 4],
1469 text: impl Into<String>,
1470 ) -> Option<(usize, usize)> {
1471 let (row, col) = self.find_cell_by_bbox(bbox)?;
1472 self.set_cell_text(row, col, text);
1473 Some((row, col))
1474 }
1475}
1476
1477/// OTSL structure overlay for a [`Table`], parallel to [`Table::rows`].
1478#[derive(Debug, Clone, PartialEq, Default)]
1479pub struct TableStructure {
1480 /// Per-row: `true` if the row's non-empty cells are column headers
1481 /// (emitted as `<ched/>` rather than `<fcel/>`).
1482 pub header_row: Vec<bool>,
1483 /// Same shape as [`Table::rows`]; `true` where a cell continues a
1484 /// horizontal span from its left neighbour (emitted as `<lcel/>`).
1485 pub col_continuation: Vec<Vec<bool>>,
1486 /// Same shape as [`Table::rows`]; `true` where a cell continues a
1487 /// vertical span from the cell above (emitted as `<ucel/>`). Empty or all
1488 /// `false` when the backend has no vertical spans (e.g. USPTO CALS).
1489 pub row_continuation: Vec<Vec<bool>>,
1490 /// Same shape as [`Table::rows`]; `true` where a non-empty cell is a row
1491 /// header (emitted as `<rhed/>`) — a chart's category column. Empty when
1492 /// the table has no row headers.
1493 pub row_header: Vec<Vec<bool>>,
1494 /// Same shape as [`Table::rows`]; `true` where a cell is a *column header*
1495 /// cell (an HTML `<th>`). When non-empty this per-cell grid supersedes the
1496 /// per-row [`Self::header_row`] for `<ched/>` emission, matching docling's
1497 /// cell-level `column_header` flag; the chunker derives its header-row
1498 /// count from it.
1499 pub col_header: Vec<Vec<bool>>,
1500}
1501
1502/// [`for_each_picture_in_mut`], read-only: every picture in `nodes`, however
1503/// nested, for a pass that only looks (the DocLang asset digests, #898).
1504pub fn for_each_picture_in<'a>(nodes: &'a [Node], f: &mut dyn FnMut(&'a Node)) {
1505 for node in nodes {
1506 match node {
1507 Node::Picture { .. } => f(node),
1508 Node::Group { children, .. } | Node::PictureChildren(children) => {
1509 for_each_picture_in(children, f)
1510 }
1511 Node::Located { inner, .. }
1512 | Node::Prov { inner, .. }
1513 | Node::Track { inner, .. }
1514 | Node::Furniture { inner, .. }
1515 | Node::Commented { inner, .. }
1516 | Node::DoclangOnly(inner) => for_each_picture_in(std::slice::from_ref(inner), f),
1517 Node::Table(t) => {
1518 if let Some(blocks) = t.cell_blocks.as_ref() {
1519 for row in blocks {
1520 for cell in row {
1521 for_each_picture_in(cell, f);
1522 }
1523 }
1524 }
1525 }
1526 _ => {}
1527 }
1528 }
1529}
1530
1531/// [`DoclingDocument::for_each_picture_mut`] over a node slice — every
1532/// picture in `nodes`, however nested (groups, wrappers, table cell blocks),
1533/// for a caller that holds page batches rather than a document (the
1534/// streaming PDF path, #896).
1535pub fn for_each_picture_in_mut(nodes: &mut [Node], f: &mut dyn FnMut(&mut Node)) {
1536 for node in nodes {
1537 match node {
1538 Node::Picture { .. } => f(node),
1539 Node::Group { children, .. } | Node::PictureChildren(children) => {
1540 for_each_picture_in_mut(children, f)
1541 }
1542 Node::Located { inner, .. }
1543 | Node::Prov { inner, .. }
1544 | Node::Track { inner, .. }
1545 | Node::Furniture { inner, .. }
1546 | Node::Commented { inner, .. }
1547 | Node::DoclangOnly(inner) => for_each_picture_in_mut(std::slice::from_mut(inner), f),
1548 Node::Table(t) => {
1549 if let Some(blocks) = t.cell_blocks.as_mut() {
1550 for row in blocks {
1551 for cell in row {
1552 for_each_picture_in_mut(cell, f);
1553 }
1554 }
1555 }
1556 }
1557 _ => {}
1558 }
1559 }
1560}
1561
1562impl DoclingDocument {
1563 /// Create an empty document with the given name.
1564 pub fn new(name: impl Into<String>) -> Self {
1565 Self {
1566 name: name.into(),
1567 nodes: Vec::new(),
1568 strict_markdown: false,
1569 compact_tables: false,
1570 picture_alt_text: false,
1571 metadata: Default::default(),
1572 metadata_output: Default::default(),
1573 page_break_placeholder: None,
1574 links: Vec::new(),
1575 confidence: None,
1576 tree: None,
1577 page_images: std::collections::BTreeMap::new(),
1578 notices: Vec::new(),
1579 }
1580 }
1581
1582 /// Append a node.
1583 /// The document's top-level tables in reading order — the read half of
1584 /// the post-extraction table API (#238). [`Node::Located`] wrappers (the
1585 /// PDF pipeline attaches layout provenance that way) are looked through;
1586 /// tables nested inside rich table cells (`Table::cell_blocks`) are not
1587 /// traversed.
1588 pub fn tables(&self) -> impl Iterator<Item = &Table> {
1589 fn unwrap_table(n: &Node) -> Option<&Table> {
1590 match n {
1591 Node::Table(t) => Some(t),
1592 Node::Located { inner, .. }
1593 | Node::Prov { inner, .. }
1594 | Node::Track { inner, .. } => unwrap_table(inner),
1595 _ => None,
1596 }
1597 }
1598 self.nodes.iter().filter_map(unwrap_table)
1599 }
1600
1601 /// Mutable access to the document's top-level tables, for repair
1602 /// workflows (#238): locate a cell via [`Table::find_cell_by_bbox`], fix
1603 /// its text with [`Table::set_cell_text`], then re-export — every
1604 /// serializer reads the same grid.
1605 pub fn tables_mut(&mut self) -> impl Iterator<Item = &mut Table> {
1606 fn unwrap_table(n: &mut Node) -> Option<&mut Table> {
1607 match n {
1608 Node::Table(t) => Some(t),
1609 Node::Located { inner, .. }
1610 | Node::Prov { inner, .. }
1611 | Node::Track { inner, .. } => unwrap_table(inner),
1612 _ => None,
1613 }
1614 }
1615 self.nodes.iter_mut().filter_map(unwrap_table)
1616 }
1617
1618 pub fn push(&mut self, node: Node) {
1619 self.nodes.push(node);
1620 }
1621
1622 /// Visit every [`Node::Picture`] in the flat node stream, wherever it
1623 /// nests — group children, table cell blocks, a picture's own
1624 /// children, the located/prov/track/comment/furniture wrappers — so an
1625 /// enrichment that reads the embedded images (picture OCR, #645) reaches
1626 /// each one. The callback gets the picture node itself.
1627 pub fn for_each_picture_mut(&mut self, f: &mut dyn FnMut(&mut Node)) {
1628 for_each_picture_in_mut(&mut self.nodes, f);
1629 }
1630
1631 /// Change the unit the pages are measured in: every length in page units
1632 /// — each [`Node::PageInfo`] size, a [`Node::Prov`] box, a first-class
1633 /// table cell's box, a script run's box — is multiplied by `sx`
1634 /// horizontally and `sy` vertically, and every image's `dpi` (its pixels
1635 /// per inch *of the page unit*: a picture crop, a page image) is divided
1636 /// by `sx`, so the same pixels still cover the same part of the page. The
1637 /// 0–511 `<location>` grid is relative to the page and needs nothing. The
1638 /// image input sizes its page from the file's resolution this way once
1639 /// the models have run on its pixels (#1093).
1640 pub fn rescale_page_units(&mut self, sx: f32, sy: f32) {
1641 let scale_box = |b: &mut [f32; 4]| {
1642 b[0] *= sx;
1643 b[1] *= sy;
1644 b[2] *= sx;
1645 b[3] *= sy;
1646 };
1647 let scale_dpi = |img: &mut PictureImage| {
1648 img.dpi = (img.dpi as f32 / sx).round().max(1.0) as u32;
1649 };
1650 fn table(t: &mut Table, scale_box: &dyn Fn(&mut [f32; 4]), walk: &dyn Fn(&mut [Node])) {
1651 for cell in t.cells.iter_mut().flatten() {
1652 if let Some(b) = cell.bbox.as_mut() {
1653 scale_box(b);
1654 }
1655 }
1656 for row in t.cell_blocks.iter_mut().flatten() {
1657 for cell in row {
1658 walk(cell);
1659 }
1660 }
1661 }
1662 fn walk(
1663 nodes: &mut [Node],
1664 sx: f32,
1665 sy: f32,
1666 scale_box: &dyn Fn(&mut [f32; 4]),
1667 scale_dpi: &dyn Fn(&mut PictureImage),
1668 ) {
1669 let recurse = |n: &mut [Node]| walk(n, sx, sy, scale_box, scale_dpi);
1670 for node in nodes {
1671 match node {
1672 Node::PageInfo { width, height, .. } => {
1673 *width *= sx;
1674 *height *= sy;
1675 }
1676 Node::Prov { bbox, inner, .. } => {
1677 scale_box(bbox);
1678 recurse(std::slice::from_mut(inner));
1679 }
1680 Node::ScriptText { inner, runs } => {
1681 for run in runs {
1682 for prov in &mut run.prov {
1683 scale_box(&mut prov.bbox);
1684 }
1685 }
1686 recurse(std::slice::from_mut(inner));
1687 }
1688 Node::Located { inner, .. }
1689 | Node::Track { inner, .. }
1690 | Node::Furniture { inner, .. }
1691 | Node::Commented { inner, .. }
1692 | Node::DoclangOnly(inner) => recurse(std::slice::from_mut(inner)),
1693 Node::Group { children, .. } | Node::PictureChildren(children) => {
1694 recurse(children)
1695 }
1696 Node::Table(t) | Node::Chart { table: t, .. } => table(t, scale_box, &recurse),
1697 Node::Picture {
1698 image: Some(img), ..
1699 } => scale_dpi(img),
1700 _ => {}
1701 }
1702 }
1703 }
1704 walk(&mut self.nodes, sx, sy, &scale_box, &scale_dpi);
1705 for img in self.page_images.values_mut() {
1706 scale_dpi(img);
1707 }
1708 }
1709
1710 /// Convenience: append a heading.
1711 pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
1712 self.push(Node::Heading {
1713 level,
1714 text: text.into(),
1715 });
1716 }
1717
1718 /// Convenience: append a paragraph.
1719 pub fn add_paragraph(&mut self, text: impl Into<String>) {
1720 self.push(Node::Paragraph { text: text.into() });
1721 }
1722
1723 /// Serialize the document to Markdown.
1724 ///
1725 /// The Rust equivalent of docling-core's
1726 /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
1727 /// pick between docling-legacy output (default) and the cleaner, more
1728 /// conformant variant.
1729 pub fn export_to_markdown(&self) -> String {
1730 to_markdown(self, self.strict_markdown)
1731 }
1732
1733 /// Serialize to Markdown, explicitly choosing the mode regardless of
1734 /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
1735 /// conformant Markdown (code-fence languages preserved, no inline-run
1736 /// spacing artifacts); `strict = false` reproduces docling's legacy output.
1737 pub fn export_to_markdown_with(&self, strict: bool) -> String {
1738 to_markdown(self, strict)
1739 }
1740
1741 /// Markdown for this document as the *content of a rich table cell*
1742 /// (docling-core's `in_table_cell` serialization, docling-core#540):
1743 /// headings render as plain text since Markdown tables can't hold them.
1744 /// Backends build a sub-document per rich cell and flatten this into the
1745 /// cell text; no trailing newline.
1746 pub fn export_to_table_cell_markdown(&self) -> String {
1747 crate::markdown::to_markdown_table_cell(self, self.strict_markdown)
1748 }
1749
1750 /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
1751 /// schema), pretty-printed — the Rust equivalent of
1752 /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
1753 /// back into Python docling-core and round-trips to the same Markdown.
1754 pub fn export_to_json(&self) -> String {
1755 let mut out = Vec::new();
1756 self.write_json_pretty(&mut out)
1757 .expect("DoclingDocument JSON is always serializable");
1758 String::from_utf8(out).expect("serde_json writes UTF-8")
1759 }
1760
1761 /// The same JSON wire format as [`Self::export_to_json`], as a
1762 /// `serde_json::Value` — for callers that append response-level extras
1763 /// (docling-serve adds the confidence report, #183) before serializing.
1764 ///
1765 /// The `Value` is large — ~2.7 KB per text item — so on a long document
1766 /// prefer [`Self::write_json`], which writes the same JSON without it.
1767 pub fn export_to_json_value(&self) -> serde_json::Value {
1768 crate::json::to_json(self)
1769 }
1770
1771 /// Write the JSON of [`Self::export_to_json_value`] to `writer`, compact
1772 /// — byte for byte `serde_json::to_writer(writer, &doc.export_to_json_value())`
1773 /// — without building the `Value`: the export holds its text items in a
1774 /// compact form and serializes them straight to the writer. Wrap a file
1775 /// or socket in a `BufWriter`.
1776 pub fn write_json<W: std::io::Write>(&self, writer: W) -> std::io::Result<()> {
1777 crate::json::write_json(self, writer, false).map_err(std::io::Error::from)
1778 }
1779
1780 /// [`Self::write_json`], indented as [`Self::export_to_json`] is.
1781 pub fn write_json_pretty<W: std::io::Write>(&self, writer: W) -> std::io::Result<()> {
1782 crate::json::write_json(self, writer, true).map_err(std::io::Error::from)
1783 }
1784
1785 /// [`Self::write_json_pretty`] with `extras` appended to the top-level
1786 /// object after `pages` — byte for byte `serde_json::to_writer_pretty`
1787 /// of [`Self::export_to_json_value`] with each `value[key] = v` set (a
1788 /// key the document JSON does not have), without building that `Value`:
1789 /// docling-serve's response adds its `confidence` report this way.
1790 pub fn write_json_pretty_with<W: std::io::Write>(
1791 &self,
1792 writer: W,
1793 extras: &[(&str, &serde_json::Value)],
1794 ) -> std::io::Result<()> {
1795 crate::json::write_json_with(self, writer, true, extras).map_err(std::io::Error::from)
1796 }
1797
1798 /// Serialize to a complete LaTeX document — the Rust counterpart of
1799 /// docling-core's `LaTeXDocSerializer` with default parameters (docling
1800 /// 2.124's `--to latex`, #317). No trailing newline, like the upstream
1801 /// CLI's `<stem>.tex`.
1802 pub fn export_to_latex(&self) -> String {
1803 crate::latex::to_latex(self)
1804 }
1805
1806 /// Serialize to Pandoc's AST as JSON (`pandoc -f json`, #515) with the
1807 /// default options: pictures as captioned figures without image data,
1808 /// body layer only, the [`PANDOC_API_VERSION`](crate::pandoc::PANDOC_API_VERSION)
1809 /// API. One line, no trailing newline. See [`crate::pandoc`].
1810 pub fn export_to_pandoc_json(&self) -> String {
1811 crate::pandoc::to_pandoc(self, &crate::pandoc::PandocExportOptions::default())
1812 .expect("the default Pandoc API version is always supported")
1813 .0
1814 }
1815
1816 /// Pandoc JSON per `options` (image mode, artifacts directory, content
1817 /// layers, required API version). Returns the JSON and, for
1818 /// [`ImageMode::Referenced`], the `(path, bytes)` image files; an
1819 /// unsupported `api_version` is an error.
1820 pub fn export_to_pandoc_json_with(
1821 &self,
1822 options: &crate::pandoc::PandocExportOptions,
1823 ) -> Result<crate::pandoc::PandocOutput, crate::pandoc::PandocError> {
1824 crate::pandoc::to_pandoc(self, options)
1825 }
1826
1827 /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
1828 /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
1829 /// `export_to_doclang()` with default parameters. No trailing newline; the
1830 /// archive writer appends exactly one.
1831 pub fn export_to_doclang(&self) -> String {
1832 self.export_doclang(crate::doclang::Pictures::Referenced { collect: false })
1833 .0
1834 }
1835
1836 /// [`Self::export_to_doclang`] plus the picture assets its
1837 /// `<src uri="assets/image_….png"/>` references name, as `(path, bytes)`
1838 /// in document order — the parts docling's `save_as_doclang_archive`
1839 /// stores next to `document.xml`. PNG and JPEG pictures come back as PNG
1840 /// (a JPEG re-encoded from its libjpeg-decoded pixels); other encodings
1841 /// keep their own bytes for the archive writer to convert.
1842 pub fn export_to_doclang_with_assets(&self) -> (String, Vec<(String, Vec<u8>)>) {
1843 self.export_doclang(crate::doclang::Pictures::Referenced { collect: true })
1844 }
1845
1846 /// DocLang with docling's `image_mode` for pictures (#884):
1847 /// [`ImageMode::Placeholder`] writes no `<src>` — docling-core's own
1848 /// `export_to_doclang()` default, which upstream's `.dclg` fixtures hold
1849 /// — [`ImageMode::Embedded`] a `data:` URI of the PNG,
1850 /// [`ImageMode::Referenced`] is [`Self::export_to_doclang_with_assets`].
1851 pub fn export_to_doclang_with_images(
1852 &self,
1853 mode: ImageMode,
1854 ) -> (String, Vec<(String, Vec<u8>)>) {
1855 use crate::doclang::Pictures;
1856 self.export_doclang(match mode {
1857 ImageMode::Placeholder => Pictures::Placeholder,
1858 ImageMode::Embedded => Pictures::Embedded,
1859 ImageMode::Referenced => Pictures::Referenced { collect: true },
1860 })
1861 }
1862
1863 /// The item tree's DocLang — docling-core's `DocLangDocSerializer`
1864 /// ported over the tree (`doclang_tree.rs`, #884), the structure the
1865 /// JSON export writes — else (no tree, or one the port does not cover:
1866 /// provenance, picture meta, form fields) the nodes'. The flat nodes
1867 /// cannot carry a footnote's label, a caption's or a cell's inline
1868 /// formulas, text docling never wrote as Markdown, or the whitespace of
1869 /// an inline group's runs, which DocLang 0.9 reads as written.
1870 fn export_doclang(
1871 &self,
1872 pictures: crate::doclang::Pictures,
1873 ) -> (String, Vec<(String, Vec<u8>)>) {
1874 self.tree
1875 .as_ref()
1876 .filter(|t| !t.doclang_nodes)
1877 .and_then(|t| crate::doclang_tree::export(t, pictures))
1878 .unwrap_or_else(|| crate::doclang::render(&self.nodes, pictures))
1879 }
1880
1881 /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
1882 /// docling's `image_mode`). Returns the Markdown and, for
1883 /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
1884 /// caller should write next to the Markdown file. `artifacts_dir` is the
1885 /// directory name used in referenced links.
1886 pub fn export_to_markdown_with_images(
1887 &self,
1888 image_mode: ImageMode,
1889 artifacts_dir: &str,
1890 ) -> (String, Vec<(String, Vec<u8>)>) {
1891 to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
1892 }
1893
1894 /// Markdown per `options` (#599) — docling-core's
1895 /// `export_to_markdown(included_content_layers=…, image_mode=…,
1896 /// image_placeholder=…, escape_html=…, escape_underscores=…,
1897 /// traverse_pictures=…)`: the content layers rendered, whether a
1898 /// picture's nested text items print, HTML and underscore escaping, the
1899 /// image placeholder, and the image mode with its referenced-image
1900 /// directory. [`Self::strict_markdown`] still picks the Markdown flavour.
1901 /// Returns the Markdown and, for [`ImageMode::Referenced`], the
1902 /// `(path, bytes)` artifacts. With [`MarkdownExportOptions::default`]
1903 /// the Markdown is [`Self::export_to_markdown`]'s byte for byte.
1904 pub fn export_to_markdown_with_options(
1905 &self,
1906 options: &MarkdownExportOptions,
1907 ) -> (String, Vec<(String, Vec<u8>)>) {
1908 crate::markdown::to_markdown_with_options(self, self.strict_markdown, options)
1909 }
1910
1911 /// WebVTT (#614) — what docling's `--to vtt` writes
1912 /// (`DoclingDocument.save_as_vtt`): a cue per timed text item — a WebVTT
1913 /// input's cues, an audio/video transcript's segments — hours always
1914 /// written, the `</v>` of a lone voice span omitted. A document without
1915 /// timed text is the bare `WEBVTT` header. No trailing newline.
1916 pub fn export_to_vtt(&self) -> String {
1917 crate::vtt::to_vtt(self, &crate::vtt::VttExportOptions::default())
1918 }
1919
1920 /// [`Self::export_to_vtt`] with docling-core's `WebVTTParams`
1921 /// (`omit_hours_if_zero`, `omit_voice_end`).
1922 pub fn export_to_vtt_with_options(&self, options: &crate::vtt::VttExportOptions) -> String {
1923 crate::vtt::to_vtt(self, options)
1924 }
1925
1926 /// Plain text — docling-core's `DoclingDocument.export_to_text()` with
1927 /// its defaults (#613, docling's `--to text` / `<stem>.txt`): the
1928 /// Markdown export without decoration ([`MarkdownExportOptions::plain_text`]).
1929 /// Lists keep their bullets and numbers, tables their `|` grid. No
1930 /// trailing newline: upstream's `serialize().text`, which its CLI
1931 /// writes verbatim to `<stem>.txt`.
1932 pub fn export_to_text(&self) -> String {
1933 let (mut text, _) = crate::markdown::to_markdown_with_options(
1934 self,
1935 self.strict_markdown,
1936 &MarkdownExportOptions::plain_text(),
1937 );
1938 if text.ends_with('\n') {
1939 text.pop();
1940 }
1941 text
1942 }
1943
1944 /// A complete HTML document — docling-core's `HTMLDocSerializer` with its
1945 /// defaults (#492): pictures stay out (`ImageRefMode.PLACEHOLDER`, only
1946 /// their captions and meta render). See [`export_to_html_with_images`]
1947 /// for the embedded / referenced modes and [`crate::html`]'s module docs
1948 /// for what is reproduced.
1949 ///
1950 /// [`export_to_html_with_images`]: Self::export_to_html_with_images
1951 pub fn export_to_html(&self) -> String {
1952 crate::html::to_html(self, &HtmlExportOptions::default()).0
1953 }
1954
1955 /// HTML with pictures per `image_mode`: `data:` URIs when embedded, and
1956 /// when referenced `<img src>` paths under `artifacts_dir` whose bytes come
1957 /// back as `(path, bytes)` for the caller to write — the Markdown export's
1958 /// contract and file names.
1959 pub fn export_to_html_with_images(
1960 &self,
1961 image_mode: ImageMode,
1962 artifacts_dir: &str,
1963 ) -> (String, Vec<(String, Vec<u8>)>) {
1964 crate::html::to_html(
1965 self,
1966 &HtmlExportOptions {
1967 image_mode,
1968 artifacts_dir: artifacts_dir.to_string(),
1969 ..HtmlExportOptions::default()
1970 },
1971 )
1972 }
1973
1974 /// HTML rendering the content `layers` — docling-core's
1975 /// `export_to_html(included_content_layers=…)` (#499). The default export
1976 /// is body only; `ContentLayers::BODY.with(ContentLayer::Furniture)` adds
1977 /// page headers/footers, `.with(ContentLayer::Notes)` reviewer comments,
1978 /// [`ContentLayers::ALL`] is Python's `set(ContentLayer)`. An item on a
1979 /// layer outside the set is skipped while its children are still walked,
1980 /// and the items that do render go through the same serializers as the
1981 /// body (a page header is a `<p>`, a comment a `<p>`, a header table a
1982 /// `<table>`), exactly as upstream's `HTMLParams.layers` behaves. Pictures
1983 /// stay placeholders; see [`export_to_html_with`] for the full option set.
1984 ///
1985 /// [`export_to_html_with`]: Self::export_to_html_with
1986 pub fn export_to_html_with_layers(&self, layers: ContentLayers) -> String {
1987 crate::html::to_html(
1988 self,
1989 &HtmlExportOptions {
1990 layers,
1991 ..HtmlExportOptions::default()
1992 },
1993 )
1994 .0
1995 }
1996
1997 /// HTML per `options` — image mode, referenced-image directory and content
1998 /// layers in one call; the other `export_to_html*` methods are
1999 /// shorthands for it. Returns the HTML and, for
2000 /// [`ImageMode::Referenced`], the `(path, bytes)` artifacts.
2001 pub fn export_to_html_with(
2002 &self,
2003 options: &HtmlExportOptions,
2004 ) -> (String, Vec<(String, Vec<u8>)>) {
2005 crate::html::to_html(self, options)
2006 }
2007}
2008
2009#[cfg(test)]
2010mod table_api_tests {
2011 use super::*;
2012
2013 fn cell(
2014 text: &str,
2015 bbox: [f32; 4],
2016 (start_row, start_col): (usize, usize),
2017 (row_span, col_span): (usize, usize),
2018 ) -> TableCell {
2019 TableCell {
2020 text: text.into(),
2021 bbox: Some(bbox),
2022 start_row,
2023 start_col,
2024 row_span,
2025 col_span,
2026 column_header: false,
2027 row_header: false,
2028 row_section: false,
2029 }
2030 }
2031
2032 fn table() -> Table {
2033 Table {
2034 rows: vec![
2035 vec!["Year".into(), "Ducks".into()],
2036 vec!["2019".into(), "120".into()],
2037 ],
2038 cells: Some(vec![
2039 cell("Year", [0.0, 0.0, 50.0, 10.0], (0, 0), (1, 1)),
2040 cell("Ducks", [50.0, 0.0, 100.0, 10.0], (0, 1), (1, 1)),
2041 cell("2019", [0.0, 10.0, 50.0, 20.0], (1, 0), (1, 1)),
2042 cell("120", [50.0, 10.0, 100.0, 20.0], (1, 1), (1, 1)),
2043 ]),
2044 ..Default::default()
2045 }
2046 }
2047
2048 /// Declarative tables derive first-class cells from the structure
2049 /// overlay: continuation grids become span extents, `col_header` (or the
2050 /// row-0 fallback) becomes the header role — the XLSX/DOCX/HTML merge
2051 /// path into real `TableCell`s (#240).
2052 #[test]
2053 fn derive_cells_reads_spans_and_headers_from_structure() {
2054 let t = Table {
2055 rows: vec![
2056 vec!["Wide".into(), "Wide".into(), "C".into()],
2057 vec!["a".into(), "b".into(), "c".into()],
2058 ],
2059 structure: Some(TableStructure {
2060 header_row: vec![true, false],
2061 col_continuation: vec![vec![false, true, false], vec![false; 3]],
2062 row_continuation: vec![vec![false; 3], vec![false; 3]],
2063 row_header: Vec::new(),
2064 col_header: Vec::new(),
2065 }),
2066 ..Default::default()
2067 };
2068 let cells = t.derive_cells();
2069 assert_eq!(cells.len(), 5, "two anchors in row 0, three in row 1");
2070 let wide = &cells[0];
2071 assert_eq!((wide.col_span, wide.row_span), (2, 1));
2072 assert!(wide.column_header, "header_row band");
2073 assert!(cells.iter().skip(2).all(|c| !c.column_header));
2074
2075 // Without any overlay: every position 1x1, row 0 the header
2076 // (docling's declarative default — the old JSON synthesis).
2077 let plain = Table {
2078 rows: vec![vec!["h".into()], vec!["x".into()]],
2079 ..Default::default()
2080 };
2081 let cells = plain.derive_cells();
2082 assert_eq!(cells.len(), 2);
2083 assert!(cells[0].column_header && !cells[1].column_header);
2084 }
2085
2086 /// A spanning cell updates once: the record text and every covered grid
2087 /// position — a repair shows once in Markdown, not once per column.
2088 #[test]
2089 fn span_repair_updates_the_whole_cell() {
2090 let mut t = Table {
2091 rows: vec![
2092 vec!["Wide".into(), "Wide".into(), "C".into()],
2093 vec!["a".into(), "b".into(), "c".into()],
2094 ],
2095 cells: Some(vec![
2096 cell("Wide", [0.0, 0.0, 100.0, 10.0], (0, 0), (1, 2)),
2097 cell("C", [100.0, 0.0, 150.0, 10.0], (0, 2), (1, 1)),
2098 ]),
2099 ..Default::default()
2100 };
2101 // Update through the covered (non-anchor) position.
2102 assert!(t.set_cell_text(0, 1, "Fixed"));
2103 assert_eq!(
2104 t.rows[0],
2105 vec!["Fixed".to_string(), "Fixed".into(), "C".into()]
2106 );
2107 assert_eq!(t.cell_at(0, 1).unwrap().text, "Fixed");
2108 assert_eq!(t.cell_at(0, 1).unwrap().col_span, 2);
2109 }
2110
2111 /// The OCR-repair loop (#238): locate a cell by an external box (best
2112 /// IoU), replace its text, and see the fix in the export — the grid is
2113 /// the single source of truth for every serializer.
2114 #[test]
2115 fn bbox_lookup_and_repair_flow_into_exports() {
2116 let mut doc = DoclingDocument::new("t");
2117 doc.push(Node::Table(table()));
2118 assert_eq!(doc.tables().count(), 1);
2119
2120 let t = doc.tables_mut().next().unwrap();
2121 // A slightly-off OCR box still lands on the (1,1) cell.
2122 assert_eq!(t.find_cell_by_bbox([52.0, 11.0, 98.0, 19.0]), Some((1, 1)));
2123 assert_eq!(
2124 t.update_cell_by_bbox([52.0, 11.0, 98.0, 19.0], "125"),
2125 Some((1, 1))
2126 );
2127 assert_eq!(t.cell_text(1, 1), Some("125"));
2128 assert!(doc.export_to_markdown().contains("125"));
2129
2130 // No overlap → no match, nothing changed.
2131 let t = doc.tables_mut().next().unwrap();
2132 assert_eq!(t.find_cell_by_bbox([500.0, 500.0, 600.0, 600.0]), None);
2133 }
2134
2135 #[test]
2136 fn cell_accessors_bound_check_and_geometry_materializes() {
2137 let mut t = table();
2138 assert_eq!(t.cell_text(0, 0), Some("Year"));
2139 assert_eq!(t.cell_text(5, 0), None);
2140 assert!(!t.set_cell_text(0, 9, "x"), "outside the grid");
2141 assert_eq!(t.cell_bbox(1, 0), Some([0.0, 10.0, 50.0, 20.0]));
2142
2143 // A geometry-less table materializes its box grid on first set.
2144 let mut plain = Table {
2145 rows: vec![vec!["a".into(), "b".into()]],
2146 ..Default::default()
2147 };
2148 assert_eq!(plain.cell_bbox(0, 1), None);
2149 assert!(!plain.set_cell_bbox(0, 5, [0.0; 4]), "outside the grid");
2150 assert!(plain.set_cell_bbox(0, 1, [1.0, 2.0, 3.0, 4.0]));
2151 assert_eq!(plain.cell_bbox(0, 1), Some([1.0, 2.0, 3.0, 4.0]));
2152 assert_eq!(plain.find_cell_by_bbox([1.5, 2.5, 2.5, 3.5]), Some((0, 1)));
2153 }
2154}
2155
2156#[cfg(test)]
2157mod rescale_tests {
2158 use super::*;
2159
2160 fn image(dpi: u32) -> PictureImage {
2161 PictureImage {
2162 mimetype: "image/png".into(),
2163 width: 300,
2164 height: 150,
2165 data: Vec::new(),
2166 dpi,
2167 display_size: None,
2168 }
2169 }
2170
2171 /// #1093: a page measured in pixels re-measured in points — the page size,
2172 /// a table cell's box and a script run's box scale per axis, an image's
2173 /// pixels per inch of the page grow by the inverse, and the 0–511
2174 /// locations, relative to the page, stay.
2175 #[test]
2176 fn a_page_unit_change_scales_lengths_and_resolutions() {
2177 let table = Table {
2178 rows: vec![vec!["a".into()]],
2179 location: Some([10, 20, 30, 40]),
2180 cells: Some(vec![TableCell {
2181 text: "a".into(),
2182 bbox: Some([100.0, 200.0, 300.0, 400.0]),
2183 start_row: 0,
2184 start_col: 0,
2185 row_span: 1,
2186 col_span: 1,
2187 column_header: false,
2188 row_header: false,
2189 row_section: false,
2190 }]),
2191 ..Table::default()
2192 };
2193 let mut doc = DoclingDocument::new("scan");
2194 doc.push(Node::PageInfo {
2195 page_no: 1,
2196 width: 1000.0,
2197 height: 2000.0,
2198 });
2199 doc.push(Node::Located {
2200 location: [1, 2, 3, 4],
2201 inner: Box::new(Node::Table(table)),
2202 });
2203 doc.push(Node::Group {
2204 label: "group".into(),
2205 name: None,
2206 layer: None,
2207 children: vec![Node::Picture {
2208 caption: None,
2209 caption_href: None,
2210 image: Some(image(72)),
2211 classification: None,
2212 description: None,
2213 caption_parent: Default::default(),
2214 caption_location: None,
2215 }],
2216 });
2217 doc.page_images.insert(1, image(144));
2218
2219 doc.rescale_page_units(0.24, 0.5);
2220
2221 assert!(matches!(
2222 doc.nodes[0],
2223 Node::PageInfo { width, height, .. } if width == 240.0 && height == 1000.0
2224 ));
2225 let Node::Located { location, inner } = &doc.nodes[1] else {
2226 panic!("located table")
2227 };
2228 assert_eq!(*location, [1, 2, 3, 4]);
2229 let Node::Table(t) = inner.as_ref() else {
2230 panic!("table")
2231 };
2232 assert_eq!(t.location, Some([10, 20, 30, 40]));
2233 assert_eq!(
2234 t.cells.as_ref().unwrap()[0].bbox,
2235 Some([24.0, 100.0, 72.0, 200.0])
2236 );
2237 let Node::Group { children, .. } = &doc.nodes[2] else {
2238 panic!("group")
2239 };
2240 assert!(matches!(&children[0], Node::Picture { image: Some(i), .. } if i.dpi == 300));
2241 assert_eq!(doc.page_images[&1].dpi, 600);
2242 }
2243}