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