Skip to content

A fast, helpful, and open-source document parser

Add remaining pdfium-extract parity capabilities

Pierre-Loic doulcetf0bbc83677f4
diff --git a/README.md b/README.md
index 8c7004c..d7db3fd 100644
--- a/README.md
+++ b/README.md
@@ -253,6 +253,25 @@ text, title, typed scalar attributes, marked-content IDs, children, and referenc
link annotations. The field is absent by default; enabled untagged pages contain
`roots: []`.
+### Document metadata, content bounds, and XFA packets
+
+Every parse result now carries the document's `/Info` `creator` and `producer`
+entries when present, and every page carries `content_bounds` — the union bbox
+of the page's top-level content objects in viewport coords (absent for empty
+pages). Enable `--extract-xfa-packets` (Rust/Python `extract_xfa_packets`,
+JavaScript/WASM `extractXfaPackets`) to add `xfa_packets` with each raw XFA
+packet's index, name, byte length, and XML content; non-XFA documents yield an
+empty list.
+
+### Screenshot raster signals
+
+Screenshots draw AcroForm field appearances (filled values, checkbox states)
+on top of the page raster, so form data is visible in the render and to OCR.
+Each screenshot result reports `is_solid_fill` (blank page after render), and
+with `detect_screenshot_rects` (Node `detectScreenshotRects`) also `rects` —
+solid same-color rectangles and lines found in the raster in viewport coords,
+which covers scanned/flattened pages that carry no vector paths.
+
### Check Complexity
Before committing to a full parse, check whether a document actually needs OCR or
diff --git a/crates/liteparse-napi/src/lib.rs b/crates/liteparse-napi/src/lib.rs
index cb87613..27a725a 100644
--- a/crates/liteparse-napi/src/lib.rs
+++ b/crates/liteparse-napi/src/lib.rs
@@ -117,6 +117,12 @@ impl LiteParse {
width: r.width,
height: r.height,
image_buffer: r.image_bytes.into(),
+ is_solid_fill: r.is_solid_fill,
+ rects: r
+ .rects
+ .iter()
+ .map(crate::types::JsScreenshotRect::from_rust)
+ .collect(),
})
.collect())
}
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index e1c1f26..11879eb 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -5,9 +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,
+ DocumentAnnotation, FormField, GraphicPrimitive, Page, ParsedPage, Rect, ScreenshotRect,
StructureAttributeValue, StructureTree, StructureTreeElement, TextItem, VectorGraphics,
- WordBox,
+ WordBox, XfaPacket,
};
// ---------------------------------------------------------------------------
@@ -62,6 +62,12 @@ pub struct JsLiteParseConfig {
pub extract_form_fields: Option<bool>,
/// Extract the tagged-PDF logical structure tree.
pub extract_structure_tree: Option<bool>,
+ /// Extract raw XFA packets (name + XML content) into
+ /// `ParseResult.xfaPackets`. Default false.
+ pub extract_xfa_packets: Option<bool>,
+ /// Detect solid rectangles/lines in rendered page screenshots and attach
+ /// them to each screenshot result. Default false.
+ pub detect_screenshot_rects: 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.
@@ -173,6 +179,12 @@ impl JsLiteParseConfig {
if let Some(v) = self.extract_structure_tree {
cfg.extract_structure_tree = v;
}
+ if let Some(v) = self.extract_xfa_packets {
+ cfg.extract_xfa_packets = v;
+ }
+ if let Some(v) = self.detect_screenshot_rects {
+ cfg.detect_screenshot_rects = v;
+ }
if let Some(v) = self.ocr_failure_fatal {
cfg.ocr_failure_fatal = v;
}
@@ -239,6 +251,8 @@ impl JsLiteParseConfig {
extract_annotations: Some(cfg.extract_annotations),
extract_form_fields: Some(cfg.extract_form_fields),
extract_structure_tree: Some(cfg.extract_structure_tree),
+ extract_xfa_packets: Some(cfg.extract_xfa_packets),
+ detect_screenshot_rects: Some(cfg.detect_screenshot_rects),
ocr_failure_fatal: Some(cfg.ocr_failure_fatal),
ocr_hedge_delays_ms: Some(
cfg.ocr_hedge_delays_ms
@@ -488,6 +502,7 @@ impl JsPageInput {
page_number: self.page_number as usize,
page_width: self.page_width as f32,
page_height: self.page_height as f32,
+ content_bounds: None,
text_items: self.text_items.iter().map(JsTextItem::to_rust).collect(),
graphics: self
.graphics
@@ -514,6 +529,9 @@ pub struct JsParsedPage {
pub page_num: u32,
pub width: f64,
pub height: f64,
+ /// Union bbox of the page's top-level content objects in viewport
+ /// coords (visible content extent). Absent for empty pages.
+ pub content_bounds: Option<JsRect>,
pub text: String,
pub markdown: String,
pub text_items: Vec<JsTextItem>,
@@ -787,6 +805,12 @@ impl JsParsedPage {
page_num: page.page_number as u32,
width: page.page_width as f64,
height: page.page_height as f64,
+ content_bounds: page.content_bounds.as_ref().map(|b| JsRect {
+ x: b.x as f64,
+ y: b.y as f64,
+ width: b.width as f64,
+ height: b.height as f64,
+ }),
text: page.text.clone(),
markdown: page.markdown.clone(),
text_items: page
@@ -829,6 +853,34 @@ pub struct JsParseResult {
pub images: Vec<JsExtractedImage>,
pub image_error_count: u32,
pub form_type: Option<i32>,
+ /// The document's `/Info` `Creator` entry, when present.
+ pub creator: Option<String>,
+ /// The document's `/Info` `Producer` entry, when present.
+ pub producer: Option<String>,
+ /// Raw XFA packets; present only when `extractXfaPackets` is enabled.
+ pub xfa_packets: Option<Vec<JsXfaPacket>>,
+}
+
+/// One raw packet from an XFA form document's `/XFA` array.
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsXfaPacket {
+ pub index: u32,
+ pub name: Option<String>,
+ pub content_length: u32,
+ /// Packet content (usually XML), lossily decoded as UTF-8.
+ pub content: Option<String>,
+}
+
+impl JsXfaPacket {
+ fn from_rust(packet: &XfaPacket) -> Self {
+ Self {
+ index: packet.index,
+ name: packet.name.clone(),
+ content_length: packet.content_length,
+ content: packet.content.clone(),
+ }
+ }
}
#[napi(object)]
@@ -867,6 +919,39 @@ pub struct JsScreenshotResult {
pub width: u32,
pub height: u32,
pub image_buffer: napi::bindgen_prelude::Buffer,
+ /// True when every pixel has the same color (blank page after render).
+ pub is_solid_fill: bool,
+ /// Solid rectangles/lines detected in the raster (viewport coords).
+ /// Populated only when `detectScreenshotRects` is enabled.
+ pub rects: Vec<JsScreenshotRect>,
+}
+
+/// One solid rectangle (or line) detected in a rendered page bitmap, in
+/// viewport coords (top-left origin, 72 DPI).
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsScreenshotRect {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+ /// Fill color as ARGB hex string (e.g. "ff1a2b3c").
+ pub color: String,
+ /// True when the region is a solid line rather than a filled area.
+ pub is_line: bool,
+}
+
+impl JsScreenshotRect {
+ pub fn from_rust(rect: &ScreenshotRect) -> Self {
+ Self {
+ x: rect.x as f64,
+ y: rect.y as f64,
+ width: rect.width as f64,
+ height: rect.height as f64,
+ color: rect.color.clone(),
+ is_line: rect.is_line,
+ }
+ }
}
#[napi(object)]
@@ -959,6 +1044,12 @@ impl JsParseResult {
text: result.text.clone(),
image_error_count: result.image_error_count,
form_type: result.form_type,
+ creator: result.creator.clone(),
+ producer: result.producer.clone(),
+ xfa_packets: result
+ .xfa_packets
+ .as_ref()
+ .map(|packets| packets.iter().map(JsXfaPacket::from_rust).collect()),
images: result
.images
.iter()
diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rs
index f1f3b1a..b031427 100644
--- a/crates/liteparse-python/src/cli.rs
+++ b/crates/liteparse-python/src/cli.rs
@@ -85,6 +85,9 @@ struct ParseCommand {
/// Include the tagged-PDF logical structure tree.
#[arg(long)]
extract_structure_tree: bool,
+ /// Include raw XFA packets (name + XML content) in JSON output.
+ #[arg(long)]
+ extract_xfa_packets: bool,
/// Include per-page complexity signals as a `complexity` object on each
/// page of JSON output. Off by default.
#[arg(long)]
@@ -177,6 +180,9 @@ struct BatchParseCommand {
/// Include the tagged-PDF logical structure tree.
#[arg(long)]
extract_structure_tree: bool,
+ /// Include raw XFA packets (name + XML content) in JSON output.
+ #[arg(long)]
+ extract_xfa_packets: bool,
}
/// Parse a `Name: Value` header string into a `(name, value)` pair.
@@ -259,6 +265,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
extract_annotations: cmd.extract_annotations,
extract_form_fields: cmd.extract_form_fields,
extract_structure_tree: cmd.extract_structure_tree,
+ extract_xfa_packets: cmd.extract_xfa_packets,
include_complexity: cmd.complexity,
extract_text_metadata: cmd.extract_text_metadata,
extract_vector_graphics: cmd.extract_vector_graphics,
@@ -274,13 +281,9 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
rt.block_on(lp.parse(&cmd.file))?
};
let formatted = match lp.config().output_format {
- OutputFormat::Json => json::format_json_result(
- &result.pages,
- &result.images,
- result.image_error_count,
- lp.config().extract_text_metadata,
- result.form_type,
- )?,
+ OutputFormat::Json => {
+ json::format_json_result(&result, lp.config().extract_text_metadata)?
+ }
OutputFormat::Text => text::format_text(&result.pages),
OutputFormat::Markdown => result.text.clone(),
};
@@ -356,6 +359,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
extract_images: cmd.extract_images,
extract_vector_graphics: cmd.extract_vector_graphics,
extract_structure_tree: cmd.extract_structure_tree,
+ extract_xfa_packets: cmd.extract_xfa_packets,
..Default::default()
};
if let Some(n) = cmd.num_workers {
@@ -397,11 +401,8 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
let fmt_result: Result<String, Box<dyn std::error::Error>> =
match lp.config().output_format {
OutputFormat::Json => json::format_json_result(
- &result.pages,
- &result.images,
- result.image_error_count,
+ &result,
lp.config().extract_text_metadata,
- result.form_type,
)
.map_err(|e| e.into()),
OutputFormat::Text => Ok(text::format_text(&result.pages)),
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index 3c4ba59..d9707cf 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -409,6 +409,8 @@ struct PyParsedPage {
#[pyo3(get)]
height: f64,
#[pyo3(get)]
+ content_bounds: Option<PyRect>,
+ #[pyo3(get)]
text: String,
#[pyo3(get)]
markdown: String,
@@ -546,6 +548,12 @@ impl PyParsedPage {
page_num: page.page_number as u32,
width: page.page_width as f64,
height: page.page_height as f64,
+ content_bounds: page.content_bounds.as_ref().map(|b| PyRect {
+ x: b.x as f64,
+ y: b.y as f64,
+ width: b.width as f64,
+ height: b.height as f64,
+ }),
text: page.text,
markdown: page.markdown,
text_items: page
@@ -591,6 +599,36 @@ struct PyParseResult {
image_error_count: u32,
#[pyo3(get)]
form_type: Option<i32>,
+ #[pyo3(get)]
+ creator: Option<String>,
+ #[pyo3(get)]
+ producer: Option<String>,
+ #[pyo3(get)]
+ xfa_packets: Option<Vec<PyXfaPacket>>,
+}
+
+/// One raw packet from an XFA form document's `/XFA` array.
+#[pyclass(frozen, from_py_object)]
+#[derive(Clone)]
+struct PyXfaPacket {
+ #[pyo3(get)]
+ index: u32,
+ #[pyo3(get)]
+ name: Option<String>,
+ #[pyo3(get)]
+ content_length: u32,
+ #[pyo3(get)]
+ content: Option<String>,
+}
+
+#[pymethods]
+impl PyXfaPacket {
+ fn __repr__(&self) -> String {
+ format!(
+ "XfaPacket(index={}, name={:?}, content_length={})",
+ self.index, self.name, self.content_length
+ )
+ }
}
#[pymethods]
@@ -630,6 +668,19 @@ impl PyParseResult {
.collect(),
image_error_count: result.image_error_count,
form_type: result.form_type,
+ creator: result.creator,
+ producer: result.producer,
+ xfa_packets: result.xfa_packets.map(|packets| {
+ packets
+ .into_iter()
+ .map(|packet| PyXfaPacket {
+ index: packet.index,
+ name: packet.name,
+ content_length: packet.content_length,
+ content: packet.content,
+ })
+ .collect()
+ }),
}
}
}
@@ -724,6 +775,39 @@ struct PyScreenshotResult {
#[pyo3(get)]
height: u32,
image_buffer: Vec<u8>,
+ #[pyo3(get)]
+ is_solid_fill: bool,
+ #[pyo3(get)]
+ rects: Vec<PyScreenshotRect>,
+}
+
+/// One solid rectangle (or line) detected in a rendered page bitmap, in
+/// viewport coords (top-left origin, 72 DPI).
+#[pyclass(frozen, from_py_object)]
+#[derive(Clone)]
+struct PyScreenshotRect {
+ #[pyo3(get)]
+ x: f64,
+ #[pyo3(get)]
+ y: f64,
+ #[pyo3(get)]
+ width: f64,
+ #[pyo3(get)]
+ height: f64,
+ #[pyo3(get)]
+ color: String,
+ #[pyo3(get)]
+ is_line: bool,
+}
+
+#[pymethods]
+impl PyScreenshotRect {
+ fn __repr__(&self) -> String {
+ format!(
+ "ScreenshotRect(x={}, y={}, width={}, height={}, color={}, is_line={})",
+ self.x, self.y, self.width, self.height, self.color, self.is_line
+ )
+ }
}
#[pymethods]
@@ -906,6 +990,10 @@ struct PyLiteParseConfig {
#[pyo3(get)]
extract_structure_tree: bool,
#[pyo3(get)]
+ extract_xfa_packets: bool,
+ #[pyo3(get)]
+ detect_screenshot_rects: bool,
+ #[pyo3(get)]
ocr_failure_fatal: bool,
#[pyo3(get)]
ocr_hedge_delays_ms: Vec<u64>,
@@ -970,6 +1058,8 @@ impl PyLiteParseConfig {
extract_annotations: cfg.extract_annotations,
extract_form_fields: cfg.extract_form_fields,
extract_structure_tree: cfg.extract_structure_tree,
+ extract_xfa_packets: cfg.extract_xfa_packets,
+ detect_screenshot_rects: cfg.detect_screenshot_rects,
ocr_failure_fatal: cfg.ocr_failure_fatal,
ocr_hedge_delays_ms: cfg.ocr_hedge_delays_ms.clone(),
emit_word_boxes: cfg.emit_word_boxes,
@@ -1023,6 +1113,8 @@ impl LiteParse {
extract_annotations = None,
extract_form_fields = None,
extract_structure_tree = None,
+ extract_xfa_packets = None,
+ detect_screenshot_rects = None,
ocr_failure_fatal = None,
ocr_hedge_delays_ms = None,
emit_word_boxes = None,
@@ -1053,6 +1145,8 @@ impl LiteParse {
extract_annotations: Option<bool>,
extract_form_fields: Option<bool>,
extract_structure_tree: Option<bool>,
+ extract_xfa_packets: Option<bool>,
+ detect_screenshot_rects: Option<bool>,
ocr_failure_fatal: Option<bool>,
ocr_hedge_delays_ms: Option<Vec<u64>>,
emit_word_boxes: Option<bool>,
@@ -1131,6 +1225,12 @@ impl LiteParse {
if let Some(v) = extract_structure_tree {
cfg.extract_structure_tree = v;
}
+ if let Some(v) = extract_xfa_packets {
+ cfg.extract_xfa_packets = v;
+ }
+ if let Some(v) = detect_screenshot_rects {
+ cfg.detect_screenshot_rects = v;
+ }
if let Some(v) = ocr_failure_fatal {
cfg.ocr_failure_fatal = v;
}
@@ -1244,6 +1344,19 @@ impl LiteParse {
width: r.width,
height: r.height,
image_buffer: r.image_bytes,
+ is_solid_fill: r.is_solid_fill,
+ rects: r
+ .rects
+ .into_iter()
+ .map(|rect| PyScreenshotRect {
+ x: rect.x as f64,
+ y: rect.y as f64,
+ width: rect.width as f64,
+ height: rect.height as f64,
+ color: rect.color,
+ is_line: rect.is_line,
+ })
+ .collect(),
})
.collect())
})
@@ -1347,6 +1460,8 @@ fn _liteparse(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyStructureTree>()?;
m.add_class::<PyFormField>()?;
m.add_class::<PyScreenshotResult>()?;
+ m.add_class::<PyScreenshotRect>()?;
+ m.add_class::<PyXfaPacket>()?;
m.add_class::<PyPageComplexityStats>()?;
m.add_class::<PyLayoutComplexityStats>()?;
m.add_class::<PyRect>()?;
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index 8b800f2..ffe7af4 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -59,6 +59,9 @@ pub struct LiteParseConfig {
extract_annotations: Option<bool>,
extract_form_fields: Option<bool>,
extract_structure_tree: Option<bool>,
+ /// Extract raw XFA packets (name + XML content) into
+ /// `ParseResult.xfaPackets`. Default false.
+ extract_xfa_packets: Option<bool>,
ocr_failure_fatal: Option<bool>,
ocr_hedge_delays_ms: Option<Vec<u64>>,
preserve_very_small_text: Option<bool>,
@@ -154,6 +157,9 @@ impl LiteParseConfig {
if let Some(v) = self.extract_structure_tree {
cfg.extract_structure_tree = v;
}
+ if let Some(v) = self.extract_xfa_packets {
+ cfg.extract_xfa_packets = v;
+ }
if let Some(v) = self.ocr_failure_fatal {
cfg.ocr_failure_fatal = v;
}
@@ -222,6 +228,7 @@ impl LiteParseConfig {
extract_annotations: Some(cfg.extract_annotations),
extract_form_fields: Some(cfg.extract_form_fields),
extract_structure_tree: Some(cfg.extract_structure_tree),
+ extract_xfa_packets: Some(cfg.extract_xfa_packets),
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),
@@ -286,6 +293,10 @@ pub struct ParsedPage {
pub page_num: usize,
pub width: f32,
pub height: f32,
+ /// Union bbox of the page's top-level content objects in viewport
+ /// coords (visible content extent). Absent for empty pages.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content_bounds: Option<VectorRect>,
pub text: String,
pub markdown: String,
pub text_items: Vec<TextItem>,
@@ -458,6 +469,29 @@ pub struct ParseResult {
pub image_error_count: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub form_type: Option<i32>,
+ /// The document's `/Info` `Creator` entry, when present.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub creator: Option<String>,
+ /// The document's `/Info` `Producer` entry, when present.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub producer: Option<String>,
+ /// Raw XFA packets; present only when `extractXfaPackets` is enabled.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub xfa_packets: Option<Vec<XfaPacket>>,
+}
+
+/// One raw packet from an XFA form document's `/XFA` array.
+#[derive(Serialize, Tsify)]
+#[tsify(into_wasm_abi)]
+#[serde(rename_all = "camelCase")]
+pub struct XfaPacket {
+ pub index: u32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ pub content_length: u32,
+ /// Packet content (usually XML), lossily decoded as UTF-8.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content: Option<String>,
}
#[derive(Serialize, Tsify)]
@@ -670,6 +704,12 @@ impl LiteParse {
page_num: p.page_number,
width: p.page_width,
height: p.page_height,
+ content_bounds: p.content_bounds.as_ref().map(|b| VectorRect {
+ x: b.x,
+ y: b.y,
+ width: b.width,
+ height: b.height,
+ }),
text: p.text.clone(),
markdown: p.markdown.clone(),
text_items: p
@@ -780,6 +820,19 @@ impl LiteParse {
images,
image_error_count: result.image_error_count,
form_type: result.form_type,
+ creator: result.creator.clone(),
+ producer: result.producer.clone(),
+ xfa_packets: result.xfa_packets.as_ref().map(|packets| {
+ packets
+ .iter()
+ .map(|packet| XfaPacket {
+ index: packet.index,
+ name: packet.name.clone(),
+ content_length: packet.content_length,
+ content: packet.content.clone(),
+ })
+ .collect()
+ }),
})
}
diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rs
index b697c8e..b7d348c 100644
--- a/crates/liteparse/src/config.rs
+++ b/crates/liteparse/src/config.rs
@@ -54,6 +54,17 @@ pub struct LiteParseConfig {
/// Extract the tagged-PDF logical structure tree. Default `false`.
#[serde(default)]
pub extract_structure_tree: bool,
+ /// Extract raw XFA packets (name + XML content) from XFA form documents
+ /// into `ParseResult.xfa_packets`. Default `false`. Non-XFA documents
+ /// yield an empty list.
+ #[serde(default)]
+ pub extract_xfa_packets: bool,
+ /// Detect solid rectangles and thick lines in rendered page screenshots
+ /// and attach them to each `ScreenshotResult.rects`. Works on the raster,
+ /// so it also finds structure in scanned/flattened pages that have no
+ /// vector paths. Default `false` (adds a full-bitmap scan per page).
+ #[serde(default)]
+ pub detect_screenshot_rects: 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
@@ -176,6 +187,8 @@ impl Default for LiteParseConfig {
extract_annotations: false,
extract_form_fields: false,
extract_structure_tree: false,
+ extract_xfa_packets: false,
+ detect_screenshot_rects: false,
ocr_failure_fatal: true,
ocr_hedge_delays_ms: Vec::new(),
emit_word_boxes: false,
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index 49357e4..db35e4d 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -116,11 +116,14 @@ pub(crate) fn extract_pages_and_images(
if extract_links {
assign_links(&mut text_items, &page.links(&view_box));
}
+ let content_bounds = page
+ .content_bounds()
+ .map(|bounds| rect_from_pdfium(page.bounds_to_viewport(&view_box, &bounds)));
let paths = page.path_objects(&view_box);
let graphics = extract_layout_graphics(&paths);
let vector_graphics = output_options
.extract_vector_graphics
- .then(|| build_vector_graphics(&paths));
+ .then(|| build_vector_graphics(&paths, content_bounds.as_ref()));
assign_strikethrough(&mut text_items, &graphics);
let struct_nodes = extract_page_struct_nodes(&page, &view_box);
let extracted_refs =
@@ -189,6 +192,7 @@ pub(crate) fn extract_pages_and_images(
page_number: page_number as usize,
page_width: page.width(),
page_height: page.height(),
+ content_bounds,
text_items,
graphics,
vector_graphics,
@@ -755,12 +759,13 @@ struct LineCandidate {
shape_index: usize,
}
-fn build_vector_graphics(paths: &[PathObject]) -> VectorGraphics {
+fn build_vector_graphics(paths: &[PathObject], content_bounds: Option<&Rect>) -> VectorGraphics {
let painted: Vec<(usize, &PathObject)> = paths
.iter()
.enumerate()
.filter(|(_, path)| path.is_stroked || path.is_filled)
.collect();
+ let white_fill = compute_white_fill_flags(&painted, content_bounds);
let raw_shapes: Vec<VectorShape> = painted
.iter()
.map(|(_, path)| VectorShape {
@@ -818,6 +823,9 @@ fn build_vector_graphics(paths: &[PathObject]) -> VectorGraphics {
let mut horizontal = Vec::new();
let mut vertical = Vec::new();
for (shape_index, (_, path)) in painted.iter().enumerate() {
+ if white_fill[shape_index] {
+ continue;
+ }
let mut current = None;
for segment in &path.segments {
match segment.kind {
@@ -856,6 +864,64 @@ fn build_vector_graphics(paths: &[PathObject]) -> VectorGraphics {
VectorGraphics { shapes, lines }
}
+/// Port of the LlamaParse extract binary's `PATH_FLAGS_WHITE_FILL` heuristic.
+/// An unstroked solid-white fill is background paint when it is aligned to
+/// the page's content margin, or when it is drawn immediately after — and
+/// overlaps — another white-filled area (pdf writers often paint the
+/// background left-to-right, top-to-bottom as a run of adjacent fills).
+/// Flagged shapes keep their bbox in `shapes` (still useful for chart /
+/// spreadsheet layout detection) but contribute no line segments, which
+/// would otherwise create false positives in outlined-table detection.
+fn compute_white_fill_flags(
+ painted: &[(usize, &PathObject)],
+ content_bounds: Option<&Rect>,
+) -> Vec<bool> {
+ const LINE_DELTA_THRESHOLD: f32 = 1.0;
+ let mut flags = vec![false; painted.len()];
+ let Some(content) = content_bounds else {
+ return flags;
+ };
+ for i in 0..painted.len() {
+ let (path_index, path) = painted[i];
+ if path.is_stroked || !path.is_filled {
+ continue;
+ }
+ let Some(fill) = path.fill_color.as_ref() else {
+ continue;
+ };
+ if fill.r != 0xff || fill.g != 0xff || fill.b != 0xff {
+ continue;
+ }
+ let bounds = &path.bbox;
+ let margin_aligned = (bounds.left - content.x).abs() < LINE_DELTA_THRESHOLD
+ || (bounds.top - content.y).abs() < LINE_DELTA_THRESHOLD
+ || (bounds.right - (content.x + content.width)).abs() < LINE_DELTA_THRESHOLD
+ || (bounds.bottom - (content.y + content.height)).abs() < LINE_DELTA_THRESHOLD;
+ if margin_aligned {
+ flags[i] = true;
+ } else if i > 0 {
+ // Consecutively drawn (adjacent path-object indices; the C
+ // implementation additionally requires the same parent object,
+ // which the flattened path list approximates) and overlapping a
+ // white area extends the blank space.
+ let (prev_index, prev) = painted[i - 1];
+ if flags[i - 1] && path_index == prev_index + 1 && rects_overlap(&prev.bbox, bounds) {
+ flags[i] = true;
+ }
+ }
+ }
+ flags
+}
+
+/// Bbox overlap with the extract binary's `PDF_POINT_EQUAL_THRESHOLD`
+/// slack, in y-down viewport coords (`top <= bottom`).
+fn rects_overlap(a: &pdfium::RectF, b: &pdfium::RectF) -> bool {
+ !(a.left - PATH_EPSILON > b.right
+ || a.right + PATH_EPSILON < b.left
+ || a.top - PATH_EPSILON > b.bottom
+ || a.bottom + PATH_EPSILON < b.top)
+}
+
fn mergeable_shape(s: &VectorShape) -> bool {
s.fill && !s.stroke && s.fill_color.is_some()
}
@@ -2618,6 +2684,7 @@ mod tests {
page_number: 1,
page_width: 100.0,
page_height: 100.0,
+ content_bounds: None,
text_items: items,
graphics: Vec::new(),
vector_graphics: None,
@@ -2867,7 +2934,7 @@ mod tests {
black,
),
];
- let output = build_vector_graphics(&paths);
+ let output = build_vector_graphics(&paths, None);
assert_eq!(output.shapes.len(), 2);
assert!(output.shapes[0].has_curve);
assert_eq!(output.shapes[0].stroke_color.as_deref(), Some("ff000000"));
@@ -2877,6 +2944,135 @@ mod tests {
assert_eq!(output.lines[0].stroke_width, Some(1.0));
}
+ #[test]
+ fn white_fill_on_content_margin_suppresses_lines_but_keeps_shape() {
+ let white = pdfium::Color {
+ r: 255,
+ g: 255,
+ b: 255,
+ a: 255,
+ };
+ // Unstroked solid-white fill whose left edge sits on the content
+ // margin: with content bounds it must contribute no lines; without
+ // content bounds the heuristic is inert and the edges survive.
+ let rect_segments = vec![
+ pdfium::PathSegment {
+ kind: SegmentKind::MoveTo,
+ x: 10.0,
+ y: 10.0,
+ close: false,
+ },
+ pdfium::PathSegment {
+ kind: SegmentKind::LineTo,
+ x: 100.0,
+ y: 10.0,
+ close: false,
+ },
+ pdfium::PathSegment {
+ kind: SegmentKind::LineTo,
+ x: 100.0,
+ y: 50.0,
+ close: false,
+ },
+ pdfium::PathSegment {
+ kind: SegmentKind::LineTo,
+ x: 10.0,
+ y: 50.0,
+ close: false,
+ },
+ ];
+ let paths = vec![vector_path(
+ RectF {
+ left: 10.0,
+ top: 10.0,
+ right: 100.0,
+ bottom: 50.0,
+ },
+ rect_segments,
+ false,
+ true,
+ 0.0,
+ white,
+ )];
+ let content = Rect {
+ x: 10.0,
+ y: 5.0,
+ width: 500.0,
+ height: 700.0,
+ };
+
+ let with_bounds = build_vector_graphics(&paths, Some(&content));
+ assert_eq!(with_bounds.shapes.len(), 1);
+ assert!(with_bounds.lines.is_empty());
+
+ let without_bounds = build_vector_graphics(&paths, None);
+ assert!(!without_bounds.lines.is_empty());
+ }
+
+ #[test]
+ fn white_fill_extends_to_consecutive_overlapping_white_fill() {
+ let white = pdfium::Color {
+ r: 255,
+ g: 255,
+ b: 255,
+ a: 255,
+ };
+ let segments = |x1: f32, x2: f32| {
+ vec![
+ pdfium::PathSegment {
+ kind: SegmentKind::MoveTo,
+ x: x1,
+ y: 10.0,
+ close: false,
+ },
+ pdfium::PathSegment {
+ kind: SegmentKind::LineTo,
+ x: x2,
+ y: 10.0,
+ close: false,
+ },
+ ]
+ };
+ // First fill sits on the left content margin; the second is drawn
+ // immediately after and overlaps it, so the blank area extends.
+ let paths = vec![
+ vector_path(
+ RectF {
+ left: 10.0,
+ top: 10.0,
+ right: 60.0,
+ bottom: 50.0,
+ },
+ segments(10.0, 60.0),
+ false,
+ true,
+ 0.0,
+ white,
+ ),
+ vector_path(
+ RectF {
+ left: 59.0,
+ top: 10.0,
+ right: 120.0,
+ bottom: 50.0,
+ },
+ segments(59.0, 120.0),
+ false,
+ true,
+ 0.0,
+ white,
+ ),
+ ];
+ let content = Rect {
+ x: 10.0,
+ y: 5.0,
+ width: 500.0,
+ height: 700.0,
+ };
+ let output = build_vector_graphics(&paths, Some(&content));
+ assert!(output.lines.is_empty());
+ }
+
#[test]
fn vector_graphics_merges_consecutive_contained_solid_fills() {
let blue = pdfium::Color {
@@ -2913,7 +3109,7 @@ mod tests {
blue,
),
];
- let output = build_vector_graphics(&paths);
+ let output = build_vector_graphics(&paths, None);
assert_eq!(output.shapes.len(), 1);
assert_eq!(output.shapes[0].bbox.width, 20.0);
assert_eq!(output.shapes[0].fill_color.as_deref(), Some("ff0000ff"));
@@ -2947,7 +3143,7 @@ mod tests {
0.0,
pdfium::Color::default(),
);
- let output = build_vector_graphics(&[path]);
+ let output = build_vector_graphics(&[path], None);
assert!(output.shapes.is_empty());
assert!(output.lines.is_empty());
}
diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rs
index 986088b..5b6bdd1 100644
--- a/crates/liteparse/src/main.rs
+++ b/crates/liteparse/src/main.rs
@@ -134,6 +134,9 @@ struct ParseCommand {
/// Include the tagged-PDF logical structure tree.
#[arg(long)]
extract_structure_tree: bool,
+ /// Include raw XFA packets (name + XML content) in JSON output.
+ #[arg(long)]
+ extract_xfa_packets: 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
@@ -258,6 +261,9 @@ struct BatchParseCommand {
/// Include the tagged-PDF logical structure tree.
#[arg(long)]
extract_structure_tree: bool,
+ /// Include raw XFA packets (name + XML content) in JSON output.
+ #[arg(long)]
+ extract_xfa_packets: bool,
}
#[derive(Args, Debug)]
@@ -380,6 +386,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
extract_annotations: cmd.extract_annotations,
extract_form_fields: cmd.extract_form_fields,
extract_structure_tree: cmd.extract_structure_tree,
+ extract_xfa_packets: cmd.extract_xfa_packets,
include_complexity: cmd.complexity,
extract_text_metadata: cmd.extract_text_metadata,
extract_vector_graphics: cmd.extract_vector_graphics,
@@ -396,13 +403,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
lp.parse(&cmd.file).await?
};
let formatted = match lp.config().output_format {
- OutputFormat::Json => json::format_json_result(
- &result.pages,
- &result.images,
- result.image_error_count,
- lp.config().extract_text_metadata,
- result.form_type,
- )?,
+ OutputFormat::Json => {
+ json::format_json_result(&result, lp.config().extract_text_metadata)?
+ }
OutputFormat::Text => text::format_text(&result.pages),
OutputFormat::Markdown => result.text.clone(),
};
@@ -484,6 +487,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
extract_annotations: cmd.extract_annotations,
extract_form_fields: cmd.extract_form_fields,
extract_structure_tree: cmd.extract_structure_tree,
+ extract_xfa_packets: cmd.extract_xfa_packets,
..Default::default()
};
if let Some(n) = cmd.num_workers {
@@ -528,11 +532,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let fmt_result: Result<String, Box<dyn std::error::Error>> =
match lp.config().output_format {
OutputFormat::Json => json::format_json_result(
- &result.pages,
- &result.images,
- result.image_error_count,
+ &result,
lp.config().extract_text_metadata,
- result.form_type,
)
.map_err(|e| e.into()),
OutputFormat::Text => Ok(text::format_text(&result.pages)),
diff --git a/crates/liteparse/src/markdown_layout/test_helpers.rs b/crates/liteparse/src/markdown_layout/test_helpers.rs
index 2d1e4bd..e350f25 100644
--- a/crates/liteparse/src/markdown_layout/test_helpers.rs
+++ b/crates/liteparse/src/markdown_layout/test_helpers.rs
@@ -33,6 +33,7 @@ pub(crate) fn page(lines: Vec<ProjectedLine>) -> ParsedPage {
page_number: 1,
page_width: 612.0,
page_height: 792.0,
+ content_bounds: None,
text: String::new(),
markdown: String::new(),
text_items: vec![],
@@ -188,6 +189,7 @@ pub(crate) fn header_footer_page(n: usize, header: &str, footer: &str, body: &st
page_number: n,
page_width: 612.0,
page_height: 100.0,
+ content_bounds: None,
text: String::new(),
markdown: String::new(),
text_items: vec![],
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index 55137bf..866c640 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -421,6 +421,13 @@ pub(crate) fn render_pages_for_ocr(
grayscale: bool,
) -> Result<Vec<RenderedPage>, LiteParseError> {
let mut rendered = Vec::new();
+ // Draw form-field appearances into the OCR raster so filled-in form
+ // values are visible to the OCR engine (matches the LlamaParse extract
+ // binary's screenshot rendering).
+ let form = document.form_environment();
+ if let Some(form) = form.as_ref() {
+ form.run_document_actions();
+ }
for (idx, page) in pages.iter().enumerate() {
let page_obj = document.page((page.page_number - 1) as i32)?;
let page_complexity = calculate_page_complexity(page, &page_obj)?;
@@ -429,7 +436,7 @@ pub(crate) fn render_pages_for_ocr(
continue;
}
- let bitmap = page_obj.render(dpi)?;
+ let bitmap = page_obj.render_with_form(dpi, form.as_ref())?;
let width = bitmap.width() as u32;
let height = bitmap.height() as u32;
// Grayscale or RGB per the engine; see `OcrEngine::prefers_grayscale`.
@@ -1160,6 +1167,7 @@ mod tests {
page_number,
page_width: 100.0,
page_height: 100.0,
+ content_bounds: None,
text_items: Vec::new(),
graphics: Vec::new(),
vector_graphics: None,
@@ -1189,6 +1197,7 @@ mod tests {
page_number,
page_width: 100.0,
page_height: 100.0,
+ content_bounds: None,
text_items: vec![TextItem {
text: "this page already has real native text content".into(),
x: 0.0,
@@ -1216,6 +1225,7 @@ mod tests {
page_number,
page_width: 100.0,
page_height: 100.0,
+ content_bounds: None,
text_items: vec![TextItem {
text: "small native header that is not enough".into(),
x: 0.0,
diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rs
index c160a30..90f7dd1 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, StructureTree, VectorGraphics,
+ DocumentAnnotation, FormField, ParsedPage, Rect, StructureTree, VectorGraphics, XfaPacket,
};
use serde::Serialize;
@@ -48,6 +48,8 @@ pub(crate) struct JsonPage {
pub page: usize,
pub width: f32,
pub height: f32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content_bounds: Option<Rect>,
pub text: String,
pub text_items: Vec<JsonTextItem>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -71,6 +73,12 @@ pub(crate) struct ParseResultJson {
pub image_error_count: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub form_type: Option<i32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub creator: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub producer: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub xfa_packets: Option<Vec<XfaPacket>>,
}
fn is_zero(value: &u32) -> bool {
@@ -99,12 +107,16 @@ pub(crate) fn build_json(pages: &[ParsedPage], extract_text_metadata: bool) -> P
images: Vec::new(),
image_error_count: 0,
form_type: None,
+ creator: None,
+ producer: None,
+ xfa_packets: None,
pages: pages
.iter()
.map(|page| JsonPage {
page: page.page_number,
width: page.page_width,
height: page.page_height,
+ content_bounds: page.content_bounds.clone(),
text: page.text.clone(),
text_items: page
.text_items
@@ -151,17 +163,16 @@ pub(crate) fn build_json(pages: &[ParsedPage], extract_text_metadata: bool) -> P
}
}
-/// Format complete parse output, including extracted-image metadata. Pixel
+/// Format complete parse output, including extracted-image metadata and
+/// document-level fields (form type, creator/producer, XFA packets). Pixel
/// bytes are written separately by the CLI's `--image-output-dir` option.
pub fn format_json_result(
- pages: &[ParsedPage],
- images: &[ExtractedImage],
- image_error_count: u32,
+ result: &crate::parser::ParseResult,
extract_text_metadata: bool,
- form_type: Option<i32>,
) -> Result<String, serde_json::Error> {
- let mut result = build_json(pages, extract_text_metadata);
- result.images = images
+ let mut json = build_json(&result.pages, extract_text_metadata);
+ json.images = result
+ .images
.iter()
.map(|image| JsonImage {
id: image.id.clone(),
@@ -176,9 +187,12 @@ pub fn format_json_result(
duplicate_of: image.duplicate_of.clone(),
})
.collect();
- result.image_error_count = image_error_count;
- result.form_type = form_type;
- serde_json::to_string_pretty(&result)
+ json.image_error_count = result.image_error_count;
+ json.form_type = result.form_type;
+ json.creator = result.creator.clone();
+ json.producer = result.producer.clone();
+ json.xfa_packets = result.xfa_packets.clone();
+ serde_json::to_string_pretty(&json)
}
/// Format parsed pages as pretty-printed JSON string.
@@ -198,7 +212,7 @@ pub fn format_json_with_text_metadata(
#[cfg(test)]
mod tests {
use super::*;
- use crate::types::{DocumentAnnotation, FormField, ParsedPage, Rect, TextItem};
+ use crate::types::{DocumentAnnotation, ExtractedImage, FormField, ParsedPage, Rect, TextItem};
use crate::types::{StructureAttributeValue, StructureTree, StructureTreeElement};
use std::collections::BTreeMap;
@@ -221,6 +235,7 @@ mod tests {
page_number: 1,
page_width: 612.0,
page_height: 792.0,
+ content_bounds: None,
text: "txt".into(),
markdown: String::new(),
text_items: items,
@@ -376,9 +391,28 @@ mod tests {
duplicate_of: Some("p1_0".into()),
bytes: vec![1, 2, 3],
};
+ let result = crate::parser::ParseResult {
+ pages: vec![],
+ text: String::new(),
+ outline: vec![],
+ images: vec![image],
+ image_error_count: 2,
+ form_type: None,
+ creator: Some("LibreOffice".into()),
+ producer: Some("LibreOffice 7.4".into()),
+ xfa_packets: Some(vec![crate::types::XfaPacket {
+ index: 0,
+ name: Some("datasets".into()),
+ content_length: 11,
+ content: Some("<xml></xml>".into()),
+ }]),
+ };
let value: serde_json::Value =
- serde_json::from_str(&format_json_result(&[], &[image], 2, false, None).unwrap())
- .unwrap();
+ serde_json::from_str(&format_json_result(&result, false).unwrap()).unwrap();
+ assert_eq!(value["creator"], "LibreOffice");
+ assert_eq!(value["producer"], "LibreOffice 7.4");
+ assert_eq!(value["xfa_packets"][0]["name"], "datasets");
+ assert_eq!(value["xfa_packets"][0]["content_length"], 11);
assert_eq!(value["images"][0]["bbox"]["x"], 10.0);
assert_eq!(value["images"][0]["width"], 640);
assert_eq!(value["images"][0]["rotation"], 90.0);
diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rs
index 16ee0f8..e976cec 100644
--- a/crates/liteparse/src/output/markdown.rs
+++ b/crates/liteparse/src/output/markdown.rs
@@ -149,6 +149,7 @@ mod tests {
page_number: n,
page_width: 612.0,
page_height: 792.0,
+ content_bounds: None,
text: "fallback".into(),
markdown: String::new(),
text_items: vec![],
@@ -202,6 +203,7 @@ mod tests {
page_number: 1,
page_width: 0.0,
page_height: 0.0,
+ content_bounds: None,
text: "hello".into(),
markdown: String::new(),
text_items: vec![],
diff --git a/crates/liteparse/src/output/text.rs b/crates/liteparse/src/output/text.rs
index 310cab4..7e98d69 100644
--- a/crates/liteparse/src/output/text.rs
+++ b/crates/liteparse/src/output/text.rs
@@ -18,6 +18,7 @@ mod tests {
page_number: n,
page_width: 0.0,
page_height: 0.0,
+ content_bounds: None,
text: text.into(),
markdown: String::new(),
text_items: vec![],
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index bc30e9a..2a4ff1a 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -13,7 +13,9 @@ use crate::output::markdown;
use crate::projection;
#[cfg(not(target_arch = "wasm32"))]
use crate::render;
-use crate::types::{ExtractedImage, OutlineTarget, Page, ParsedPage, PdfInput};
+use crate::types::{
+ ExtractedImage, OutlineTarget, Page, ParsedPage, PdfInput, ScreenshotRect, XfaPacket,
+};
use pdfium::Library;
/// Result of parsing a document.
@@ -36,6 +38,13 @@ pub struct ParseResult {
/// PDFium form type (0 none, 1 AcroForm, 2 XFA full, 3 XFA foreground),
/// present only when form-field extraction is enabled.
pub form_type: Option<i32>,
+ /// The document's `/Info` `Creator` entry, when present.
+ pub creator: Option<String>,
+ /// The document's `/Info` `Producer` entry, when present.
+ pub producer: Option<String>,
+ /// Raw XFA packets, present only when `extract_xfa_packets` is enabled.
+ /// `Some([])` means extraction ran on a non-XFA document.
+ pub xfa_packets: Option<Vec<XfaPacket>>,
}
/// Result of rendering a single page screenshot.
@@ -45,6 +54,11 @@ pub struct ScreenshotResult {
pub width: u32,
pub height: u32,
pub image_bytes: Vec<u8>,
+ /// True when every pixel has the same color (blank page after render).
+ pub is_solid_fill: bool,
+ /// Solid rectangles/lines detected in the raster (viewport coords).
+ /// Populated only when `LiteParseConfig::detect_screenshot_rects` is on.
+ pub rects: Vec<ScreenshotRect>,
}
/// Env var pointing at a fragmented glyph-outline → unicode font database
@@ -355,7 +369,18 @@ impl LiteParse {
let ocr_grayscale = ocr_engine.as_ref().is_some_and(|e| e.prefers_grayscale());
#[allow(unused_mut)] // mutated only by the native image-output writer
- let (pages, ocr_rendered, outline, mut images, image_error_count, complexity, form_type) = {
+ let (
+ pages,
+ ocr_rendered,
+ outline,
+ mut images,
+ image_error_count,
+ complexity,
+ form_type,
+ creator,
+ producer,
+ xfa_packets,
+ ) = {
let lib = Library::init();
#[cfg(not(target_arch = "wasm32"))]
let repaired_input = self
@@ -378,6 +403,25 @@ impl LiteParse {
.config
.extract_form_fields
.then(|| document.form_type());
+ let creator = document.meta_text("Creator");
+ let producer = document.meta_text("Producer");
+ let xfa_packets = self.config.extract_xfa_packets.then(|| {
+ document
+ .xfa_packets()
+ .into_iter()
+ .map(|packet| XfaPacket {
+ index: packet.index.max(0) as u32,
+ name: packet.name,
+ content_length: packet
+ .content
+ .as_ref()
+ .map_or(0, |content| content.len() as u32),
+ content: packet
+ .content
+ .map(|bytes| String::from_utf8_lossy(&bytes).into_owned()),
+ })
+ .collect::<Vec<_>>()
+ });
let outline = extract::extract_outline(&document);
let (pages, images, image_error_count) = extract::extract_pages_and_images(
&document,
@@ -442,6 +486,9 @@ impl LiteParse {
image_error_count,
complexity,
form_type,
+ creator,
+ producer,
+ xfa_packets,
)
};
let mut pages = pages;
@@ -528,6 +575,9 @@ impl LiteParse {
images,
image_error_count,
form_type,
+ creator,
+ producer,
+ xfa_packets,
})
}
@@ -565,6 +615,9 @@ impl LiteParse {
images: Vec::new(),
image_error_count: 0,
form_type: None,
+ creator: None,
+ producer: None,
+ xfa_packets: None,
}
}
@@ -610,6 +663,7 @@ impl LiteParse {
page_numbers.as_deref(),
self.config.dpi,
self.config.password.as_deref(),
+ self.config.detect_screenshot_rects,
)?;
Ok(rendered
@@ -619,6 +673,8 @@ impl LiteParse {
width: page.width,
height: page.height,
image_bytes: page.png_bytes,
+ is_solid_fill: page.is_solid_fill,
+ rects: page.rects,
})
.collect())
}
@@ -638,6 +694,7 @@ mod tests {
page_number: 1,
page_width: 100.0,
page_height: 100.0,
+ content_bounds: None,
text_items: vec![TextItem {
text: "hello".into(),
width: 20.0,
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index 327da59..6c22e02 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -2894,6 +2894,7 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {
page_number: page.page_number,
page_width: page.page_width,
page_height: page.page_height,
+ content_bounds: page.content_bounds,
text,
markdown: String::new(),
text_items: projected_items
@@ -5004,6 +5005,7 @@ mod tests {
page_number: 1,
page_width: 612.0,
page_height: 792.0,
+ content_bounds: None,
graphics: Vec::new(),
vector_graphics: None,
text_items: Vec::new(),
@@ -5309,6 +5311,7 @@ mod tests {
page_number: 1,
page_width: 612.0,
page_height: 792.0,
+ content_bounds: None,
text_items: Vec::new(),
graphics: Vec::new(),
vector_graphics: None,
@@ -5333,6 +5336,7 @@ mod tests {
page_number: 1,
page_width: 612.0,
page_height: 792.0,
+ content_bounds: None,
text_items: vec![
TextItem {
text: "A".to_string(),
@@ -5383,6 +5387,7 @@ mod tests {
page_number: 1,
page_width: 612.0,
page_height: 792.0,
+ content_bounds: None,
text_items: vec![
TextItem {
text: "A".to_string(),
@@ -5441,6 +5446,7 @@ mod tests {
page_number: 1,
page_width: 612.0,
page_height: 792.0,
+ content_bounds: None,
text_items: vec![
TextItem {
text: "ab".to_string(),
diff --git a/crates/liteparse/src/render.rs b/crates/liteparse/src/render.rs
index b33680b..36df4a7 100644
--- a/crates/liteparse/src/render.rs
+++ b/crates/liteparse/src/render.rs
@@ -1,20 +1,30 @@
use crate::error::LiteParseError;
use crate::extract::{encode_png, load_document_from_input};
-use crate::types::PdfInput;
+use crate::types::{PdfInput, ScreenshotRect};
use pdfium::Library;
use serde::Serialize;
-/// A single rendered page as PNG bytes.
+/// A single rendered page as PNG bytes, plus raster-derived signals.
#[derive(Debug, Clone)]
pub struct RenderedPage {
pub page_num: u32,
pub width: u32,
pub height: u32,
pub png_bytes: Vec<u8>,
+ /// True when every pixel has the same color (blank page after render).
+ pub is_solid_fill: bool,
+ /// Solid rectangles/lines detected in the raster (viewport coords).
+ /// Empty unless rect detection was requested — and always empty for
+ /// solid-fill pages, where detection is skipped.
+ pub rects: Vec<ScreenshotRect>,
}
/// Render selected pages from a PDF input to PNG bytes.
///
+/// Form-field appearances (filled values, checkbox states) are drawn on top
+/// of the page raster when the document has a form. With `detect_rects`,
+/// each page's raster is also scanned for solid rectangles and lines.
+///
/// Acquires the process-global PDFium lock for the entire render. The lock
/// is held until this function returns — PNG encoding happens inside the
/// critical section, which is fine because it is pure CPU work with no
@@ -24,16 +34,18 @@ pub fn render_pages_to_png(
page_numbers: Option<&[u32]>,
dpi: f32,
password: Option<&str>,
+ detect_rects: bool,
) -> Result<Vec<RenderedPage>, LiteParseError> {
let lib = Library::init();
let document = load_document_from_input(&lib, input, password)?;
- render_document_pages(&document, page_numbers, dpi)
+ render_document_pages(&document, page_numbers, dpi, detect_rects)
}
fn render_document_pages(
document: &pdfium::Document,
page_numbers: Option<&[u32]>,
dpi: f32,
+ detect_rects: bool,
) -> Result<Vec<RenderedPage>, LiteParseError> {
let page_count = document.page_count() as u32;
let pages: Vec<u32> = match page_numbers {
@@ -41,6 +53,11 @@ fn render_document_pages(
None => (1..=page_count).collect(),
};
+ let form = document.form_environment();
+ if let Some(form) = form.as_ref() {
+ form.run_document_actions();
+ }
+
let mut results = Vec::with_capacity(pages.len());
for page_num in pages {
if page_num < 1 || page_num > page_count {
@@ -50,10 +67,26 @@ fn render_document_pages(
}
let page = document.page((page_num - 1) as i32)?;
- let bitmap = page.render(dpi)?;
+ let bitmap = page.render_with_form(dpi, form.as_ref())?;
let width = bitmap.width() as u32;
let height = bitmap.height() as u32;
let rgba = bitmap.to_rgba();
+
+ let is_solid_fill = is_solid_fill_rgba(&rgba, width as usize, height as usize);
+ // A solid-fill page has no structure to find; skip the scan (this is
+ // also the extract binary's cheap blank-page short-circuit).
+ let rects = if detect_rects && !is_solid_fill {
+ find_solid_rects_rgba(
+ &rgba,
+ width as usize,
+ height as usize,
+ page.width(),
+ page.height(),
+ )
+ } else {
+ Vec::new()
+ };
+
let png_bytes = encode_png(&rgba, width, height)?;
results.push(RenderedPage {
@@ -61,12 +94,139 @@ fn render_document_pages(
width,
height,
png_bytes,
+ is_solid_fill,
+ rects,
});
}
Ok(results)
}
+/// Minimum rect dimension as a fraction of page height: 0.5%. Small renders
+/// (<400px tall) fall back to a 2px floor.
+const FIND_RECTS_MIN_DIMENSION_DENOM: usize = 200;
+
+#[inline]
+fn rgb_at(rgba: &[u8], pixel_index: usize) -> u32 {
+ let base = pixel_index * 4;
+ ((rgba[base] as u32) << 16) | ((rgba[base + 1] as u32) << 8) | (rgba[base + 2] as u32)
+}
+
+/// True when every pixel matches the first pixel's RGB (alpha ignored — the
+/// render always starts from an opaque white fill).
+pub(crate) fn is_solid_fill_rgba(rgba: &[u8], width: usize, height: usize) -> bool {
+ if width == 0 || height == 0 || rgba.len() < width * height * 4 {
+ return false;
+ }
+ let first = rgb_at(rgba, 0);
+ (1..width * height).all(|i| rgb_at(rgba, i) == first)
+}
+
+/// Find solid same-color rectangles and lines in a rendered page bitmap.
+/// Port of the LlamaParse extract binary's `ParseImage_findSolidRects`
+/// (rectangles + lines modes; whitespace mode is not ported, so white areas
+/// are skipped). Returned coordinates are scaled from pixels to the page's
+/// viewport space (`page_width`/`page_height` in PDF points).
+pub(crate) fn find_solid_rects_rgba(
+ rgba: &[u8],
+ width: usize,
+ height: usize,
+ page_width: f32,
+ page_height: f32,
+) -> Vec<ScreenshotRect> {
+ let mut out = Vec::new();
+ if width == 0 || height == 0 || rgba.len() < width * height * 4 {
+ return out;
+ }
+
+ let mut visited = vec![false; width * height];
+ // For small renders (<200px edge) count a rectangle as at least 2x2
+ // pixels, a line as 1x2.
+ let min_dimension = (height / FIND_RECTS_MIN_DIMENSION_DENOM).max(2);
+
+ for y in 0..height {
+ for x in 0..width {
+ if visited[y * width + x] {
+ continue;
+ }
+ let color = rgb_at(rgba, y * width + x);
+ visited[y * width + x] = true;
+
+ // White pixels are page background, not content.
+ if color == 0xffffff {
+ continue;
+ }
+
+ let mut min_dimension_matches = 0;
+ if x + min_dimension - 1 < width
+ && rgb_at(rgba, y * width + x + min_dimension - 1) == color
+ {
+ min_dimension_matches += 1;
+ }
+ if y + min_dimension - 1 < height
+ && rgb_at(rgba, (y + min_dimension - 1) * width + x) == color
+ {
+ min_dimension_matches += 1;
+ }
+ if min_dimension_matches < 1 {
+ continue;
+ }
+
+ // Grow the same-color region down and right; the rect width is
+ // the narrowest row so partial rows don't inflate it.
+ let mut rect_width: Option<usize> = None;
+ let mut yy = y;
+ while yy < height {
+ if yy != y && (visited[yy * width + x] || rgb_at(rgba, yy * width + x) != color) {
+ break;
+ }
+ let mut xx = x + 1;
+ while xx < width
+ && !visited[yy * width + xx]
+ && rgb_at(rgba, yy * width + xx) == color
+ {
+ xx += 1;
+ }
+ let row_width = xx - x;
+ rect_width = Some(rect_width.map_or(row_width, |w| w.min(row_width)));
+ yy += 1;
+ }
+ let rect_height = yy - y;
+ let rect_width = rect_width.unwrap_or(0);
+
+ for vy in y..y + rect_height {
+ for vx in x..x + rect_width {
+ visited[vy * width + vx] = true;
+ }
+ }
+
+ let (found, is_line) = if min_dimension_matches == 1 {
+ (
+ rect_height >= min_dimension || rect_width >= min_dimension,
+ true,
+ )
+ } else {
+ (
+ rect_height >= min_dimension && rect_width >= min_dimension,
+ false,
+ )
+ };
+ if found {
+ out.push(ScreenshotRect {
+ x: x as f32 / width as f32 * page_width,
+ y: y as f32 / height as f32 * page_height,
+ width: rect_width as f32 / width as f32 * page_width,
+ height: rect_height as f32 / height as f32 * page_height,
+ color: format!("ff{:06x}", color),
+ is_line,
+ });
+ }
+ }
+ }
+
+ out
+}
+
/// Render a single page to a PNG file.
pub fn screenshot(
pdf_path: &str,
@@ -76,7 +236,7 @@ pub fn screenshot(
password: Option<&str>,
) -> Result<(), LiteParseError> {
let input = PdfInput::Path(pdf_path.to_string());
- let pages = render_pages_to_png(&input, Some(&[page_num]), dpi, password)?;
+ let pages = render_pages_to_png(&input, Some(&[page_num]), dpi, password, false)?;
let page = pages
.into_iter()
.next()
@@ -170,4 +330,82 @@ mod tests {
let r = image_bounds("/nonexistent/path/does_not_exist.pdf", None);
assert!(r.is_err());
}
+
+ /// Build an RGBA buffer from rows of 24-bit RGB pixel values.
+ fn rgba_from_rows(rows: &[&[u32]]) -> (Vec<u8>, usize, usize) {
+ let height = rows.len();
+ let width = rows[0].len();
+ let mut buf = Vec::with_capacity(width * height * 4);
+ for row in rows {
+ for &px in *row {
+ buf.push((px >> 16) as u8);
+ buf.push((px >> 8) as u8);
+ buf.push(px as u8);
+ buf.push(0xff);
+ }
+ }
+ (buf, width, height)
+ }
+
+ #[test]
+ fn solid_fill_detects_uniform_and_rejects_mixed() {
+ let uniform_rows = [[0xffffffu32; 4]; 4];
+ let uniform_refs: Vec<&[u32]> = uniform_rows.iter().map(|r| &r[..]).collect();
+ let (uniform, w, h) = rgba_from_rows(&uniform_refs);
+ assert!(is_solid_fill_rgba(&uniform, w, h));
+
+ let mut rows = [[0x336699u32; 4]; 4];
+ rows[3][3] = 0x336698;
+ let row_refs: Vec<&[u32]> = rows.iter().map(|r| &r[..]).collect();
+ let (mixed, w, h) = rgba_from_rows(&row_refs);
+ assert!(!is_solid_fill_rgba(&mixed, w, h));
+ }
+
+ #[test]
+ fn find_solid_rects_finds_colored_block_and_skips_white() {
+ // 8x8 white page with a 4x4 colored block at (2,2). min_dimension
+ // floors at 2, so the block qualifies as a rectangle.
+ const W: u32 = 0xffffff;
+ const C: u32 = 0x112233;
+ let mut rows = [[W; 8]; 8];
+ for row in rows.iter_mut().skip(2).take(4) {
+ for px in row.iter_mut().skip(2).take(4) {
+ *px = C;
+ }
+ }
+ let row_refs: Vec<&[u32]> = rows.iter().map(|r| &r[..]).collect();
+ let (buf, w, h) = rgba_from_rows(&row_refs);
+
+ // Page is 80x80pt, so pixel coords scale 10x.
+ let rects = find_solid_rects_rgba(&buf, w, h, 80.0, 80.0);
+ assert_eq!(rects.len(), 1);
+ let rect = &rects[0];
+ assert_eq!(rect.x, 20.0);
+ assert_eq!(rect.y, 20.0);
+ assert_eq!(rect.width, 40.0);
+ assert_eq!(rect.height, 40.0);
+ assert_eq!(rect.color, "ff112233");
+ assert!(!rect.is_line);
+ }
+
+ #[test]
+ fn find_solid_rects_flags_thin_line_as_line() {
+ // 8x8 white page with a 1px-tall, 6px-wide dark line: only the
+ // horizontal min-dimension probe matches, so it is a line.
+ const W: u32 = 0xffffff;
+ const C: u32 = 0x000000;
+ let mut rows = [[W; 8]; 8];
+ for px in rows[4].iter_mut().skip(1).take(6) {
+ *px = C;
+ }
+ let row_refs: Vec<&[u32]> = rows.iter().map(|r| &r[..]).collect();
+ let (buf, w, h) = rgba_from_rows(&row_refs);
+
+ let rects = find_solid_rects_rgba(&buf, w, h, 8.0, 8.0);
+ assert_eq!(rects.len(), 1);
+ assert!(rects[0].is_line);
+ assert_eq!(rects[0].color, "ff000000");
+ assert_eq!(rects[0].width, 6.0);
+ assert_eq!(rects[0].height, 1.0);
+ }
}
diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rs
index 86b5570..beb8496 100644
--- a/crates/liteparse/src/types.rs
+++ b/crates/liteparse/src/types.rs
@@ -105,6 +105,10 @@ pub struct Page {
pub page_number: usize,
pub page_width: f32,
pub page_height: f32,
+ /// Union bbox of the page's top-level content objects in viewport
+ /// coords (visible content extent). `None` for empty pages.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content_bounds: Option<Rect>,
pub text_items: Vec<TextItem>,
/// Vector graphics on the page, distilled from PDFium path objects.
/// Not emitted in JSON/text outputs — consumed by the markdown layout pass.
@@ -226,6 +230,40 @@ pub struct FormField {
pub selected_options: Vec<String>,
}
+/// One raw packet from an XFA form document's `/XFA` array. Surfaced on
+/// `ParseResult.xfa_packets` when `extract_xfa_packets` is enabled.
+#[derive(Debug, Clone, Serialize)]
+pub struct XfaPacket {
+ /// Zero-based index in the XFA array.
+ pub index: u32,
+ /// Packet name (e.g. `template`, `datasets`), when present.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ /// Decoded content length in bytes.
+ pub content_length: u32,
+ /// Packet content (usually XML), lossily decoded as UTF-8. `None` when
+ /// the packet stream could not be read.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content: Option<String>,
+}
+
+/// One solid rectangle (or thick line) detected in a rendered page bitmap.
+/// Coordinates are in the same top-left, 72-DPI viewport space as text
+/// items. Detection runs on the raster, so it also covers scanned/flattened
+/// pages that carry no vector paths.
+#[derive(Debug, Clone, Serialize)]
+pub struct ScreenshotRect {
+ pub x: f32,
+ pub y: f32,
+ pub width: f32,
+ pub height: f32,
+ /// Fill color as ARGB hex string (e.g. "ff1a2b3c").
+ pub color: String,
+ /// True when only one dimension reaches the minimum rectangle size —
+ /// a solid line rather than a filled area.
+ pub is_line: bool,
+}
+
/// One entry in the document outline (bookmarks). Coordinates are in PDF
/// user space (origin bottom-left) — convert to viewport with
/// `page_height - y` once you know the page.
@@ -261,6 +299,10 @@ pub struct ParsedPage {
pub page_number: usize,
pub page_width: f32,
pub page_height: f32,
+ /// Union bbox of the page's top-level content objects in viewport
+ /// coords (visible content extent). `None` for empty pages.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content_bounds: Option<Rect>,
pub text: String,
#[serde(skip_serializing_if = "String::is_empty")]
pub markdown: String,
@@ -614,6 +656,7 @@ mod tests {
page_number: 1,
page_width: 100.0,
page_height: 200.0,
+ content_bounds: None,
text_items: vec![sample_item()],
graphics: vec![],
vector_graphics: None,
diff --git a/crates/pdfium-sys/bindings.rs b/crates/pdfium-sys/bindings.rs
index 8ff4e3e..27a0477 100644
--- a/crates/pdfium-sys/bindings.rs
+++ b/crates/pdfium-sys/bindings.rs
@@ -2970,3 +2970,22 @@ unsafe extern "C" {
unsafe extern "C" {
pub fn FPDFPage_InsertClipPath(page: FPDF_PAGE, clipPath: FPDF_CLIPPATH);
}
+unsafe extern "C" {
+ pub fn FORM_OnAfterLoadPage(page: FPDF_PAGE, hHandle: FPDF_FORMHANDLE);
+}
+unsafe extern "C" {
+ pub fn FORM_OnBeforeClosePage(page: FPDF_PAGE, hHandle: FPDF_FORMHANDLE);
+}
+unsafe extern "C" {
+ pub fn FORM_DoDocumentJSAction(hHandle: FPDF_FORMHANDLE);
+}
+unsafe extern "C" {
+ pub fn FORM_DoDocumentOpenAction(hHandle: FPDF_FORMHANDLE);
+}
+unsafe extern "C" {
+ pub fn FORM_DoPageAAction(
+ page: FPDF_PAGE,
+ hHandle: FPDF_FORMHANDLE,
+ aaType: ::std::os::raw::c_int,
+ );
+}
diff --git a/crates/pdfium-sys/build.rs b/crates/pdfium-sys/build.rs
index 69f1ed1..7cfdbb4 100644
--- a/crates/pdfium-sys/build.rs
+++ b/crates/pdfium-sys/build.rs
@@ -269,6 +269,7 @@ fn run_bindgen(include_dir: &Path) {
.header("wrapper.h")
.clang_arg(format!("-I{}", include_dir.display()))
.allowlist_function("FPDF.*")
+ .allowlist_function("FORM_.*")
.allowlist_function("FPDFText_.*")
.allowlist_function("FPDFPage.*")
.allowlist_function("FPDFLink_.*")
diff --git a/crates/pdfium-sys/src/dynamic.rs b/crates/pdfium-sys/src/dynamic.rs
index df2b647..b1fb7bb 100644
--- a/crates/pdfium-sys/src/dynamic.rs
+++ b/crates/pdfium-sys/src/dynamic.rs
@@ -45,6 +45,42 @@ pub struct PdfiumBindings {
pub FPDFDOC_InitFormFillEnvironment:
unsafe extern "C" fn(FPDF_DOCUMENT, *mut FPDF_FORMFILLINFO) -> FPDF_FORMHANDLE,
pub FPDFDOC_ExitFormFillEnvironment: unsafe extern "C" fn(FPDF_FORMHANDLE),
+ pub FORM_OnAfterLoadPage: unsafe extern "C" fn(FPDF_PAGE, FPDF_FORMHANDLE),
+ pub FORM_OnBeforeClosePage: unsafe extern "C" fn(FPDF_PAGE, FPDF_FORMHANDLE),
+ pub FORM_DoDocumentJSAction: unsafe extern "C" fn(FPDF_FORMHANDLE),
+ pub FORM_DoDocumentOpenAction: unsafe extern "C" fn(FPDF_FORMHANDLE),
+ pub FORM_DoPageAAction: unsafe extern "C" fn(FPDF_PAGE, FPDF_FORMHANDLE, std::os::raw::c_int),
+ pub FPDF_FFLDraw: unsafe extern "C" fn(
+ FPDF_FORMHANDLE,
+ FPDF_BITMAP,
+ FPDF_PAGE,
+ std::os::raw::c_int,
+ std::os::raw::c_int,
+ std::os::raw::c_int,
+ std::os::raw::c_int,
+ std::os::raw::c_int,
+ std::os::raw::c_int,
+ ),
+ pub FPDF_GetMetaText: unsafe extern "C" fn(
+ FPDF_DOCUMENT,
+ FPDF_BYTESTRING,
+ *mut std::os::raw::c_void,
+ std::os::raw::c_ulong,
+ ) -> std::os::raw::c_ulong,
+ pub FPDF_GetXFAPacketCount: unsafe extern "C" fn(FPDF_DOCUMENT) -> std::os::raw::c_int,
+ pub FPDF_GetXFAPacketName: unsafe extern "C" fn(
+ FPDF_DOCUMENT,
+ std::os::raw::c_int,
+ *mut std::os::raw::c_void,
+ std::os::raw::c_ulong,
+ ) -> std::os::raw::c_ulong,
+ pub FPDF_GetXFAPacketContent: unsafe extern "C" fn(
+ FPDF_DOCUMENT,
+ std::os::raw::c_int,
+ *mut std::os::raw::c_void,
+ std::os::raw::c_ulong,
+ *mut std::os::raw::c_ulong,
+ ) -> FPDF_BOOL,
// -- Page --
pub FPDF_LoadPage: unsafe extern "C" fn(FPDF_DOCUMENT, std::os::raw::c_int) -> FPDF_PAGE,
@@ -481,6 +517,16 @@ impl PdfiumBindings {
FPDF_GetFormType: load_fn!(lib, "FPDF_GetFormType"),
FPDFDOC_InitFormFillEnvironment: load_fn!(lib, "FPDFDOC_InitFormFillEnvironment"),
FPDFDOC_ExitFormFillEnvironment: load_fn!(lib, "FPDFDOC_ExitFormFillEnvironment"),
+ FORM_OnAfterLoadPage: load_fn!(lib, "FORM_OnAfterLoadPage"),
+ FORM_OnBeforeClosePage: load_fn!(lib, "FORM_OnBeforeClosePage"),
+ FORM_DoDocumentJSAction: load_fn!(lib, "FORM_DoDocumentJSAction"),
+ FORM_DoDocumentOpenAction: load_fn!(lib, "FORM_DoDocumentOpenAction"),
+ FORM_DoPageAAction: load_fn!(lib, "FORM_DoPageAAction"),
+ FPDF_FFLDraw: load_fn!(lib, "FPDF_FFLDraw"),
+ FPDF_GetMetaText: load_fn!(lib, "FPDF_GetMetaText"),
+ FPDF_GetXFAPacketCount: load_fn!(lib, "FPDF_GetXFAPacketCount"),
+ FPDF_GetXFAPacketName: load_fn!(lib, "FPDF_GetXFAPacketName"),
+ FPDF_GetXFAPacketContent: load_fn!(lib, "FPDF_GetXFAPacketContent"),
FPDF_LoadPage: load_fn!(lib, "FPDF_LoadPage"),
FPDF_ClosePage: load_fn!(lib, "FPDF_ClosePage"),
FPDF_GetPageWidthF: load_fn!(lib, "FPDF_GetPageWidthF"),
diff --git a/crates/pdfium/src/document.rs b/crates/pdfium/src/document.rs
index bcd9538..7e7f18e 100644
--- a/crates/pdfium/src/document.rs
+++ b/crates/pdfium/src/document.rs
@@ -39,6 +39,17 @@ pub struct OutlineEntry {
pub y: Option<f32>,
}
+/// One raw packet from an XFA form document's `/XFA` array.
+#[derive(Debug, Clone)]
+pub struct XfaPacket {
+ /// Zero-based index in the XFA array.
+ pub index: i32,
+ /// Packet name (e.g. `template`, `datasets`), when present.
+ pub name: Option<String>,
+ /// Raw packet bytes (usually XML), when readable.
+ pub content: Option<Vec<u8>>,
+}
+
impl<'lib> Document<'lib> {
pub fn page_count(&self) -> i32 {
unsafe { ffi!(FPDF_GetPageCount(self.handle)) }
@@ -81,6 +92,132 @@ impl<'lib> Document<'lib> {
})
}
+ /// Read one entry from the document's `/Info` metadata dictionary
+ /// (e.g. `"Creator"`, `"Producer"`, `"Title"`). Returns `None` when the
+ /// tag is absent or empty.
+ pub fn meta_text(&self, tag: &str) -> Option<String> {
+ let tag_c = std::ffi::CString::new(tag).ok()?;
+ let needed = unsafe {
+ ffi!(FPDF_GetMetaText(
+ self.handle,
+ tag_c.as_ptr(),
+ std::ptr::null_mut(),
+ 0
+ ))
+ } as usize;
+ if needed < 2 {
+ return None;
+ }
+ // `needed` is byte length of the UTF-16 value including a trailing NUL.
+ let mut buf: Vec<u16> = vec![0; needed / 2];
+ let written = unsafe {
+ ffi!(FPDF_GetMetaText(
+ self.handle,
+ tag_c.as_ptr(),
+ buf.as_mut_ptr() as *mut std::os::raw::c_void,
+ needed as std::os::raw::c_ulong,
+ ))
+ } as usize;
+ if written < 2 {
+ return None;
+ }
+ let chars = written / 2;
+ let end = if buf.get(chars - 1) == Some(&0) {
+ chars - 1
+ } else {
+ chars
+ };
+ if end == 0 {
+ return None;
+ }
+ Some(String::from_utf16_lossy(&buf[..end]))
+ }
+
+ /// Number of packets in the document's `/XFA` array (0 for non-XFA docs).
+ pub fn xfa_packet_count(&self) -> i32 {
+ unsafe { ffi!(FPDF_GetXFAPacketCount(self.handle)) }
+ }
+
+ /// Read every packet from the document's `/XFA` array. Empty for
+ /// non-XFA documents. Individual name/content read failures surface as
+ /// `None` fields rather than dropping the packet.
+ pub fn xfa_packets(&self) -> Vec<XfaPacket> {
+ let count = self.xfa_packet_count();
+ if count <= 0 {
+ return Vec::new();
+ }
+ let mut out = Vec::with_capacity(count as usize);
+ for index in 0..count {
+ let name_len = unsafe {
+ ffi!(FPDF_GetXFAPacketName(
+ self.handle,
+ index,
+ std::ptr::null_mut(),
+ 0
+ ))
+ } as usize;
+ let name = (name_len > 0)
+ .then(|| {
+ let mut buf = vec![0u8; name_len];
+ let written = unsafe {
+ ffi!(FPDF_GetXFAPacketName(
+ self.handle,
+ index,
+ buf.as_mut_ptr() as *mut std::os::raw::c_void,
+ name_len as std::os::raw::c_ulong,
+ ))
+ } as usize;
+ if written == 0 {
+ return None;
+ }
+ buf.truncate(written.min(name_len));
+ while buf.last() == Some(&0) {
+ buf.pop();
+ }
+ Some(String::from_utf8_lossy(&buf).into_owned())
+ })
+ .flatten();
+
+ let mut content_len: std::os::raw::c_ulong = 0;
+ let sized = unsafe {
+ ffi!(FPDF_GetXFAPacketContent(
+ self.handle,
+ index,
+ std::ptr::null_mut(),
+ 0,
+ &mut content_len,
+ ))
+ };
+ let content = (sized != 0 && content_len > 0)
+ .then(|| {
+ let mut buf = vec![0u8; content_len as usize];
+ let mut written: std::os::raw::c_ulong = 0;
+ let ok = unsafe {
+ ffi!(FPDF_GetXFAPacketContent(
+ self.handle,
+ index,
+ buf.as_mut_ptr() as *mut std::os::raw::c_void,
+ content_len,
+ &mut written,
+ ))
+ };
+ if ok == 0 {
+ return None;
+ }
+ buf.truncate((written as usize).min(buf.len()));
+ Some(buf)
+ })
+ .flatten();
+
+ out.push(XfaPacket {
+ index,
+ name,
+ content,
+ });
+ }
+ out
+ }
+
/// Walk the document outline (bookmarks). Returns entries in pre-order
/// (depth-first), so parents precede their children. Empty when the
/// document has no outline.
@@ -125,6 +262,17 @@ impl<'lib> Document<'lib> {
}
}
+impl FormEnvironment<'_, '_> {
+ /// Execute document-level JavaScript and open actions. Some AcroForms
+ /// only compute field values/appearances in these actions, so run this
+ /// once after init when the environment is used for rendering. Mirrors
+ /// the LlamaParse extract binary's document setup.
+ pub fn run_document_actions(&self) {
+ unsafe { ffi!(FORM_DoDocumentJSAction(self.handle)) };
+ unsafe { ffi!(FORM_DoDocumentOpenAction(self.handle)) };
+ }
+}
+
impl Drop for FormEnvironment<'_, '_> {
fn drop(&mut self) {
unsafe { ffi!(FPDFDOC_ExitFormFillEnvironment(self.handle)) };
diff --git a/crates/pdfium/src/lib.rs b/crates/pdfium/src/lib.rs
index 8e813d4..48f607d 100644
--- a/crates/pdfium/src/lib.rs
+++ b/crates/pdfium/src/lib.rs
@@ -9,7 +9,7 @@ mod text_page;
mod types;
pub use bitmap::Bitmap;
-pub use document::{Document, FormEnvironment, OutlineEntry};
+pub use document::{Document, FormEnvironment, OutlineEntry, XfaPacket};
pub use error::PdfiumError;
pub use font::{Font, FontType};
pub use library::Library;
diff --git a/crates/pdfium/src/page.rs b/crates/pdfium/src/page.rs
index 57af9bc..46a1058 100644
--- a/crates/pdfium/src/page.rs
+++ b/crates/pdfium/src/page.rs
@@ -327,6 +327,49 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
/// Render the page to a BGRA bitmap at the given DPI.
pub fn render(&self, dpi: f32) -> Result<Bitmap<'lib>, PdfiumError> {
+ self.render_with_form(dpi, None)
+ }
+
+ /// Render the page to a BGRA bitmap, drawing form-field appearances
+ /// (filled values, checkbox states) on top via `FPDF_FFLDraw` when a form
+ /// environment is supplied. Without it, PDFium only paints widget
+ /// annotations' static appearance streams, so filled-in form data can be
+ /// missing from the raster. The page open/close form notifications are
+ /// wrapped around the render, mirroring the LlamaParse extract binary.
+ pub fn render_with_form(
+ &self,
+ dpi: f32,
+ form: Option<&FormEnvironment>,
+ ) -> Result<Bitmap<'lib>, PdfiumError> {
+ if let Some(form) = form {
+ unsafe {
+ ffi!(FORM_OnAfterLoadPage(self.handle, form.handle));
+ ffi!(FORM_DoPageAAction(
+ self.handle,
+ form.handle,
+ pdfium_sys::FPDFPAGE_AACTION_OPEN as i32,
+ ));
+ }
+ }
+ let result = self.render_bitmap(dpi, form);
+ if let Some(form) = form {
+ unsafe {
+ ffi!(FORM_DoPageAAction(
+ self.handle,
+ form.handle,
+ pdfium_sys::FPDFPAGE_AACTION_CLOSE as i32,
+ ));
+ ffi!(FORM_OnBeforeClosePage(self.handle, form.handle));
+ }
+ }
+ result
+ }
+
+ fn render_bitmap(
+ &self,
+ dpi: f32,
+ form: Option<&FormEnvironment>,
+ ) -> Result<Bitmap<'lib>, PdfiumError> {
let scale = dpi / 72.0;
let width = (self.width() * scale).round() as i32;
let height = (self.height() * scale).round() as i32;
@@ -354,9 +397,72 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
));
}
+ if let Some(form) = form {
+ // NOTE: like the LlamaParse extract binary, popup annotations are
+ // not drawn (flags 0 for the form layer draw).
+ unsafe {
+ ffi!(FPDF_FFLDraw(
+ form.handle,
+ bitmap.handle(),
+ self.handle,
+ 0,
+ 0,
+ width,
+ height,
+ 0,
+ 0,
+ ));
+ }
+ }
+
Ok(bitmap)
}
+ /// Union of all top-level page object bounds, in PDF page space.
+ /// `None` when the page has no content objects. Mirrors the LlamaParse
+ /// extract binary's `Parse_getContentBounds`.
+ pub fn content_bounds(&self) -> Option<RectF> {
+ let count = unsafe { ffi!(FPDFPage_CountObjects(self.handle)) };
+ let mut bounds: Option<RectF> = None;
+ for i in 0..count {
+ let obj = unsafe { ffi!(FPDFPage_GetObject(self.handle, i)) };
+ if obj.is_null() {
+ continue;
+ }
+ let mut left: f32 = 0.0;
+ let mut bottom: f32 = 0.0;
+ let mut right: f32 = 0.0;
+ let mut top: f32 = 0.0;
+ let ok = unsafe {
+ ffi!(FPDFPageObj_GetBounds(
+ obj,
+ &mut left,
+ &mut bottom,
+ &mut right,
+ &mut top
+ ))
+ };
+ if ok == 0 {
+ continue;
+ }
+ bounds = Some(match bounds {
+ None => RectF {
+ left,
+ top,
+ right,
+ bottom,
+ },
+ Some(prev) => RectF {
+ left: prev.left.min(left),
+ top: prev.top.max(top),
+ right: prev.right.max(right),
+ bottom: prev.bottom.min(bottom),
+ },
+ });
+ }
+ bounds
+ }
+
/// Extract bounding boxes of embedded image objects on this page.
/// Returns coordinates in viewport space (Y-down, top-left origin) in PDF points.
/// Filters out images smaller than `min_size_pt` and images covering more than
diff --git a/packages/node/README.md b/packages/node/README.md
index 63ff173..6d8eb8a 100644
--- a/packages/node/README.md
+++ b/packages/node/README.md
@@ -65,6 +65,8 @@ const parser = new LiteParse({
extractAnnotations: false, // Include page annotations in structured output
extractFormFields: false, // Include AcroForm widget fields and values
extractStructureTree: false, // Include tagged-PDF logical structure
+ extractXfaPackets: false, // Include raw XFA packets (name + XML content)
+ detectScreenshotRects: false, // Detect solid rects/lines in screenshots
preserveVerySmallText: false, // Keep tiny text
extractTextMetadata: false, // Opt in to MCID, font metrics, colors, char codes, and trailingSpaceGenerated
password: undefined, // Password for protected documents
@@ -96,6 +98,14 @@ 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.
+Every result also carries the document's `/Info` `creator`/`producer` when
+present, and each page a `contentBounds` union bbox of its top-level content
+objects. With `extractXfaPackets`, `result.xfaPackets` lists each raw XFA
+packet (index, name, content length, XML content); non-XFA documents yield an
+empty array. Screenshots draw form-field appearances into the raster and
+report `isSolidFill` per page, plus detected solid `rects` when
+`detectScreenshotRects` is enabled.
+
## 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 7f435d5..bf935ed 100644
--- a/packages/node/native.d.ts
+++ b/packages/node/native.d.ts
@@ -57,6 +57,16 @@ export interface JsLiteParseConfig {
extractFormFields?: boolean
/** Extract the tagged-PDF logical structure tree. */
extractStructureTree?: boolean
+ /**
+ * Extract raw XFA packets (name + XML content) into
+ * `ParseResult.xfaPackets`. Default false.
+ */
+ extractXfaPackets?: boolean
+ /**
+ * Detect solid rectangles/lines in rendered page screenshots and attach
+ * them to each screenshot result. Default false.
+ */
+ detectScreenshotRects?: boolean
/**
* Whether a systemic OCR failure aborts the whole parse (default true).
* Set false to keep already-recovered native text and return partial
@@ -194,6 +204,11 @@ export interface JsParsedPage {
pageNum: number
width: number
height: number
+ /**
+ * Union bbox of the page's top-level content objects in viewport
+ * coords (visible content extent). Absent for empty pages.
+ */
+ contentBounds?: JsRect
text: string
markdown: string
textItems: Array<JsTextItem>
@@ -293,6 +308,20 @@ export interface JsParseResult {
images: Array<JsExtractedImage>
imageErrorCount: number
formType?: number
+ /** The document's `/Info` `Creator` entry, when present. */
+ creator?: string
+ /** The document's `/Info` `Producer` entry, when present. */
+ producer?: string
+ /** Raw XFA packets; present only when `extractXfaPackets` is enabled. */
+ xfaPackets?: Array<JsXfaPacket>
+}
+/** One raw packet from an XFA form document's `/XFA` array. */
+export interface JsXfaPacket {
+ index: number
+ name?: string
+ contentLength: number
+ /** Packet content (usually XML), lossily decoded as UTF-8. */
+ content?: string
}
export interface JsImageRect {
x: number
@@ -318,6 +347,27 @@ export interface JsScreenshotResult {
width: number
height: number
imageBuffer: Buffer
+ /** True when every pixel has the same color (blank page after render). */
+ isSolidFill: boolean
+ /**
+ * Solid rectangles/lines detected in the raster (viewport coords).
+ * Populated only when `detectScreenshotRects` is enabled.
+ */
+ rects: Array<JsScreenshotRect>
+}
+/**
+ * One solid rectangle (or line) detected in a rendered page bitmap, in
+ * viewport coords (top-left origin, 72 DPI).
+ */
+export interface JsScreenshotRect {
+ x: number
+ y: number
+ width: number
+ height: number
+ /** Fill color as ARGB hex string (e.g. "ff1a2b3c"). */
+ color: string
+ /** True when the region is a solid line rather than a filled area. */
+ isLine: boolean
}
export interface JsLayoutComplexityStats {
columnCount: number
diff --git a/packages/node/src/cli.ts b/packages/node/src/cli.ts
index 6766a9e..6db7662 100644
--- a/packages/node/src/cli.ts
+++ b/packages/node/src/cli.ts
@@ -68,6 +68,10 @@ program
.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-xfa-packets",
+ "Include raw XFA packets (name + XML content) in JSON output",
+ )
.option("--ocr-server-url <url>", "HTTP OCR server URL")
.option(
"--ocr-server-header <header>",
@@ -122,6 +126,7 @@ program
if (opts.extractAnnotations) config.extractAnnotations = true;
if (opts.extractFormFields) config.extractFormFields = true;
if (opts.extractStructureTree) config.extractStructureTree = true;
+ if (opts.extractXfaPackets) config.extractXfaPackets = true;
if (opts.ocrServerUrl)
config.ocrServerUrl = opts.ocrServerUrl as string;
if (opts.ocrServerHeader)
@@ -322,6 +327,10 @@ program
.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-xfa-packets",
+ "Include raw XFA packets (name + XML content) in JSON output",
+ )
.option(
"--extract-vector-graphics",
"Include page-scoped vector shapes and merged horizontal/vertical lines",
@@ -352,6 +361,8 @@ program
if (opts.extractAnnotations) config.extractAnnotations = true;
if (opts.extractFormFields) config.extractFormFields = true;
if (opts.extractStructureTree) config.extractStructureTree = true;
+ if (opts.extractXfaPackets) config.extractXfaPackets = true;
+ if (opts.extractXfaPackets) config.extractXfaPackets = 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 9da7d61..d53dd96 100644
--- a/packages/node/src/lib.ts
+++ b/packages/node/src/lib.ts
@@ -44,6 +44,10 @@ export interface LiteParseConfig {
extractFormFields: boolean;
/** Extract the tagged-PDF logical structure tree (default: false). */
extractStructureTree: boolean;
+ /** Extract raw XFA packets (name + XML content) into `ParseResult.xfaPackets` (default: false). */
+ extractXfaPackets: boolean;
+ /** Detect solid rectangles/lines in rendered page screenshots (default: false). */
+ detectScreenshotRects: boolean;
preserveVerySmallText: boolean;
password?: string;
quiet: boolean;
@@ -194,10 +198,22 @@ export interface PageInput {
graphics?: Graphic[];
}
+export interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
export interface ParsedPage {
pageNum: number;
width: number;
height: number;
+ /**
+ * Union bbox of the page's top-level content objects in viewport coords
+ * (visible content extent). Absent for empty pages.
+ */
+ contentBounds?: Rect;
text: string;
markdown: string;
textItems: TextItem[];
@@ -326,6 +342,21 @@ export interface ParseResult {
imageErrorCount: number;
/** PDFium form type, present only when `extractFormFields` is enabled. */
formType?: number;
+ /** The document's `/Info` `Creator` entry, when present. */
+ creator?: string;
+ /** The document's `/Info` `Producer` entry, when present. */
+ producer?: string;
+ /** Raw XFA packets; present only when `extractXfaPackets` is enabled. */
+ xfaPackets?: XfaPacket[];
+}
+
+/** One raw packet from an XFA form document's `/XFA` array. */
+export interface XfaPacket {
+ index: number;
+ name?: string;
+ contentLength: number;
+ /** Packet content (usually XML), lossily decoded as UTF-8. */
+ content?: string;
}
export interface ScreenshotResult {
@@ -333,6 +364,22 @@ export interface ScreenshotResult {
width: number;
height: number;
imageBuffer: Buffer;
+ /** True when every pixel has the same color (blank page after render). */
+ isSolidFill: boolean;
+ /** Solid rectangles/lines detected in the raster (viewport coords). Populated only with `detectScreenshotRects`. */
+ rects: ScreenshotRect[];
+}
+
+/** One solid rectangle (or line) detected in a rendered page bitmap. */
+export interface ScreenshotRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ /** Fill color as ARGB hex string (e.g. "ff1a2b3c"). */
+ color: string;
+ /** True when the region is a solid line rather than a filled area. */
+ isLine: boolean;
}
/**
@@ -437,6 +484,8 @@ export class LiteParse {
extractAnnotations: userConfig.extractAnnotations,
extractFormFields: userConfig.extractFormFields,
extractStructureTree: userConfig.extractStructureTree,
+ extractXfaPackets: userConfig.extractXfaPackets,
+ detectScreenshotRects: userConfig.detectScreenshotRects,
preserveVerySmallText: userConfig.preserveVerySmallText,
password: userConfig.password,
quiet: userConfig.quiet,
@@ -472,6 +521,8 @@ export class LiteParse {
extractAnnotations: resolved.extractAnnotations ?? false,
extractFormFields: resolved.extractFormFields ?? false,
extractStructureTree: resolved.extractStructureTree ?? false,
+ extractXfaPackets: resolved.extractXfaPackets ?? false,
+ detectScreenshotRects: resolved.detectScreenshotRects ?? false,
preserveVerySmallText: resolved.preserveVerySmallText ?? false,
password: resolved.password ?? undefined,
quiet: resolved.quiet ?? false,
@@ -498,6 +549,9 @@ export class LiteParse {
images: (result.images ?? []).map(toImage),
imageErrorCount: result.imageErrorCount ?? 0,
formType: result.formType,
+ creator: result.creator,
+ producer: result.producer,
+ xfaPackets: result.xfaPackets,
};
}
@@ -552,6 +606,8 @@ export class LiteParse {
width: r.width,
height: r.height,
imageBuffer: r.imageBuffer,
+ isSolidFill: r.isSolidFill,
+ rects: r.rects,
}));
}
@@ -595,6 +651,7 @@ function toPage(p: NativeParsedPage): ParsedPage {
pageNum: p.pageNum,
width: p.width,
height: p.height,
+ contentBounds: p.contentBounds,
text: p.text,
markdown: p.markdown,
textItems: p.textItems.map(toTextItem),
diff --git a/packages/node/src/native.ts b/packages/node/src/native.ts
index 13e0a55..922f8ca 100644
--- a/packages/node/src/native.ts
+++ b/packages/node/src/native.ts
@@ -36,6 +36,8 @@ export interface LiteParseNativeConfig {
extractAnnotations?: boolean;
extractFormFields?: boolean;
extractStructureTree?: boolean;
+ extractXfaPackets?: boolean;
+ detectScreenshotRects?: boolean;
preserveVerySmallText?: boolean;
password?: string;
quiet?: boolean;
@@ -114,10 +116,18 @@ export interface NativePageInput {
graphics?: NativeGraphic[];
}
+export interface NativeRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
export interface NativeParsedPage {
pageNum: number;
width: number;
height: number;
+ contentBounds?: NativeRect;
text: string;
markdown: string;
textItems: NativeTextItem[];
@@ -225,6 +235,16 @@ export interface NativeParseResult {
images: NativeExtractedImage[];
imageErrorCount: number;
formType?: number;
+ creator?: string;
+ producer?: string;
+ xfaPackets?: NativeXfaPacket[];
+}
+
+export interface NativeXfaPacket {
+ index: number;
+ name?: string;
+ contentLength: number;
+ content?: string;
}
export interface NativeScreenshotResult {
@@ -232,6 +252,17 @@ export interface NativeScreenshotResult {
width: number;
height: number;
imageBuffer: Buffer;
+ isSolidFill: boolean;
+ rects: NativeScreenshotRect[];
+}
+
+export interface NativeScreenshotRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ color: string;
+ isLine: boolean;
}
export interface NativeLayoutComplexityStats {
diff --git a/packages/python/liteparse/__init__.py b/packages/python/liteparse/__init__.py
index 8f3d36c..c069726 100644
--- a/packages/python/liteparse/__init__.py
+++ b/packages/python/liteparse/__init__.py
@@ -13,9 +13,11 @@ from .types import (
LiteParseConfig,
PageComplexityStats,
ParseResult,
+ XfaPacket,
ParsedPage,
TextItem,
WordBox,
+ ScreenshotRect,
ScreenshotResult,
ParseError,
VectorGraphics,
@@ -36,9 +38,11 @@ __all__ = [
"StructureTreeElement",
"LiteParseConfig",
"ParseResult",
+ "XfaPacket",
"ParsedPage",
"TextItem",
"WordBox",
+ "ScreenshotRect",
"ScreenshotResult",
"PageComplexityStats",
"LayoutComplexityStats",
diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.py
index 8c7b89d..c67ca56 100644
--- a/packages/python/liteparse/parser.py
+++ b/packages/python/liteparse/parser.py
@@ -20,8 +20,10 @@ from .types import (
ParsedPage,
ParseError,
ParseResult,
+ ScreenshotRect,
ScreenshotResult,
TextItem,
+ XfaPacket,
WordBox,
VectorGraphics,
VectorLine,
@@ -158,6 +160,21 @@ def _convert_native_result(native_result: Any) -> ParseResult:
page_num=native_page.page_num,
width=native_page.width,
height=native_page.height,
+ content_bounds=(
+ (
+ native_content_bounds.x,
+ native_content_bounds.y,
+ native_content_bounds.width,
+ native_content_bounds.height,
+ )
+ if (
+ native_content_bounds := getattr(
+ native_page, "content_bounds", None
+ )
+ )
+ is not None
+ else None
+ ),
text=native_page.text,
markdown=native_page.markdown,
text_items=text_items,
@@ -290,12 +307,28 @@ def _convert_native_result(native_result: Any) -> ParseResult:
)
for img in getattr(native_result, "images", [])
]
+ native_xfa_packets = getattr(native_result, "xfa_packets", None)
return ParseResult(
pages=pages,
text=native_result.text,
images=images,
image_error_count=getattr(native_result, "image_error_count", 0),
form_type=getattr(native_result, "form_type", None),
+ creator=getattr(native_result, "creator", None),
+ producer=getattr(native_result, "producer", None),
+ xfa_packets=(
+ [
+ XfaPacket(
+ index=packet.index,
+ name=packet.name,
+ content_length=packet.content_length,
+ content=packet.content,
+ )
+ for packet in native_xfa_packets
+ ]
+ if native_xfa_packets is not None
+ else None
+ ),
)
@@ -335,6 +368,8 @@ class LiteParse:
extract_annotations: Optional[bool] = None,
extract_form_fields: Optional[bool] = None,
extract_structure_tree: Optional[bool] = None,
+ extract_xfa_packets: Optional[bool] = None,
+ detect_screenshot_rects: Optional[bool] = None,
ocr_failure_fatal: Optional[bool] = None,
ocr_hedge_delays_ms: Optional[List[int]] = None,
emit_word_boxes: Optional[bool] = None,
@@ -452,6 +487,10 @@ class LiteParse:
kwargs["extract_form_fields"] = extract_form_fields
if extract_structure_tree is not None:
kwargs["extract_structure_tree"] = extract_structure_tree
+ if extract_xfa_packets is not None:
+ kwargs["extract_xfa_packets"] = extract_xfa_packets
+ if detect_screenshot_rects is not None:
+ kwargs["detect_screenshot_rects"] = detect_screenshot_rects
if ocr_failure_fatal is not None:
kwargs["ocr_failure_fatal"] = ocr_failure_fatal
if ocr_hedge_delays_ms is not None:
@@ -577,6 +616,18 @@ class LiteParse:
width=r.width,
height=r.height,
image_bytes=r.image_bytes,
+ is_solid_fill=getattr(r, "is_solid_fill", False),
+ rects=[
+ ScreenshotRect(
+ x=rect.x,
+ y=rect.y,
+ width=rect.width,
+ height=rect.height,
+ color=rect.color,
+ is_line=rect.is_line,
+ )
+ for rect in getattr(r, "rects", [])
+ ],
)
for r in native_results
]
@@ -615,6 +666,8 @@ class LiteParse:
extract_text_metadata=cfg.extract_text_metadata,
extract_images=cfg.extract_images,
extract_vector_graphics=cfg.extract_vector_graphics,
+ extract_xfa_packets=cfg.extract_xfa_packets,
+ detect_screenshot_rects=cfg.detect_screenshot_rects,
)
def __repr__(self) -> str:
diff --git a/packages/python/liteparse/types.py b/packages/python/liteparse/types.py
index 7db220f..476f25e 100644
--- a/packages/python/liteparse/types.py
+++ b/packages/python/liteparse/types.py
@@ -137,6 +137,10 @@ class ParsedPage:
form_fields: Optional[List[FormField]] = None
#: Present only when parsing with ``extract_structure_tree=True``.
structure_tree: Optional[StructureTree] = None
+ #: Union bbox ``(x, y, width, height)`` of the page's top-level content
+ #: objects in viewport coords (visible content extent). ``None`` for
+ #: empty pages.
+ content_bounds: Optional[Tuple[float, float, float, float]] = None
@dataclass
@@ -199,6 +203,16 @@ class ExtractedImage:
duplicate_of: Optional[str] = None
+@dataclass
+class XfaPacket:
+ """One raw packet from an XFA form document's ``/XFA`` array."""
+ index: int
+ name: Optional[str]
+ content_length: int
+ #: Packet content (usually XML), lossily decoded as UTF-8.
+ content: Optional[str]
+
+
@dataclass
class ParseResult:
"""Result of parsing a document."""
@@ -208,6 +222,12 @@ class ParseResult:
image_error_count: int = 0
#: PDFium form type, present only when ``extract_form_fields=True``.
form_type: Optional[int] = None
+ #: The document's ``/Info`` ``Creator`` entry, when present.
+ creator: Optional[str] = None
+ #: The document's ``/Info`` ``Producer`` entry, when present.
+ producer: Optional[str] = None
+ #: Raw XFA packets; present only when ``extract_xfa_packets=True``.
+ xfa_packets: Optional[List[XfaPacket]] = None
@property
def num_pages(self) -> int:
@@ -221,6 +241,20 @@ class ParseResult:
return None
+@dataclass
+class ScreenshotRect:
+ """One solid rectangle (or line) detected in a rendered page bitmap,
+ in viewport coords (top-left origin, 72 DPI)."""
+ x: float
+ y: float
+ width: float
+ height: float
+ #: Fill color as ARGB hex string (e.g. ``"ff1a2b3c"``).
+ color: str
+ #: True when the region is a solid line rather than a filled area.
+ is_line: bool
+
+
@dataclass
class ScreenshotResult:
"""Result of a single page screenshot."""
@@ -228,6 +262,11 @@ class ScreenshotResult:
width: int
height: int
image_bytes: bytes
+ #: True when every pixel has the same color (blank page after render).
+ is_solid_fill: bool = False
+ #: Solid rectangles/lines detected in the raster. Populated only when
+ #: ``detect_screenshot_rects=True``.
+ rects: List[ScreenshotRect] = field(default_factory=list)
@dataclass
@@ -310,6 +349,8 @@ class LiteParseConfig:
extract_text_metadata: bool = False
extract_images: bool = False
extract_vector_graphics: bool = False
+ extract_xfa_packets: bool = False
+ detect_screenshot_rects: bool = False
class ParseError(Exception):