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