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 /// Hyperlinks recovered from the source, as `(anchor_text, href)` pairs in
28 /// document order. docling's standard pipeline drops PDF link annotations, so
29 /// these are rendered as Markdown `[anchor](href)` **only in strict mode**
30 /// (legacy/docling output is left byte-for-byte unchanged). The PDF backend
31 /// populates this from pdfium link annotations; other backends leave it empty.
32 pub links: Vec<(String, String)>,
33}
34
35/// A single piece of document content.
36#[derive(Debug, Clone, PartialEq)]
37pub enum Node {
38 /// A heading. `level` is 1-6.
39 Heading { level: u8, text: String },
40 /// A run of body text.
41 Paragraph { text: String },
42 /// A single list item at the given nesting `level` (0 = top). For ordered
43 /// items, `number` is the display number (honoring the list's `start`); it
44 /// is unused for unordered items. `first_in_list` marks the first item of a
45 /// list so the serializer can blank-line-separate adjacent sibling lists.
46 ///
47 /// `marker` is the DocLang enumeration marker (`"1."`, `"1.1."`, …) when the
48 /// backend provides one — HTML and DOCX set it for enumerated items, so
49 /// DocLang emits `<ldiv><marker>…</marker></ldiv>`; Markdown and the other
50 /// declarative backends leave it `None`, giving a bare `<ldiv/>` (matching
51 /// docling, whose Markdown backend passes no marker).
52 ListItem {
53 ordered: bool,
54 number: u64,
55 first_in_list: bool,
56 text: String,
57 level: u8,
58 marker: Option<String>,
59 },
60 /// A fenced code block.
61 Code {
62 language: Option<String>,
63 text: String,
64 },
65 /// A table. The first row is treated as the header.
66 Table(Table),
67 /// A picture/figure, with an optional caption and (when a backend extracts
68 /// it) the embedded image itself.
69 Picture {
70 caption: Option<String>,
71 image: Option<PictureImage>,
72 },
73 /// A logical grouping of child nodes (e.g. a list, a section).
74 Group { label: String, children: Vec<Node> },
75 /// A form key-value region (docling's `field_region`): a set of form fields,
76 /// each pairing an optional marker, key, and value. Backends detect these
77 /// from form structure (e.g. HTML's `keyN` / `keyN_valueM` / `keyN_marker`
78 /// `id`-convention); the serializers render each item's parts as separate
79 /// labelled texts (`marker` / `field_key` / `field_value`).
80 FieldRegion { items: Vec<FieldItem> },
81 /// Rich inline content — docling's `InlineGroup`: a run of styled text
82 /// segments that a backend captured with formatting (`<bold>`, `<italic>`,
83 /// `<underline>`, `<strikethrough>`, sub/superscript, inline `<code>`) the
84 /// flat Markdown text cannot represent. Markdown/JSON render this exactly
85 /// like `Paragraph { text: md_text }` (so their output is unchanged); the
86 /// DocLang serializer uses the structured `runs`. `unwrapped` is set when the
87 /// group's docling parent is a heading/text (no enclosing `<text>` wrapper).
88 InlineGroup {
89 unwrapped: bool,
90 runs: Vec<InlineRun>,
91 md_text: String,
92 },
93 /// A node in docling's `furniture` content layer (page headers/footers, the
94 /// HTML `<title>`, …). Markdown and JSON omit furniture by default; DocLang
95 /// renders the wrapped node with a `<layer value="furniture"/>` head.
96 Furniture(Box<Node>),
97}
98
99/// Vertical text position of an [`InlineRun`] — docling's `Script`.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
101pub enum Script {
102 #[default]
103 Baseline,
104 Sub,
105 Super,
106}
107
108/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
109/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
110/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
111/// source text node). A hyperlink is intentionally not stored: DocLang drops the
112/// target inside inline scope, keeping only the anchor text.
113#[derive(Debug, Clone, PartialEq, Eq, Default)]
114pub struct InlineRun {
115 pub text: String,
116 pub bold: bool,
117 pub italic: bool,
118 pub underline: bool,
119 pub strike: bool,
120 pub script: Script,
121 pub code: bool,
122}
123
124impl InlineRun {
125 /// A run with no active formatting (renders as bare inline text).
126 pub fn is_plain(&self) -> bool {
127 !self.bold
128 && !self.italic
129 && !self.underline
130 && !self.strike
131 && !self.code
132 && self.script == Script::Baseline
133 }
134}
135
136/// Build the [`Node`] for a paragraph of inline content from its structured
137/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
138///
139/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
140/// serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
141/// * a single uniformly-formatted run, or two or more runs → a
142/// [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
143/// heading, so no enclosing `<text>`) only applies to multi-run groups.
144///
145/// Markdown/JSON render the group's `md_text`, so their output is identical to
146/// emitting a `Paragraph` — the structured runs are DocLang-only.
147pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
148 let single_plain = runs.len() <= 1 && runs.first().map_or(true, |r| r.is_plain());
149 if single_plain {
150 Node::Paragraph { text: md_text }
151 } else {
152 Node::InlineGroup {
153 unwrapped: unwrapped && runs.len() >= 2,
154 runs,
155 md_text,
156 }
157 }
158}
159
160/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
161/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
162/// / `field_value` child texts.
163#[derive(Debug, Clone, PartialEq, Default)]
164pub struct FieldItem {
165 pub marker: Option<String>,
166 pub key: Option<String>,
167 pub value: Option<String>,
168}
169
170/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
171/// the docling.rs analogue of docling-core's `ImageRef`.
172#[derive(Debug, Clone, PartialEq)]
173pub struct PictureImage {
174 /// e.g. `image/png`, `image/jpeg`.
175 pub mimetype: String,
176 pub width: u32,
177 pub height: u32,
178 /// The image file bytes, exactly as embedded (PNG/JPEG/…).
179 pub data: Vec<u8>,
180}
181
182impl PictureImage {
183 /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
184 pub fn data_uri(&self) -> String {
185 format!(
186 "data:{};base64,{}",
187 self.mimetype,
188 crate::base64::encode(&self.data)
189 )
190 }
191}
192
193/// A simple row-major table. `rows[0]` is the header row.
194#[derive(Debug, Clone, PartialEq, Default)]
195pub struct Table {
196 pub rows: Vec<Vec<String>>,
197 /// Optional layout provenance: the four DocLang `<location>` values
198 /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
199 /// before the table's cells. Set only by backends with real geometry (e.g.
200 /// the spreadsheet backend, whose cell grid yields a bounding box); left
201 /// `None` by declarative backends, which have no coordinates.
202 pub location: Option<[u16; 4]>,
203}
204
205impl DoclingDocument {
206 /// Create an empty document with the given name.
207 pub fn new(name: impl Into<String>) -> Self {
208 Self {
209 name: name.into(),
210 nodes: Vec::new(),
211 strict_markdown: false,
212 compact_tables: false,
213 links: Vec::new(),
214 }
215 }
216
217 /// Append a node.
218 pub fn push(&mut self, node: Node) {
219 self.nodes.push(node);
220 }
221
222 /// Convenience: append a heading.
223 pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
224 self.push(Node::Heading {
225 level,
226 text: text.into(),
227 });
228 }
229
230 /// Convenience: append a paragraph.
231 pub fn add_paragraph(&mut self, text: impl Into<String>) {
232 self.push(Node::Paragraph { text: text.into() });
233 }
234
235 /// Serialize the document to Markdown.
236 ///
237 /// The Rust equivalent of docling-core's
238 /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
239 /// pick between docling-legacy output (default) and the cleaner, more
240 /// conformant variant.
241 pub fn export_to_markdown(&self) -> String {
242 to_markdown(self, self.strict_markdown)
243 }
244
245 /// Serialize to Markdown, explicitly choosing the mode regardless of
246 /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
247 /// conformant Markdown (code-fence languages preserved, no inline-run
248 /// spacing artifacts); `strict = false` reproduces docling's legacy output.
249 pub fn export_to_markdown_with(&self, strict: bool) -> String {
250 to_markdown(self, strict)
251 }
252
253 /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
254 /// schema), pretty-printed — the Rust equivalent of
255 /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
256 /// back into Python docling-core and round-trips to the same Markdown.
257 pub fn export_to_json(&self) -> String {
258 serde_json::to_string_pretty(&crate::json::to_json(self))
259 .expect("DoclingDocument JSON is always serializable")
260 }
261
262 /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
263 /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
264 /// `export_to_doclang()` with default parameters. No trailing newline; the
265 /// archive writer appends exactly one.
266 pub fn export_to_doclang(&self) -> String {
267 crate::doclang::export_to_doclang(&self.nodes)
268 }
269
270 /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
271 /// docling's `image_mode`). Returns the Markdown and, for
272 /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
273 /// caller should write next to the Markdown file. `artifacts_dir` is the
274 /// directory name used in referenced links.
275 pub fn export_to_markdown_with_images(
276 &self,
277 image_mode: ImageMode,
278 artifacts_dir: &str,
279 ) -> (String, Vec<(String, Vec<u8>)>) {
280 to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
281 }
282}