Skip to content

A fast, helpful, and open-source document parser

feat: expose tagged PDF structure trees

Pierre-Loic doulcet001d510e3e7a
diff --git a/README.md b/README.md
index 19a2494..8c7004c 100644
--- a/README.md
+++ b/README.md
@@ -197,6 +197,9 @@ lit parse document.pdf --format json --extract-images
# Emit link text as plain text (no [text](url) syntax)
lit parse document.pdf --format markdown --no-links
+
+# Include tagged-PDF logical structure in JSON
+lit parse document.pdf --format json --extract-structure-tree
```
Image handling is controlled by `--image-mode`:
@@ -241,6 +244,15 @@ the shape rectangle `bbox` rather than PDFium's `coords`, and uses `width` /
default. Diagonal and curved segments are represented by their parent shape but
are not emitted as lines.
+### Tagged PDF structure tree
+
+Enable `--extract-structure-tree` (Rust/Python `extract_structure_tree`,
+JavaScript/WASM `extractStructureTree`) to add a page-scoped `structure_tree`.
+It preserves every root and recursively exposes element type, ID, actual/alternate
+text, title, typed scalar attributes, marked-content IDs, children, and referenced
+link annotations. The field is absent by default; enabled untagged pages contain
+`roots: []`.
+
### Check Complexity
Before committing to a full parse, check whether a document actually needs OCR or
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index 64949d1..e1c1f26 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -5,8 +5,9 @@ use napi_derive::napi;
use liteparse::config::{CropBox, ImageMode, LiteParseConfig, OutputFormat};
use liteparse::parser::ParseResult;
use liteparse::types::{
- DocumentAnnotation, FormField, GraphicPrimitive, Page, ParsedPage, Rect, TextItem,
- VectorGraphics, WordBox,
+ DocumentAnnotation, FormField, GraphicPrimitive, Page, ParsedPage, Rect,
+ StructureAttributeValue, StructureTree, StructureTreeElement, TextItem, VectorGraphics,
+ WordBox,
};
// ---------------------------------------------------------------------------
@@ -59,6 +60,8 @@ pub struct JsLiteParseConfig {
pub extract_annotations: Option<bool>,
/// Extract AcroForm widget fields and values.
pub extract_form_fields: Option<bool>,
+ /// Extract the tagged-PDF logical structure tree.
+ pub extract_structure_tree: Option<bool>,
/// Whether a systemic OCR failure aborts the whole parse (default true).
/// Set false to keep already-recovered native text and return partial
/// results when OCR is unavailable, instead of rejecting.
@@ -167,6 +170,9 @@ impl JsLiteParseConfig {
if let Some(v) = self.extract_form_fields {
cfg.extract_form_fields = v;
}
+ if let Some(v) = self.extract_structure_tree {
+ cfg.extract_structure_tree = v;
+ }
if let Some(v) = self.ocr_failure_fatal {
cfg.ocr_failure_fatal = v;
}
@@ -232,6 +238,7 @@ impl JsLiteParseConfig {
extract_links: Some(cfg.extract_links),
extract_annotations: Some(cfg.extract_annotations),
extract_form_fields: Some(cfg.extract_form_fields),
+ extract_structure_tree: Some(cfg.extract_structure_tree),
ocr_failure_fatal: Some(cfg.ocr_failure_fatal),
ocr_hedge_delays_ms: Some(
cfg.ocr_hedge_delays_ms
@@ -492,6 +499,7 @@ impl JsPageInput {
image_refs: Vec::new(),
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
}
@@ -513,6 +521,86 @@ pub struct JsParsedPage {
pub vector_graphics: Option<JsVectorGraphics>,
pub annotations: Option<Vec<JsDocumentAnnotation>>,
pub form_fields: Option<Vec<JsFormField>>,
+ pub structure_tree: Option<JsStructureTree>,
+}
+
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsStructureAttribute {
+ pub name: String,
+ pub boolean_value: Option<bool>,
+ pub number_value: Option<f64>,
+ pub string_value: Option<String>,
+}
+
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsStructureTree {
+ pub roots: Vec<JsStructureTreeElement>,
+}
+
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsStructureTreeElement {
+ pub element_type: String,
+ pub id: Option<String>,
+ pub actual_text: Option<String>,
+ pub alt_text: Option<String>,
+ pub title: Option<String>,
+ pub attributes: Vec<JsStructureAttribute>,
+ pub marked_content_ids: Vec<i32>,
+ pub children: Vec<JsStructureTreeElement>,
+ pub annotations: Vec<JsDocumentAnnotation>,
+}
+
+impl JsStructureTree {
+ fn from_rust(tree: &StructureTree) -> Self {
+ Self {
+ roots: tree
+ .roots
+ .iter()
+ .map(JsStructureTreeElement::from_rust)
+ .collect(),
+ }
+ }
+}
+
+impl JsStructureTreeElement {
+ fn from_rust(element: &StructureTreeElement) -> Self {
+ Self {
+ element_type: element.element_type.clone(),
+ id: element.id.clone(),
+ actual_text: element.actual_text.clone(),
+ alt_text: element.alt_text.clone(),
+ title: element.title.clone(),
+ attributes: element
+ .attributes
+ .iter()
+ .map(|(name, value)| {
+ let (boolean_value, number_value, string_value) = match value {
+ StructureAttributeValue::Boolean(value) => (Some(*value), None, None),
+ StructureAttributeValue::Number(value) => {
+ (None, Some(f64::from(*value)), None)
+ }
+ StructureAttributeValue::String(value) => (None, None, Some(value.clone())),
+ };
+ JsStructureAttribute {
+ name: name.clone(),
+ boolean_value,
+ number_value,
+ string_value,
+ }
+ })
+ .collect(),
+ marked_content_ids: element.marked_content_ids.clone(),
+ children: element.children.iter().map(Self::from_rust).collect(),
+ annotations: element
+ .annotations
+ .iter()
+ .map(JsDocumentAnnotation::from_rust)
+ .collect(),
+ }
+ }
}
#[napi(object)]
@@ -724,6 +812,7 @@ impl JsParsedPage {
.form_fields
.as_ref()
.map(|fields| fields.iter().map(JsFormField::from_rust).collect()),
+ structure_tree: page.structure_tree.as_ref().map(JsStructureTree::from_rust),
}
}
}
diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rs
index 437fb33..f1f3b1a 100644
--- a/crates/liteparse-python/src/cli.rs
+++ b/crates/liteparse-python/src/cli.rs
@@ -82,6 +82,9 @@ struct ParseCommand {
/// Include AcroForm widget fields and values.
#[arg(long)]
extract_form_fields: bool,
+ /// Include the tagged-PDF logical structure tree.
+ #[arg(long)]
+ extract_structure_tree: bool,
/// Include per-page complexity signals as a `complexity` object on each
/// page of JSON output. Off by default.
#[arg(long)]
@@ -171,6 +174,9 @@ struct BatchParseCommand {
/// Include page-scoped vector shapes and merged horizontal/vertical lines.
#[arg(long)]
extract_vector_graphics: bool,
+ /// Include the tagged-PDF logical structure tree.
+ #[arg(long)]
+ extract_structure_tree: bool,
}
/// Parse a `Name: Value` header string into a `(name, value)` pair.
@@ -252,6 +258,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
extract_links: !cmd.no_links,
extract_annotations: cmd.extract_annotations,
extract_form_fields: cmd.extract_form_fields,
+ extract_structure_tree: cmd.extract_structure_tree,
include_complexity: cmd.complexity,
extract_text_metadata: cmd.extract_text_metadata,
extract_vector_graphics: cmd.extract_vector_graphics,
@@ -348,6 +355,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
extract_text_metadata: cmd.extract_text_metadata,
extract_images: cmd.extract_images,
extract_vector_graphics: cmd.extract_vector_graphics,
+ extract_structure_tree: cmd.extract_structure_tree,
..Default::default()
};
if let Some(n) = cmd.num_workers {
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index eb20191..3c4ba59 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -158,6 +158,91 @@ struct PyDocumentAnnotation {
uri: Option<String>,
}
+#[pyclass(frozen, from_py_object)]
+#[derive(Clone)]
+struct PyStructureAttribute {
+ #[pyo3(get)]
+ name: String,
+ #[pyo3(get)]
+ boolean_value: Option<bool>,
+ #[pyo3(get)]
+ number_value: Option<f64>,
+ #[pyo3(get)]
+ string_value: Option<String>,
+}
+
+#[pyclass(frozen, from_py_object)]
+#[derive(Clone)]
+struct PyStructureTreeElement {
+ #[pyo3(get)]
+ element_type: String,
+ #[pyo3(get)]
+ id: Option<String>,
+ #[pyo3(get)]
+ actual_text: Option<String>,
+ #[pyo3(get)]
+ alt_text: Option<String>,
+ #[pyo3(get)]
+ title: Option<String>,
+ #[pyo3(get)]
+ attributes: Vec<PyStructureAttribute>,
+ #[pyo3(get)]
+ marked_content_ids: Vec<i32>,
+ #[pyo3(get)]
+ children: Vec<PyStructureTreeElement>,
+ #[pyo3(get)]
+ annotations: Vec<PyDocumentAnnotation>,
+}
+
+#[pyclass(frozen, from_py_object)]
+#[derive(Clone)]
+struct PyStructureTree {
+ #[pyo3(get)]
+ roots: Vec<PyStructureTreeElement>,
+}
+
+impl PyStructureTreeElement {
+ fn from_rust(element: liteparse::types::StructureTreeElement) -> Self {
+ Self {
+ element_type: element.element_type,
+ id: element.id,
+ actual_text: element.actual_text,
+ alt_text: element.alt_text,
+ title: element.title,
+ attributes: element
+ .attributes
+ .into_iter()
+ .map(|(name, value)| {
+ let (boolean_value, number_value, string_value) = match value {
+ liteparse::types::StructureAttributeValue::Boolean(value) => {
+ (Some(value), None, None)
+ }
+ liteparse::types::StructureAttributeValue::Number(value) => {
+ (None, Some(f64::from(value)), None)
+ }
+ liteparse::types::StructureAttributeValue::String(value) => {
+ (None, None, Some(value))
+ }
+ };
+ PyStructureAttribute {
+ name,
+ boolean_value,
+ number_value,
+ string_value,
+ }
+ })
+ .collect(),
+ marked_content_ids: element.marked_content_ids,
+ children: element.children.into_iter().map(Self::from_rust).collect(),
+ annotations: element
+ .annotations
+ .into_iter()
+ .map(PyDocumentAnnotation::from_rust)
+ .collect(),
+ }
+ }
+}
+
impl PyDocumentAnnotation {
fn from_rust(annotation: liteparse::types::DocumentAnnotation) -> Self {
Self {
@@ -337,6 +422,8 @@ struct PyParsedPage {
annotations: Option<Vec<PyDocumentAnnotation>>,
#[pyo3(get)]
form_fields: Option<Vec<PyFormField>>,
+ #[pyo3(get)]
+ structure_tree: Option<PyStructureTree>,
}
#[pyclass(frozen, from_py_object)]
@@ -480,6 +567,13 @@ impl PyParsedPage {
form_fields: page
.form_fields
.map(|fields| fields.into_iter().map(PyFormField::from_rust).collect()),
+ structure_tree: page.structure_tree.map(|tree| PyStructureTree {
+ roots: tree
+ .roots
+ .into_iter()
+ .map(PyStructureTreeElement::from_rust)
+ .collect(),
+ }),
}
}
}
@@ -810,6 +904,8 @@ struct PyLiteParseConfig {
#[pyo3(get)]
extract_form_fields: bool,
#[pyo3(get)]
+ extract_structure_tree: bool,
+ #[pyo3(get)]
ocr_failure_fatal: bool,
#[pyo3(get)]
ocr_hedge_delays_ms: Vec<u64>,
@@ -873,6 +969,7 @@ impl PyLiteParseConfig {
extract_links: cfg.extract_links,
extract_annotations: cfg.extract_annotations,
extract_form_fields: cfg.extract_form_fields,
+ extract_structure_tree: cfg.extract_structure_tree,
ocr_failure_fatal: cfg.ocr_failure_fatal,
ocr_hedge_delays_ms: cfg.ocr_hedge_delays_ms.clone(),
emit_word_boxes: cfg.emit_word_boxes,
@@ -925,6 +1022,7 @@ impl LiteParse {
extract_links = None,
extract_annotations = None,
extract_form_fields = None,
+ extract_structure_tree = None,
ocr_failure_fatal = None,
ocr_hedge_delays_ms = None,
emit_word_boxes = None,
@@ -954,6 +1052,7 @@ impl LiteParse {
extract_links: Option<bool>,
extract_annotations: Option<bool>,
extract_form_fields: Option<bool>,
+ extract_structure_tree: Option<bool>,
ocr_failure_fatal: Option<bool>,
ocr_hedge_delays_ms: Option<Vec<u64>>,
emit_word_boxes: Option<bool>,
@@ -1029,6 +1128,9 @@ impl LiteParse {
if let Some(v) = extract_form_fields {
cfg.extract_form_fields = v;
}
+ if let Some(v) = extract_structure_tree {
+ cfg.extract_structure_tree = v;
+ }
if let Some(v) = ocr_failure_fatal {
cfg.ocr_failure_fatal = v;
}
@@ -1240,6 +1342,9 @@ fn _liteparse(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyWordBox>()?;
m.add_class::<PyAnnotationRect>()?;
m.add_class::<PyDocumentAnnotation>()?;
+ m.add_class::<PyStructureAttribute>()?;
+ m.add_class::<PyStructureTreeElement>()?;
+ m.add_class::<PyStructureTree>()?;
m.add_class::<PyFormField>()?;
m.add_class::<PyScreenshotResult>()?;
m.add_class::<PyPageComplexityStats>()?;
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index 8925ba6..8b800f2 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -58,6 +58,7 @@ pub struct LiteParseConfig {
extract_links: Option<bool>,
extract_annotations: Option<bool>,
extract_form_fields: Option<bool>,
+ extract_structure_tree: Option<bool>,
ocr_failure_fatal: Option<bool>,
ocr_hedge_delays_ms: Option<Vec<u64>>,
preserve_very_small_text: Option<bool>,
@@ -150,6 +151,9 @@ impl LiteParseConfig {
if let Some(v) = self.extract_form_fields {
cfg.extract_form_fields = v;
}
+ if let Some(v) = self.extract_structure_tree {
+ cfg.extract_structure_tree = v;
+ }
if let Some(v) = self.ocr_failure_fatal {
cfg.ocr_failure_fatal = v;
}
@@ -217,6 +221,7 @@ impl LiteParseConfig {
extract_links: Some(cfg.extract_links),
extract_annotations: Some(cfg.extract_annotations),
extract_form_fields: Some(cfg.extract_form_fields),
+ extract_structure_tree: Some(cfg.extract_structure_tree),
ocr_failure_fatal: Some(cfg.ocr_failure_fatal),
ocr_hedge_delays_ms: Some(cfg.ocr_hedge_delays_ms.clone()),
preserve_very_small_text: Some(cfg.preserve_very_small_text),
diff --git a/crates/liteparse/README.md b/crates/liteparse/README.md
index 6f286dc..99857c2 100644
--- a/crates/liteparse/README.md
+++ b/crates/liteparse/README.md
@@ -57,6 +57,7 @@ let config = LiteParseConfig {
dpi: 150.0, // Rendering DPI
output_format: OutputFormat::Json, // Json | Text | Markdown
extract_annotations: false, // Include page annotations in output
+ extract_structure_tree: false, // Include tagged-PDF logical structure
preserve_very_small_text: false, // Keep tiny text
extract_text_metadata: false, // Opt in to rich PDF text metadata
password: None, // Password for protected documents
@@ -73,6 +74,11 @@ rectangle and quadpoint rectangles, and external link URI. It is independent
of `extract_links`, which controls Markdown link rendering. The field is
`None` when extraction is disabled.
+Set `extract_structure_tree: true` to populate `ParsedPage::structure_tree` with
+the complete tagged-PDF hierarchy: all roots, element type/ID, actual and alternate
+text, title, typed scalar attributes, MCIDs, recursive children, and referenced link
+annotations. Disabled pages use `None`; enabled untagged pages have no roots.
+
## Markdown Output
LiteParse can render documents directly to Markdown, including headings, tables, lists,
diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rs
index bd58d97..b697c8e 100644
--- a/crates/liteparse/src/config.rs
+++ b/crates/liteparse/src/config.rs
@@ -51,6 +51,9 @@ pub struct LiteParseConfig {
/// Extract AcroForm widget fields and values. Default `false`.
#[serde(default)]
pub extract_form_fields: bool,
+ /// Extract the tagged-PDF logical structure tree. Default `false`.
+ #[serde(default)]
+ pub extract_structure_tree: bool,
/// Whether a systemic OCR failure (every OCR task failed *and* at least one
/// was a text-sparse page whose primary text source was OCR) aborts the
/// whole parse. Default `true`: surface the root cause instead of silently
@@ -172,6 +175,7 @@ impl Default for LiteParseConfig {
extract_links: true,
extract_annotations: false,
extract_form_fields: false,
+ extract_structure_tree: false,
ocr_failure_fatal: true,
ocr_hedge_delays_ms: Vec::new(),
emit_word_boxes: false,
@@ -300,6 +304,7 @@ mod tests {
assert!(!c.extract_text_metadata);
assert!(c.password.is_none());
assert!(!c.extract_images);
+ assert!(!c.extract_structure_tree);
}
#[test]
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index 93c52ad..49357e4 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -2,8 +2,8 @@ use crate::error::LiteParseError;
use crate::glyph_names::resolve_glyph_name;
use crate::types::{
DocumentAnnotation, ExtractedImage, FormField, GraphicPrimitive, ImageRef, OutlineTarget,
- Page as LitePage, PdfInput, Rect, StructNode, TextItem, VectorGraphics, VectorLine,
- VectorShape, WordBox,
+ Page as LitePage, PdfInput, Rect, StructNode, StructureAttributeValue, StructureTree,
+ StructureTreeElement, TextItem, VectorGraphics, VectorLine, VectorShape, WordBox,
};
use image::ImageEncoder;
use pdfium::{
@@ -127,24 +127,26 @@ pub(crate) fn extract_pages_and_images(
extract_page_image_refs(&page, page_number, output_options.extract_images);
let mut image_refs = extracted_refs.refs;
image_error_count += extracted_refs.error_count;
- let annotations = output_options.extract_annotations.then(|| {
- page.annotations(&view_box)
- .into_iter()
- .map(|annotation| DocumentAnnotation {
- subtype: annotation.subtype,
- contents: annotation.contents,
- created: annotation.created,
- modified: annotation.modified,
- title: annotation.title,
- rect: annotation.rect.map(rect_from_pdfium),
- quadpoint_rects: annotation
- .quadpoint_rects
- .into_iter()
- .map(rect_from_pdfium)
- .collect(),
- uri: annotation.uri,
- })
- .collect()
+ let pdf_annotations = (output_options.extract_annotations
+ || output_options.extract_structure_tree)
+ .then(|| page.annotations(&view_box))
+ .unwrap_or_default();
+ let annotations = output_options
+ .extract_annotations
+ .then(|| pdf_annotations.iter().map(document_annotation).collect());
+ let structure_tree = output_options.extract_structure_tree.then(|| {
+ let annotations_by_object = pdf_annotations
+ .iter()
+ .filter(|annotation| annotation.subtype == "link")
+ .filter_map(|annotation| annotation.object_number.map(|n| (n, annotation)))
+ .collect::<std::collections::HashMap<_, _>>();
+ StructureTree {
+ roots: page
+ .structure_tree()
+ .into_iter()
+ .map(|element| structure_tree_element(element, &annotations_by_object))
+ .collect(),
+ }
});
let form_fields = output_options.extract_form_fields.then(|| {
form_environment.as_ref().map_or_else(Vec::new, |form| {
@@ -194,6 +196,7 @@ pub(crate) fn extract_pages_and_images(
image_refs,
annotations,
form_fields,
+ structure_tree,
});
}
@@ -207,9 +210,66 @@ pub(crate) struct ExtractionOutputOptions {
pub extract_vector_graphics: bool,
pub extract_annotations: bool,
pub extract_form_fields: bool,
+ pub extract_structure_tree: bool,
pub emit_word_boxes: bool,
}
+fn document_annotation(annotation: &pdfium::PdfAnnotation) -> DocumentAnnotation {
+ DocumentAnnotation {
+ subtype: annotation.subtype.clone(),
+ contents: annotation.contents.clone(),
+ created: annotation.created.clone(),
+ modified: annotation.modified.clone(),
+ title: annotation.title.clone(),
+ rect: annotation.rect.map(rect_from_pdfium),
+ quadpoint_rects: annotation
+ .quadpoint_rects
+ .iter()
+ .copied()
+ .map(rect_from_pdfium)
+ .collect(),
+ uri: annotation.uri.clone(),
+ }
+}
+
+fn structure_tree_element(
+ element: pdfium::StructureElement,
+ annotations_by_object: &std::collections::HashMap<i32, &pdfium::PdfAnnotation>,
+) -> StructureTreeElement {
+ let attributes = element
+ .attributes
+ .into_iter()
+ .map(|(name, value)| {
+ let value = match value {
+ pdfium::StructureAttributeValue::Boolean(v) => StructureAttributeValue::Boolean(v),
+ pdfium::StructureAttributeValue::Number(v) => StructureAttributeValue::Number(v),
+ pdfium::StructureAttributeValue::String(v) => StructureAttributeValue::String(v),
+ };
+ (name, value)
+ })
+ .collect();
+ StructureTreeElement {
+ element_type: element.element_type,
+ id: element.id,
+ actual_text: element.actual_text,
+ alt_text: element.alt_text,
+ title: element.title,
+ attributes,
+ marked_content_ids: element.marked_content_ids,
+ children: element
+ .children
+ .into_iter()
+ .map(|child| structure_tree_element(child, annotations_by_object))
+ .collect(),
+ annotations: element
+ .annotation_object_numbers
+ .into_iter()
+ .filter_map(|number| annotations_by_object.get(&number))
+ .map(|annotation| document_annotation(annotation))
+ .collect(),
+ }
+}
+
fn rect_from_pdfium(rect: RectF) -> Rect {
Rect {
x: rect.left,
@@ -2565,6 +2625,7 @@ mod tests {
image_refs: Vec::new(),
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rs
index d791d93..986088b 100644
--- a/crates/liteparse/src/main.rs
+++ b/crates/liteparse/src/main.rs
@@ -131,6 +131,10 @@ struct ParseCommand {
#[arg(long)]
extract_form_fields: bool,
+ /// Include the tagged-PDF logical structure tree.
+ #[arg(long)]
+ extract_structure_tree: bool,
+
/// Include per-page complexity signals (the same `is-complex` reports) as a
/// `complexity` object on each page of JSON output. Off by default; enabling
/// it runs the extra vector-text detection pass.
@@ -251,6 +255,9 @@ struct BatchParseCommand {
/// Include AcroForm widget fields and values as page-scoped structured data.
#[arg(long)]
extract_form_fields: bool,
+ /// Include the tagged-PDF logical structure tree.
+ #[arg(long)]
+ extract_structure_tree: bool,
}
#[derive(Args, Debug)]
@@ -372,6 +379,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
extract_links: !cmd.no_links,
extract_annotations: cmd.extract_annotations,
extract_form_fields: cmd.extract_form_fields,
+ extract_structure_tree: cmd.extract_structure_tree,
include_complexity: cmd.complexity,
extract_text_metadata: cmd.extract_text_metadata,
extract_vector_graphics: cmd.extract_vector_graphics,
@@ -475,6 +483,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
extract_vector_graphics: cmd.extract_vector_graphics,
extract_annotations: cmd.extract_annotations,
extract_form_fields: cmd.extract_form_fields,
+ extract_structure_tree: cmd.extract_structure_tree,
..Default::default()
};
if let Some(n) = cmd.num_workers {
@@ -779,4 +788,33 @@ mod tests {
})
));
}
+
+ #[test]
+ fn extract_structure_tree_flag_is_available_for_parse_and_batch() {
+ let cli = Cli::try_parse_from(["lit", "parse", "document.pdf", "--extract-structure-tree"])
+ .unwrap();
+ assert!(matches!(
+ cli.command,
+ Commands::Parse(ParseCommand {
+ extract_structure_tree: true,
+ ..
+ })
+ ));
+
+ let cli = Cli::try_parse_from([
+ "lit",
+ "batch-parse",
+ "input",
+ "output",
+ "--extract-structure-tree",
+ ])
+ .unwrap();
+ assert!(matches!(
+ cli.command,
+ Commands::BatchParse(BatchParseCommand {
+ extract_structure_tree: true,
+ ..
+ })
+ ));
+ }
}
diff --git a/crates/liteparse/src/markdown_layout/test_helpers.rs b/crates/liteparse/src/markdown_layout/test_helpers.rs
index 5ed2adc..2d1e4bd 100644
--- a/crates/liteparse/src/markdown_layout/test_helpers.rs
+++ b/crates/liteparse/src/markdown_layout/test_helpers.rs
@@ -46,6 +46,7 @@ pub(crate) fn page(lines: Vec<ProjectedLine>) -> ParsedPage {
complexity: None,
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
@@ -200,6 +201,7 @@ pub(crate) fn header_footer_page(n: usize, header: &str, footer: &str, body: &st
complexity: None,
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index 6474a1d..55137bf 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -1167,6 +1167,7 @@ mod tests {
image_refs: Vec::new(),
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
@@ -1202,6 +1203,7 @@ mod tests {
image_refs: Vec::new(),
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
@@ -1228,6 +1230,7 @@ mod tests {
image_refs: Vec::new(),
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rs
index 2fa5bf3..c160a30 100644
--- a/crates/liteparse/src/output/json.rs
+++ b/crates/liteparse/src/output/json.rs
@@ -1,6 +1,6 @@
use crate::ocr_merge::PageComplexityStats;
use crate::types::{
- DocumentAnnotation, ExtractedImage, FormField, ParsedPage, Rect, VectorGraphics,
+ DocumentAnnotation, ExtractedImage, FormField, ParsedPage, Rect, StructureTree, VectorGraphics,
};
use serde::Serialize;
@@ -58,6 +58,8 @@ pub(crate) struct JsonPage {
pub annotations: Option<Vec<DocumentAnnotation>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub form_fields: Option<Vec<FormField>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub structure_tree: Option<StructureTree>,
}
#[derive(Debug, Serialize)]
@@ -143,6 +145,7 @@ pub(crate) fn build_json(pages: &[ParsedPage], extract_text_metadata: bool) -> P
vector_graphics: page.vector_graphics.clone(),
annotations: page.annotations.clone(),
form_fields: page.form_fields.clone(),
+ structure_tree: page.structure_tree.clone(),
})
.collect(),
}
@@ -196,6 +199,8 @@ pub fn format_json_with_text_metadata(
mod tests {
use super::*;
use crate::types::{DocumentAnnotation, FormField, ParsedPage, Rect, TextItem};
+ use crate::types::{StructureAttributeValue, StructureTree, StructureTreeElement};
+ use std::collections::BTreeMap;
fn item(text: &str, conf: Option<f32>) -> TextItem {
TextItem {
@@ -229,9 +234,45 @@ mod tests {
complexity: None,
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
+ #[test]
+ fn structure_tree_uses_snake_case_and_preserves_typed_attributes() {
+ let mut page = page(vec![]);
+ page.structure_tree = Some(StructureTree {
+ roots: vec![StructureTreeElement {
+ element_type: "Figure".into(),
+ id: Some("figure-1".into()),
+ actual_text: Some("diagram".into()),
+ alt_text: Some("A diagram".into()),
+ title: None,
+ attributes: BTreeMap::from([
+ ("Decorative".into(), StructureAttributeValue::Boolean(false)),
+ ("Width".into(), StructureAttributeValue::Number(42.5)),
+ (
+ "Placement".into(),
+ StructureAttributeValue::String("Block".into()),
+ ),
+ ]),
+ marked_content_ids: vec![7],
+ children: vec![],
+ annotations: vec![],
+ }],
+ });
+
+ let value = serde_json::to_value(build_json(&[page], false)).unwrap();
+ let root = &value["pages"][0]["structure_tree"]["roots"][0];
+ assert_eq!(root["type"], "Figure");
+ assert_eq!(root["actual_text"], "diagram");
+ assert_eq!(root["marked_content_ids"][0], 7);
+ assert_eq!(root["attributes"]["Decorative"], false);
+ assert_eq!(root["attributes"]["Width"], 42.5);
+ assert_eq!(root["attributes"]["Placement"], "Block");
+ assert!(root.get("actualText").is_none());
+ }
+
#[test]
fn test_build_json_native_text_defaults_confidence_to_one() {
let j = build_json(&[page(vec![item("hi", None)])], false);
diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rs
index 8022ae8..16ee0f8 100644
--- a/crates/liteparse/src/output/markdown.rs
+++ b/crates/liteparse/src/output/markdown.rs
@@ -162,6 +162,7 @@ mod tests {
complexity: None,
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
@@ -214,6 +215,7 @@ mod tests {
complexity: None,
annotations: None,
form_fields: None,
+ structure_tree: None,
};
let out = format_markdown(&[p], &[], ImageMode::Placeholder);
assert!(out.contains("```text"));
diff --git a/crates/liteparse/src/output/text.rs b/crates/liteparse/src/output/text.rs
index eb1305c..310cab4 100644
--- a/crates/liteparse/src/output/text.rs
+++ b/crates/liteparse/src/output/text.rs
@@ -31,6 +31,7 @@ mod tests {
complexity: None,
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index 878f206..bc30e9a 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -393,6 +393,7 @@ impl LiteParse {
extract_vector_graphics: self.config.extract_vector_graphics,
extract_annotations: self.config.extract_annotations,
extract_form_fields: self.config.extract_form_fields,
+ extract_structure_tree: self.config.extract_structure_tree,
},
)?;
let t_extract = web_time::Instant::now();
@@ -662,6 +663,7 @@ mod tests {
image_refs: vec![],
annotations: None,
form_fields: None,
+ structure_tree: None,
}
}
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index 837e8c5..327da59 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -2917,6 +2917,7 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {
complexity: None,
annotations: page.annotations,
form_fields: page.form_fields,
+ structure_tree: page.structure_tree,
}
})
.collect()
@@ -5010,6 +5011,7 @@ mod tests {
image_refs: Vec::new(),
annotations: None,
form_fields: None,
+ structure_tree: None,
};
let projection_boxes = vec![
projected_item("", 10.0, 0.0, 10.0),
@@ -5314,6 +5316,7 @@ mod tests {
image_refs: Vec::new(),
annotations: None,
form_fields: None,
+ structure_tree: None,
}];
let parsed = project_pages_to_grid(pages);
@@ -5354,6 +5357,7 @@ mod tests {
image_refs: Vec::new(),
annotations: None,
form_fields: None,
+ structure_tree: None,
}];
let parsed = project_pages_to_grid(pages);
@@ -5417,6 +5421,7 @@ mod tests {
image_refs: Vec::new(),
annotations: None,
form_fields: None,
+ structure_tree: None,
}];
let parsed = project_pages_to_grid(pages);
@@ -5460,6 +5465,7 @@ mod tests {
image_refs: Vec::new(),
annotations: None,
form_fields: None,
+ structure_tree: None,
}];
let parsed = project_pages_to_grid(pages);
diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rs
index 32c740c..86b5570 100644
--- a/crates/liteparse/src/types.rs
+++ b/crates/liteparse/src/types.rs
@@ -1,5 +1,5 @@
use serde::Serialize;
-use std::collections::HashMap;
+use std::collections::{BTreeMap, HashMap};
#[doc(hidden)]
#[derive(Debug, Clone)]
@@ -130,6 +130,9 @@ pub struct Page {
/// AcroForm widgets when explicitly requested.
#[serde(skip)]
pub form_fields: Option<Vec<FormField>>,
+ /// Tagged-PDF logical structure when explicitly requested.
+ #[serde(skip)]
+ pub structure_tree: Option<StructureTree>,
}
/// One PDF page annotation. Coordinates use the same top-left, 72-DPI
@@ -153,6 +156,42 @@ pub struct DocumentAnnotation {
pub uri: Option<String>,
}
+/// Scalar value from a tagged-PDF structure element's `/A` dictionary.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(untagged)]
+pub enum StructureAttributeValue {
+ Boolean(bool),
+ Number(f32),
+ String(String),
+}
+
+/// A complete page-scoped tagged-PDF logical structure tree.
+#[derive(Debug, Clone, Serialize)]
+pub struct StructureTree {
+ pub roots: Vec<StructureTreeElement>,
+}
+
+/// One tagged-PDF structure element. Field names intentionally use the
+/// repository's snake_case JSON convention rather than PDFium's C spellings.
+#[derive(Debug, Clone, Serialize)]
+pub struct StructureTreeElement {
+ #[serde(rename = "type")]
+ pub element_type: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub actual_text: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub alt_text: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub title: Option<String>,
+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]
+ pub attributes: BTreeMap<String, StructureAttributeValue>,
+ pub marked_content_ids: Vec<i32>,
+ pub children: Vec<StructureTreeElement>,
+ pub annotations: Vec<DocumentAnnotation>,
+}
+
/// One AcroForm widget and its resolved field metadata.
#[derive(Debug, Clone, Serialize)]
pub struct FormField {
@@ -271,6 +310,9 @@ pub struct ParsedPage {
/// AcroForm widgets when `extract_form_fields` is true.
#[serde(skip_serializing_if = "Option::is_none")]
pub form_fields: Option<Vec<FormField>>,
+ /// Tagged-PDF logical structure when `extract_structure_tree` is true.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub structure_tree: Option<StructureTree>,
}
/// One embedded raster image on a page. `id` is a stable, page-scoped slug
@@ -579,6 +621,7 @@ mod tests {
image_refs: vec![],
annotations: None,
form_fields: None,
+ structure_tree: None,
};
let s = serde_json::to_string(&p).unwrap();
assert!(s.contains("\"page_number\":1"));
diff --git a/crates/pdfium-sys/src/dynamic.rs b/crates/pdfium-sys/src/dynamic.rs
index c7a9948..df2b647 100644
--- a/crates/pdfium-sys/src/dynamic.rs
+++ b/crates/pdfium-sys/src/dynamic.rs
@@ -402,6 +402,16 @@ pub struct PdfiumBindings {
*mut std::os::raw::c_void,
std::os::raw::c_ulong,
) -> std::os::raw::c_ulong,
+ pub FPDF_StructElement_GetActualText: unsafe extern "C" fn(
+ FPDF_STRUCTELEMENT,
+ *mut std::os::raw::c_void,
+ std::os::raw::c_ulong,
+ ) -> std::os::raw::c_ulong,
+ pub FPDF_StructElement_GetID: unsafe extern "C" fn(
+ FPDF_STRUCTELEMENT,
+ *mut std::os::raw::c_void,
+ std::os::raw::c_ulong,
+ ) -> std::os::raw::c_ulong,
pub FPDF_StructElement_GetTitle: unsafe extern "C" fn(
FPDF_STRUCTELEMENT,
*mut std::os::raw::c_void,
@@ -419,6 +429,38 @@ pub struct PdfiumBindings {
unsafe extern "C" fn(FPDF_STRUCTELEMENT) -> std::os::raw::c_int,
pub FPDF_StructElement_GetMarkedContentIdAtIndex:
unsafe extern "C" fn(FPDF_STRUCTELEMENT, std::os::raw::c_int) -> std::os::raw::c_int,
+ pub FPDF_StructElement_GetChildObjNum:
+ unsafe extern "C" fn(FPDF_STRUCTELEMENT, std::os::raw::c_int) -> std::os::raw::c_int,
+ pub FPDF_StructElement_GetAttributeCount:
+ unsafe extern "C" fn(FPDF_STRUCTELEMENT) -> std::os::raw::c_int,
+ pub FPDF_StructElement_GetAttributeAtIndex:
+ unsafe extern "C" fn(FPDF_STRUCTELEMENT, std::os::raw::c_int) -> FPDF_STRUCTELEMENT_ATTR,
+ pub FPDF_StructElement_Attr_GetCount:
+ unsafe extern "C" fn(FPDF_STRUCTELEMENT_ATTR) -> std::os::raw::c_int,
+ pub FPDF_StructElement_Attr_GetName: unsafe extern "C" fn(
+ FPDF_STRUCTELEMENT_ATTR,
+ std::os::raw::c_int,
+ *mut std::os::raw::c_void,
+ std::os::raw::c_ulong,
+ *mut std::os::raw::c_ulong,
+ ) -> FPDF_BOOL,
+ pub FPDF_StructElement_Attr_GetValue: unsafe extern "C" fn(
+ FPDF_STRUCTELEMENT_ATTR,
+ FPDF_BYTESTRING,
+ )
+ -> FPDF_STRUCTELEMENT_ATTR_VALUE,
+ pub FPDF_StructElement_Attr_GetType:
+ unsafe extern "C" fn(FPDF_STRUCTELEMENT_ATTR_VALUE) -> FPDF_OBJECT_TYPE,
+ pub FPDF_StructElement_Attr_GetBooleanValue:
+ unsafe extern "C" fn(FPDF_STRUCTELEMENT_ATTR_VALUE, *mut FPDF_BOOL) -> FPDF_BOOL,
+ pub FPDF_StructElement_Attr_GetNumberValue:
+ unsafe extern "C" fn(FPDF_STRUCTELEMENT_ATTR_VALUE, *mut f32) -> FPDF_BOOL,
+ pub FPDF_StructElement_Attr_GetStringValue: unsafe extern "C" fn(
+ FPDF_STRUCTELEMENT_ATTR_VALUE,
+ *mut std::os::raw::c_void,
+ std::os::raw::c_ulong,
+ *mut std::os::raw::c_ulong,
+ ) -> FPDF_BOOL,
}
// SAFETY: PdfiumBindings contains only function pointers and a Library handle.
@@ -565,6 +607,8 @@ impl PdfiumBindings {
FPDF_StructTree_GetChildAtIndex: load_fn!(lib, "FPDF_StructTree_GetChildAtIndex"),
FPDF_StructElement_GetType: load_fn!(lib, "FPDF_StructElement_GetType"),
FPDF_StructElement_GetAltText: load_fn!(lib, "FPDF_StructElement_GetAltText"),
+ FPDF_StructElement_GetActualText: load_fn!(lib, "FPDF_StructElement_GetActualText"),
+ FPDF_StructElement_GetID: load_fn!(lib, "FPDF_StructElement_GetID"),
FPDF_StructElement_GetTitle: load_fn!(lib, "FPDF_StructElement_GetTitle"),
FPDF_StructElement_CountChildren: load_fn!(lib, "FPDF_StructElement_CountChildren"),
FPDF_StructElement_GetChildAtIndex: load_fn!(lib, "FPDF_StructElement_GetChildAtIndex"),
@@ -584,6 +628,31 @@ impl PdfiumBindings {
lib,
"FPDF_StructElement_GetMarkedContentIdAtIndex"
),
+ FPDF_StructElement_GetChildObjNum: load_fn!(lib, "FPDF_StructElement_GetChildObjNum"),
+ FPDF_StructElement_GetAttributeCount: load_fn!(
+ lib,
+ "FPDF_StructElement_GetAttributeCount"
+ ),
+ FPDF_StructElement_GetAttributeAtIndex: load_fn!(
+ lib,
+ "FPDF_StructElement_GetAttributeAtIndex"
+ ),
+ FPDF_StructElement_Attr_GetCount: load_fn!(lib, "FPDF_StructElement_Attr_GetCount"),
+ FPDF_StructElement_Attr_GetName: load_fn!(lib, "FPDF_StructElement_Attr_GetName"),
+ FPDF_StructElement_Attr_GetValue: load_fn!(lib, "FPDF_StructElement_Attr_GetValue"),
+ FPDF_StructElement_Attr_GetType: load_fn!(lib, "FPDF_StructElement_Attr_GetType"),
+ FPDF_StructElement_Attr_GetBooleanValue: load_fn!(
+ lib,
+ "FPDF_StructElement_Attr_GetBooleanValue"
+ ),
+ FPDF_StructElement_Attr_GetNumberValue: load_fn!(
+ lib,
+ "FPDF_StructElement_Attr_GetNumberValue"
+ ),
+ FPDF_StructElement_Attr_GetStringValue: load_fn!(
+ lib,
+ "FPDF_StructElement_Attr_GetStringValue"
+ ),
_lib: lib,
})
diff --git a/crates/pdfium/src/lib.rs b/crates/pdfium/src/lib.rs
index 2234e6f..8e813d4 100644
--- a/crates/pdfium/src/lib.rs
+++ b/crates/pdfium/src/lib.rs
@@ -17,7 +17,7 @@ pub use page::{
ImageBounds, ImageObjectInfo, ImageObjects, Page, PathObject, PathSegment, PdfAnnotation,
PdfFormField, PdfLink, SegmentKind, ViewportTransform,
};
-pub use struct_tree::StructNode;
+pub use struct_tree::{StructNode, StructureAttributeValue, StructureElement};
pub use text_page::{TextChar, TextCharIter, TextPage};
pub use types::*;
diff --git a/crates/pdfium/src/page.rs b/crates/pdfium/src/page.rs
index 58fb393..57af9bc 100644
--- a/crates/pdfium/src/page.rs
+++ b/crates/pdfium/src/page.rs
@@ -185,6 +185,7 @@ pub struct PdfLink {
/// origin, 72 DPI). String fields mirror the standard annotation dictionary.
#[derive(Debug, Clone)]
pub struct PdfAnnotation {
+ pub object_number: Option<i32>,
pub subtype: String,
pub contents: Option<String>,
pub created: Option<String>,
@@ -765,6 +766,10 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
};
out.push(PdfAnnotation {
+ object_number: match unsafe { ffi!(FPDFAnnot_GetObjNum(annot)) } {
+ number if number > 0 => Some(number),
+ _ => None,
+ },
subtype: annotation_subtype_name(subtype).to_string(),
contents: read_annotation_string(annot, b"Contents\0"),
created: read_annotation_string(annot, b"CreationDate\0"),
diff --git a/crates/pdfium/src/struct_tree.rs b/crates/pdfium/src/struct_tree.rs
index 6767fe5..bcde073 100644
--- a/crates/pdfium/src/struct_tree.rs
+++ b/crates/pdfium/src/struct_tree.rs
@@ -15,6 +15,30 @@
use crate::ffi;
use crate::page::{Page, ViewportTransform};
use crate::types::RectF;
+use std::collections::BTreeMap;
+
+/// A scalar value from a structure element's PDF `/A` attribute dictionary.
+#[derive(Debug, Clone, PartialEq)]
+pub enum StructureAttributeValue {
+ Boolean(bool),
+ Number(f32),
+ String(String),
+}
+
+/// One element in the page-scoped tagged-PDF structure tree.
+#[derive(Debug, Clone)]
+pub struct StructureElement {
+ pub element_type: String,
+ pub id: Option<String>,
+ pub actual_text: Option<String>,
+ pub alt_text: Option<String>,
+ pub title: Option<String>,
+ pub attributes: BTreeMap<String, StructureAttributeValue>,
+ pub marked_content_ids: Vec<i32>,
+ pub children: Vec<StructureElement>,
+ /// PDF object numbers for link annotations referenced by non-element children.
+ pub annotation_object_numbers: Vec<i32>,
+}
/// One node in the structure tree, flattened for downstream use.
#[derive(Debug, Clone)]
@@ -32,6 +56,25 @@ pub struct StructNode {
}
impl Page<'_, '_> {
+ /// Extract the complete tagged-PDF structure tree for public output.
+ /// Returns an empty vector for untagged pages and preserves multiple roots.
+ pub fn structure_tree(&self) -> Vec<StructureElement> {
+ let tree = unsafe { ffi!(FPDF_StructTree_GetForPage(self.handle)) };
+ if tree.is_null() {
+ return Vec::new();
+ }
+ let count = unsafe { ffi!(FPDF_StructTree_CountChildren(tree)) };
+ let mut roots = Vec::with_capacity(count.max(0) as usize);
+ for index in 0..count {
+ let element = unsafe { ffi!(FPDF_StructTree_GetChildAtIndex(tree, index)) };
+ if !element.is_null() {
+ roots.push(read_structure_element(element));
+ }
+ }
+ unsafe { ffi!(FPDF_StructTree_Close(tree)) };
+ roots
+ }
+
/// Walk this page's structure tree (tagged-PDF tree). Returns an empty
/// vec when the page is untagged or the document has no struct tree.
/// Nodes are returned in pre-order (parent before children).
@@ -58,6 +101,184 @@ impl Page<'_, '_> {
}
}
+fn read_structure_element(elem: pdfium_sys::FPDF_STRUCTELEMENT) -> StructureElement {
+ let element_type = read_element_type(elem);
+ let id = read_optional_widestring(|buf, len| unsafe {
+ ffi!(FPDF_StructElement_GetID(elem, buf, len))
+ });
+ let actual_text = read_optional_widestring(|buf, len| unsafe {
+ ffi!(FPDF_StructElement_GetActualText(elem, buf, len))
+ });
+ let alt_text = read_alt_text(elem);
+ let title = read_optional_widestring(|buf, len| unsafe {
+ ffi!(FPDF_StructElement_GetTitle(elem, buf, len))
+ });
+ let attributes = read_attributes(elem);
+ let marked_content_ids = read_marked_content_ids(elem);
+ let count = unsafe { ffi!(FPDF_StructElement_CountChildren(elem)) };
+ let mut children = Vec::new();
+ let mut annotation_object_numbers = Vec::new();
+ for index in 0..count {
+ let child = unsafe { ffi!(FPDF_StructElement_GetChildAtIndex(elem, index)) };
+ if child.is_null() {
+ let object_number = unsafe { ffi!(FPDF_StructElement_GetChildObjNum(elem, index)) };
+ if object_number >= 0 {
+ annotation_object_numbers.push(object_number);
+ }
+ } else {
+ children.push(read_structure_element(child));
+ }
+ }
+ StructureElement {
+ element_type,
+ id,
+ actual_text,
+ alt_text,
+ title,
+ attributes,
+ marked_content_ids,
+ children,
+ annotation_object_numbers,
+ }
+}
+
+fn read_marked_content_ids(elem: pdfium_sys::FPDF_STRUCTELEMENT) -> Vec<i32> {
+ let count = unsafe { ffi!(FPDF_StructElement_GetMarkedContentIdCount(elem)) };
+ let mut ids = Vec::with_capacity(count.max(0) as usize);
+ for index in 0..count {
+ let id = unsafe { ffi!(FPDF_StructElement_GetMarkedContentIdAtIndex(elem, index)) };
+ if id >= 0 {
+ ids.push(id);
+ }
+ }
+ ids
+}
+
+fn read_attributes(
+ elem: pdfium_sys::FPDF_STRUCTELEMENT,
+) -> BTreeMap<String, StructureAttributeValue> {
+ let mut out = BTreeMap::new();
+ let attr_count = unsafe { ffi!(FPDF_StructElement_GetAttributeCount(elem)) };
+ for attr_index in 0..attr_count {
+ let attr = unsafe { ffi!(FPDF_StructElement_GetAttributeAtIndex(elem, attr_index)) };
+ if attr.is_null() {
+ continue;
+ }
+ let value_count = unsafe { ffi!(FPDF_StructElement_Attr_GetCount(attr)) };
+ for value_index in 0..value_count {
+ let Some(name) = read_attribute_name(attr, value_index) else {
+ continue;
+ };
+ let mut name_bytes = name.as_bytes().to_vec();
+ name_bytes.push(0);
+ let value = unsafe {
+ ffi!(FPDF_StructElement_Attr_GetValue(
+ attr,
+ name_bytes.as_ptr().cast()
+ ))
+ };
+ if value.is_null() {
+ continue;
+ }
+ let value_type = unsafe { ffi!(FPDF_StructElement_Attr_GetType(value)) };
+ let parsed = if value_type == pdfium_sys::FPDF_OBJECT_BOOLEAN as i32 {
+ let mut boolean = 0;
+ (unsafe { ffi!(FPDF_StructElement_Attr_GetBooleanValue(value, &mut boolean)) } != 0)
+ .then_some(StructureAttributeValue::Boolean(boolean != 0))
+ } else if value_type == pdfium_sys::FPDF_OBJECT_NUMBER as i32 {
+ let mut number = 0.0;
+ (unsafe { ffi!(FPDF_StructElement_Attr_GetNumberValue(value, &mut number)) } != 0)
+ .then_some(StructureAttributeValue::Number(number))
+ } else if value_type == pdfium_sys::FPDF_OBJECT_STRING as i32
+ || value_type == pdfium_sys::FPDF_OBJECT_NAME as i32
+ {
+ read_attribute_string(value).map(StructureAttributeValue::String)
+ } else {
+ None
+ };
+ if let Some(parsed) = parsed {
+ out.insert(name, parsed);
+ }
+ }
+ }
+ out
+}
+
+fn read_attribute_name(attr: pdfium_sys::FPDF_STRUCTELEMENT_ATTR, index: i32) -> Option<String> {
+ let mut needed = 0;
+ unsafe {
+ ffi!(FPDF_StructElement_Attr_GetName(
+ attr,
+ index,
+ std::ptr::null_mut(),
+ 0,
+ &mut needed
+ ));
+ }
+ if needed == 0 || needed > usize::MAX as std::os::raw::c_ulong {
+ return None;
+ }
+ let mut bytes = vec![0u8; needed as usize];
+ let ok = unsafe {
+ ffi!(FPDF_StructElement_Attr_GetName(
+ attr,
+ index,
+ bytes.as_mut_ptr().cast(),
+ needed,
+ &mut needed
+ ))
+ };
+ if ok == 0 {
+ return None;
+ }
+ let end = bytes
+ .iter()
+ .position(|byte| *byte == 0)
+ .unwrap_or(bytes.len());
+ String::from_utf8(bytes[..end].to_vec()).ok()
+}
+
+fn read_attribute_string(value: pdfium_sys::FPDF_STRUCTELEMENT_ATTR_VALUE) -> Option<String> {
+ let mut needed = 0;
+ unsafe {
+ ffi!(FPDF_StructElement_Attr_GetStringValue(
+ value,
+ std::ptr::null_mut(),
+ 0,
+ &mut needed
+ ));
+ }
+ if needed < 2 || needed > usize::MAX as std::os::raw::c_ulong {
+ return None;
+ }
+ let mut buffer = vec![0u16; needed as usize / 2];
+ let ok = unsafe {
+ ffi!(FPDF_StructElement_Attr_GetStringValue(
+ value,
+ buffer.as_mut_ptr().cast(),
+ needed,
+ &mut needed
+ ))
+ };
+ if ok == 0 {
+ return None;
+ }
+ let chars = needed as usize / 2;
+ let mut end = chars.min(buffer.len());
+ while end > 0 && buffer[end - 1] == 0 {
+ end -= 1;
+ }
+ Some(String::from_utf16_lossy(&buffer[..end]))
+}
+
+fn read_optional_widestring<F>(getter: F) -> Option<String>
+where
+ F: Fn(*mut std::os::raw::c_void, std::os::raw::c_ulong) -> std::os::raw::c_ulong,
+{
+ let value = read_widestring(getter);
+ (!value.is_empty()).then_some(value)
+}
+
/// Pre-scan all page objects on the page, building `mcid → union(bbox)` in
/// viewport space. Each struct node then unions the bboxes for its own mcids.
fn collect_mcid_bboxes(
@@ -216,10 +437,9 @@ where
return String::new();
}
let chars = written / 2;
- let end = if buf.get(chars - 1) == Some(&0) {
- chars - 1
- } else {
- chars
- };
+ let mut end = chars.min(buf.len());
+ while end > 0 && buf[end - 1] == 0 {
+ end -= 1;
+ }
String::from_utf16_lossy(&buf[..end])
}
diff --git a/packages/node/README.md b/packages/node/README.md
index 38a9eff..63ff173 100644
--- a/packages/node/README.md
+++ b/packages/node/README.md
@@ -64,6 +64,7 @@ const parser = new LiteParse({
extractVectorGraphics: false, // Opt-in shapes + merged H/V lines per page
extractAnnotations: false, // Include page annotations in structured output
extractFormFields: false, // Include AcroForm widget fields and values
+ extractStructureTree: false, // Include tagged-PDF logical structure
preserveVerySmallText: false, // Keep tiny text
extractTextMetadata: false, // Opt in to MCID, font metrics, colors, char codes, and trailingSpaceGenerated
password: undefined, // Password for protected documents
@@ -90,6 +91,11 @@ viewport-space rectangle and quadpoint rectangles, and URI for external link
annotations. It is independent of `extractLinks`, which controls Markdown link
rendering. The field is omitted when extraction is disabled.
+When `extractStructureTree` is enabled, each page has a `structureTree` containing
+all tagged-PDF roots and recursive elements with type, ID, actual/alternate text,
+title, typed attributes, MCIDs, children, and referenced link annotations. Untagged
+pages have an empty `roots` array; the field is omitted when disabled.
+
## Parsing from Bytes
Pass a `Buffer` or `Uint8Array` directly — useful for HTTP responses or in-memory data:
diff --git a/packages/node/native.d.ts b/packages/node/native.d.ts
index 90e72b7..7f435d5 100644
--- a/packages/node/native.d.ts
+++ b/packages/node/native.d.ts
@@ -53,7 +53,10 @@ export interface JsLiteParseConfig {
extractLinks?: boolean
/** Extract all PDF annotations as page-scoped structured data. */
extractAnnotations?: boolean
+ /** Extract AcroForm widget fields and values. */
extractFormFields?: boolean
+ /** Extract the tagged-PDF logical structure tree. */
+ extractStructureTree?: boolean
/**
* Whether a systemic OCR failure aborts the whole parse (default true).
* Set false to keep already-recovered native text and return partial
@@ -198,6 +201,27 @@ export interface JsParsedPage {
vectorGraphics?: JsVectorGraphics
annotations?: Array<JsDocumentAnnotation>
formFields?: Array<JsFormField>
+ structureTree?: JsStructureTree
+}
+export interface JsStructureAttribute {
+ name: string
+ booleanValue?: boolean
+ numberValue?: number
+ stringValue?: string
+}
+export interface JsStructureTree {
+ roots: Array<JsStructureTreeElement>
+}
+export interface JsStructureTreeElement {
+ elementType: string
+ id?: string
+ actualText?: string
+ altText?: string
+ title?: string
+ attributes: Array<JsStructureAttribute>
+ markedContentIds: Array<number>
+ children: Array<JsStructureTreeElement>
+ annotations: Array<JsDocumentAnnotation>
}
export interface JsVectorShape {
bbox: JsRect
@@ -244,7 +268,6 @@ export interface JsDocumentAnnotation {
quadpointRects: Array<JsAnnotationRect>
uri?: string
}
-
export interface JsFormField {
id: string
fieldType: string
diff --git a/packages/node/src/cli-json.ts b/packages/node/src/cli-json.ts
index 11e527c..3ff7fa8 100644
--- a/packages/node/src/cli-json.ts
+++ b/packages/node/src/cli-json.ts
@@ -6,6 +6,7 @@ import type {
ParseResult,
TextItem,
VectorGraphics,
+ StructureTreeElement,
} from "./lib.js";
function textItemToCliJson(item: TextItem) {
@@ -35,6 +36,20 @@ function textItemToCliJson(item: TextItem) {
};
}
+function structureTreeElementToCliJson(element: StructureTreeElement): object {
+ return {
+ type: element.type,
+ ...(element.id !== undefined ? { id: element.id } : {}),
+ ...(element.actualText !== undefined ? { actual_text: element.actualText } : {}),
+ ...(element.altText !== undefined ? { alt_text: element.altText } : {}),
+ ...(element.title !== undefined ? { title: element.title } : {}),
+ ...(Object.keys(element.attributes).length ? { attributes: element.attributes } : {}),
+ marked_content_ids: element.markedContentIds,
+ children: element.children.map(structureTreeElementToCliJson),
+ annotations: element.annotations.map(annotationToCliJson),
+ };
+}
+
function complexityToCliJson(complexity: PageComplexityStats) {
return {
page_number: complexity.pageNumber,
@@ -197,6 +212,13 @@ export function parseResultToCliJson(result: ParseResult) {
...(page.formFields !== undefined
? { form_fields: page.formFields.map(formFieldToCliJson) }
: {}),
+ ...(page.structureTree !== undefined
+ ? {
+ structure_tree: {
+ roots: page.structureTree.roots.map(structureTreeElementToCliJson),
+ },
+ }
+ : {}),
})),
...(result.images.length
? { images: result.images.map(imageToCliJson) }
diff --git a/packages/node/src/cli.ts b/packages/node/src/cli.ts
index e8a2e6a..6766a9e 100644
--- a/packages/node/src/cli.ts
+++ b/packages/node/src/cli.ts
@@ -67,6 +67,7 @@ program
.option("--no-links", "Disable hyperlink extraction (emit plain anchor text)")
.option("--extract-annotations", "Include all PDF annotations in page output")
.option("--extract-form-fields", "Include AcroForm widget fields and values")
+ .option("--extract-structure-tree", "Include the tagged-PDF logical structure tree")
.option("--ocr-server-url <url>", "HTTP OCR server URL")
.option(
"--ocr-server-header <header>",
@@ -120,6 +121,7 @@ program
if (opts.links === false) config.extractLinks = false;
if (opts.extractAnnotations) config.extractAnnotations = true;
if (opts.extractFormFields) config.extractFormFields = true;
+ if (opts.extractStructureTree) config.extractStructureTree = true;
if (opts.ocrServerUrl)
config.ocrServerUrl = opts.ocrServerUrl as string;
if (opts.ocrServerHeader)
@@ -319,6 +321,7 @@ program
.option("--extract-images", "Extract embedded image bytes and metadata")
.option("--extract-annotations", "Include all PDF annotations in page output")
.option("--extract-form-fields", "Include AcroForm widget fields and values")
+ .option("--extract-structure-tree", "Include the tagged-PDF logical structure tree")
.option(
"--extract-vector-graphics",
"Include page-scoped vector shapes and merged horizontal/vertical lines",
@@ -348,6 +351,7 @@ program
if (opts.extractImages) config.extractImages = true;
if (opts.extractAnnotations) config.extractAnnotations = true;
if (opts.extractFormFields) config.extractFormFields = true;
+ if (opts.extractStructureTree) config.extractStructureTree = true;
if (opts.extractVectorGraphics) config.extractVectorGraphics = true;
const parser = new LiteParse(config);
diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.ts
index 9e157e0..9da7d61 100644
--- a/packages/node/src/lib.ts
+++ b/packages/node/src/lib.ts
@@ -7,6 +7,7 @@ import {
type NativePageInput,
type NativeTextItem,
type NativeExtractedImage,
+ type NativeStructureTreeElement,
type NativePageComplexityStats,
} from "./native.js";
@@ -41,6 +42,8 @@ export interface LiteParseConfig {
extractAnnotations: boolean;
/** Extract AcroForm widget fields and values (default: false). */
extractFormFields: boolean;
+ /** Extract the tagged-PDF logical structure tree (default: false). */
+ extractStructureTree: boolean;
preserveVerySmallText: boolean;
password?: string;
quiet: boolean;
@@ -210,6 +213,26 @@ export interface ParsedPage {
annotations?: DocumentAnnotation[];
/** Present only when `extractFormFields` is enabled. */
formFields?: FormField[];
+ /** Present only when `extractStructureTree` is enabled. */
+ structureTree?: StructureTree;
+}
+
+export type StructureAttributeValue = boolean | number | string;
+
+export interface StructureTree {
+ roots: StructureTreeElement[];
+}
+
+export interface StructureTreeElement {
+ type: string;
+ id?: string;
+ actualText?: string;
+ altText?: string;
+ title?: string;
+ attributes: Record<string, StructureAttributeValue>;
+ markedContentIds: number[];
+ children: StructureTreeElement[];
+ annotations: DocumentAnnotation[];
}
export interface VectorGraphics {
@@ -413,6 +436,7 @@ export class LiteParse {
extractLinks: userConfig.extractLinks,
extractAnnotations: userConfig.extractAnnotations,
extractFormFields: userConfig.extractFormFields,
+ extractStructureTree: userConfig.extractStructureTree,
preserveVerySmallText: userConfig.preserveVerySmallText,
password: userConfig.password,
quiet: userConfig.quiet,
@@ -447,6 +471,7 @@ export class LiteParse {
extractLinks: resolved.extractLinks ?? true,
extractAnnotations: resolved.extractAnnotations ?? false,
extractFormFields: resolved.extractFormFields ?? false,
+ extractStructureTree: resolved.extractStructureTree ?? false,
preserveVerySmallText: resolved.preserveVerySmallText ?? false,
password: resolved.password ?? undefined,
quiet: resolved.quiet ?? false,
@@ -595,6 +620,35 @@ function toPage(p: NativeParsedPage): ParsedPage {
options: field.options,
selectedOptions: field.selectedOptions,
})),
+ structureTree: p.structureTree
+ ? { roots: p.structureTree.roots.map(toStructureTreeElement) }
+ : undefined,
+ };
+}
+
+function toStructureTreeElement(
+ element: NativeStructureTreeElement,
+): StructureTreeElement {
+ const attributes: Record<string, StructureAttributeValue> = {};
+ for (const attribute of element.attributes) {
+ if (attribute.booleanValue !== undefined) {
+ attributes[attribute.name] = attribute.booleanValue;
+ } else if (attribute.numberValue !== undefined) {
+ attributes[attribute.name] = attribute.numberValue;
+ } else if (attribute.stringValue !== undefined) {
+ attributes[attribute.name] = attribute.stringValue;
+ }
+ }
+ return {
+ type: element.elementType,
+ id: element.id,
+ actualText: element.actualText,
+ altText: element.altText,
+ title: element.title,
+ attributes,
+ markedContentIds: element.markedContentIds,
+ children: element.children.map(toStructureTreeElement),
+ annotations: element.annotations,
};
}
diff --git a/packages/node/src/native.ts b/packages/node/src/native.ts
index 76972a4..13e0a55 100644
--- a/packages/node/src/native.ts
+++ b/packages/node/src/native.ts
@@ -35,6 +35,7 @@ export interface LiteParseNativeConfig {
extractLinks?: boolean;
extractAnnotations?: boolean;
extractFormFields?: boolean;
+ extractStructureTree?: boolean;
preserveVerySmallText?: boolean;
password?: string;
quiet?: boolean;
@@ -124,6 +125,30 @@ export interface NativeParsedPage {
vectorGraphics?: NativeVectorGraphics;
annotations?: NativeDocumentAnnotation[];
formFields?: NativeFormField[];
+ structureTree?: NativeStructureTree;
+}
+
+export interface NativeStructureAttribute {
+ name: string;
+ booleanValue?: boolean;
+ numberValue?: number;
+ stringValue?: string;
+}
+
+export interface NativeStructureTree {
+ roots: NativeStructureTreeElement[];
+}
+
+export interface NativeStructureTreeElement {
+ elementType: string;
+ id?: string;
+ actualText?: string;
+ altText?: string;
+ title?: string;
+ attributes: NativeStructureAttribute[];
+ markedContentIds: number[];
+ children: NativeStructureTreeElement[];
+ annotations: NativeDocumentAnnotation[];
}
export interface NativeVectorGraphics {
diff --git a/packages/python/README.md b/packages/python/README.md
index b81e4ea..12ba698 100644
--- a/packages/python/README.md
+++ b/packages/python/README.md
@@ -63,6 +63,7 @@ parser = LiteParse(
extract_vector_graphics=False, # Opt-in shapes + merged H/V lines per page
extract_annotations=False, # Include page annotations in structured output
extract_form_fields=False, # Include AcroForm widget fields and values
+ extract_structure_tree=False, # Include tagged-PDF logical structure
preserve_very_small_text=False, # Keep tiny text
extract_text_metadata=False, # Opt in to MCID, font metrics, colors, char codes, and trailing_space_generated
password=None, # Password for protected documents
@@ -86,6 +87,11 @@ viewport-space rectangle and quadpoint rectangles, and URI for external link
annotations. It is independent of `extract_links`, which controls Markdown
link rendering. The field is `None` when extraction is disabled.
+When ``extract_structure_tree=True``, each page has a ``structure_tree`` containing
+all tagged-PDF roots and recursive elements with type, ID, actual/alternate text,
+title, typed attributes, MCIDs, children, and referenced link annotations. Untagged
+pages have an empty ``roots`` list; the field is ``None`` when disabled.
+
## Parsing from Bytes
Pass raw PDF bytes directly — useful for web uploads or downloaded files:
diff --git a/packages/python/liteparse/__init__.py b/packages/python/liteparse/__init__.py
index c8940e3..8f3d36c 100644
--- a/packages/python/liteparse/__init__.py
+++ b/packages/python/liteparse/__init__.py
@@ -5,6 +5,8 @@ from .types import (
AnnotationRect,
DocumentAnnotation,
FormField,
+ StructureTree,
+ StructureTreeElement,
ExtractedImage,
ImageRect,
LayoutComplexityStats,
@@ -30,6 +32,8 @@ __all__ = [
"AnnotationRect",
"DocumentAnnotation",
"FormField",
+ "StructureTree",
+ "StructureTreeElement",
"LiteParseConfig",
"ParseResult",
"ParsedPage",
diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.py
index b9bb592..8c7b89d 100644
--- a/packages/python/liteparse/parser.py
+++ b/packages/python/liteparse/parser.py
@@ -10,6 +10,8 @@ from .types import (
AnnotationRect,
DocumentAnnotation,
FormField,
+ StructureTree,
+ StructureTreeElement,
ExtractedImage,
ImageRect,
LayoutComplexityStats,
@@ -27,6 +29,53 @@ from .types import (
)
+def _convert_annotation(annotation: Any) -> DocumentAnnotation:
+ return DocumentAnnotation(
+ subtype=annotation.subtype,
+ contents=annotation.contents,
+ created=annotation.created,
+ modified=annotation.modified,
+ title=annotation.title,
+ rect=(
+ AnnotationRect(
+ x=annotation.rect.x,
+ y=annotation.rect.y,
+ width=annotation.rect.width,
+ height=annotation.rect.height,
+ )
+ if annotation.rect is not None
+ else None
+ ),
+ quadpoint_rects=[
+ AnnotationRect(x=r.x, y=r.y, width=r.width, height=r.height)
+ for r in annotation.quadpoint_rects
+ ],
+ uri=annotation.uri,
+ )
+
+
+def _convert_structure_element(element: Any) -> StructureTreeElement:
+ attributes = {}
+ for attribute in element.attributes:
+ if attribute.boolean_value is not None:
+ attributes[attribute.name] = attribute.boolean_value
+ elif attribute.number_value is not None:
+ attributes[attribute.name] = attribute.number_value
+ elif attribute.string_value is not None:
+ attributes[attribute.name] = attribute.string_value
+ return StructureTreeElement(
+ element_type=element.element_type,
+ id=element.id,
+ actual_text=element.actual_text,
+ alt_text=element.alt_text,
+ title=element.title,
+ attributes=attributes,
+ marked_content_ids=list(element.marked_content_ids),
+ children=[_convert_structure_element(child) for child in element.children],
+ annotations=[_convert_annotation(a) for a in element.annotations],
+ )
+
+
def _convert_complexity(s: Any) -> PageComplexityStats:
"""Convert a native PyPageComplexityStats to our Python dataclass."""
return PageComplexityStats(
@@ -103,6 +152,7 @@ def _convert_native_result(native_result: Any) -> ParseResult:
native_vectors = getattr(native_page, "vector_graphics", None)
native_annotations = getattr(native_page, "annotations", None)
native_form_fields = getattr(native_page, "form_fields", None)
+ native_structure_tree = getattr(native_page, "structure_tree", None)
pages.append(
ParsedPage(
page_num=native_page.page_num,
@@ -207,6 +257,16 @@ def _convert_native_result(native_result: Any) -> ParseResult:
if native_form_fields is not None
else None
),
+ structure_tree=(
+ StructureTree(
+ roots=[
+ _convert_structure_element(root)
+ for root in native_structure_tree.roots
+ ]
+ )
+ if native_structure_tree is not None
+ else None
+ ),
)
)
images = [
@@ -274,6 +334,7 @@ class LiteParse:
extract_links: Optional[bool] = None,
extract_annotations: Optional[bool] = None,
extract_form_fields: Optional[bool] = None,
+ extract_structure_tree: Optional[bool] = None,
ocr_failure_fatal: Optional[bool] = None,
ocr_hedge_delays_ms: Optional[List[int]] = None,
emit_word_boxes: Optional[bool] = None,
@@ -313,6 +374,8 @@ class LiteParse:
structured data (default: False).
extract_form_fields: Include AcroForm widget fields and values as
page-scoped structured data (default: False).
+ extract_structure_tree: Include the tagged-PDF logical structure
+ tree as page-scoped structured data (default: False).
ocr_failure_fatal: Whether a systemic OCR failure (every OCR task
failed and at least one was a text-sparse page) aborts the whole
parse (default: True). Set False to keep already-recovered native
@@ -387,6 +450,8 @@ class LiteParse:
kwargs["extract_annotations"] = extract_annotations
if extract_form_fields is not None:
kwargs["extract_form_fields"] = extract_form_fields
+ if extract_structure_tree is not None:
+ kwargs["extract_structure_tree"] = extract_structure_tree
if ocr_failure_fatal is not None:
kwargs["ocr_failure_fatal"] = ocr_failure_fatal
if ocr_hedge_delays_ms is not None:
@@ -540,6 +605,7 @@ class LiteParse:
extract_links=cfg.extract_links,
extract_annotations=cfg.extract_annotations,
extract_form_fields=cfg.extract_form_fields,
+ extract_structure_tree=cfg.extract_structure_tree,
ocr_failure_fatal=cfg.ocr_failure_fatal,
ocr_hedge_delays_ms=list(cfg.ocr_hedge_delays_ms),
emit_word_boxes=cfg.emit_word_boxes,
diff --git a/packages/python/liteparse/types.py b/packages/python/liteparse/types.py
index b73c485..7db220f 100644
--- a/packages/python/liteparse/types.py
+++ b/packages/python/liteparse/types.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import Dict, Iterator, List, Optional, Tuple
+from typing import Dict, Iterator, List, Optional, Tuple, Union
@dataclass
@@ -93,6 +93,29 @@ class FormField:
selected_options: List[str] = field(default_factory=list)
+StructureAttributeValue = Union[bool, float, str]
+
+
+@dataclass
+class StructureTreeElement:
+ """One element in a tagged-PDF logical structure tree."""
+ element_type: str
+ id: Optional[str] = None
+ actual_text: Optional[str] = None
+ alt_text: Optional[str] = None
+ title: Optional[str] = None
+ attributes: Dict[str, StructureAttributeValue] = field(default_factory=dict)
+ marked_content_ids: List[int] = field(default_factory=list)
+ children: List[StructureTreeElement] = field(default_factory=list)
+ annotations: List[DocumentAnnotation] = field(default_factory=list)
+
+
+@dataclass
+class StructureTree:
+ """Complete page-scoped tagged-PDF logical structure."""
+ roots: List[StructureTreeElement] = field(default_factory=list)
+
+
@dataclass
class ParsedPage:
"""A parsed page from a document."""
@@ -112,6 +135,8 @@ class ParsedPage:
annotations: Optional[List[DocumentAnnotation]] = None
#: Present only when parsing with ``extract_form_fields=True``.
form_fields: Optional[List[FormField]] = None
+ #: Present only when parsing with ``extract_structure_tree=True``.
+ structure_tree: Optional[StructureTree] = None
@dataclass
@@ -273,6 +298,7 @@ class LiteParseConfig:
extract_links: bool
extract_annotations: bool
extract_form_fields: bool
+ extract_structure_tree: bool
ocr_failure_fatal: bool
ocr_hedge_delays_ms: List[int]
emit_word_boxes: bool
diff --git a/packages/wasm/README.md b/packages/wasm/README.md
index e5070d1..0c0b14d 100644
--- a/packages/wasm/README.md
+++ b/packages/wasm/README.md
@@ -70,6 +70,7 @@ All optional, camelCase:
| `extractLinks` | `boolean` | `true` | Render hyperlink annotations as `[text](url)` in markdown output |
| `extractVectorGraphics` | `boolean` | `false` | Include page-scoped shapes and merged horizontal/vertical lines |
| `extractAnnotations` | `boolean` | `false` | Include page annotations and their metadata/geometry in structured output |
+| `extractStructureTree` | `boolean` | `false` | Include the tagged-PDF logical structure tree |
| `preserveVerySmallText` | `boolean` | `false` | Keep tiny text that's normally filtered |
| `password` | `string` | — | Password for protected PDFs |
| `quiet` | `boolean` | `false` | Suppress progress logging |