A fast, helpful, and open-source document parser
feat: extract AcroForm fields
Pierre-Loic doulcet2f1b26d2c2cf
diff --git a/Cargo.lock b/Cargo.lockindex e6eff05..9016f98 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -357,6 +357,15 @@ dependencies = ["hybrid-array",]+[[package]]+name = "block-padding"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"+dependencies = [+ "generic-array",+]+[[package]]name = "built"version = "0.8.1"@@ -369,6 +378,12 @@ version = "3.20.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"+[[package]]+name = "bytecount"+version = "0.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e"+[[package]]name = "bytemuck"version = "1.25.2"@@ -421,6 +436,15 @@ dependencies = ["rustversion",]+[[package]]+name = "cbc"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"+dependencies = [+ "cipher",+]+[[package]]name = "cc"version = "1.3.0"@@ -987,6 +1011,15 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"+[[package]]+name = "ecb"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a8bfa975b1aec2145850fcaa1c6fe269a16578c44705a532ae3edc92b8881c7"+dependencies = [+ "cipher",+]+[[package]]name = "either"version = "1.16.0"@@ -1750,6 +1783,7 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"dependencies = [+ "block-padding","generic-array",]@@ -1992,6 +2026,7 @@ dependencies = ["image","liteparse-pdfium","liteparse-pdfium-sys",+ "lopdf","oar-ocr","ordered-float","regex",@@ -2101,6 +2136,34 @@ dependencies = ["imgref",]+[[package]]+name = "lopdf"+version = "0.38.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7184fdea2bc3cd272a1acec4030c321a8f9875e877b3f92a53f2f6033fdc289"+dependencies = [+ "aes",+ "bitflags 2.13.1",+ "cbc",+ "ecb",+ "encoding_rs",+ "flate2",+ "getrandom 0.3.4",+ "indexmap",+ "itoa",+ "log",+ "md-5",+ "nom 8.0.0",+ "nom_locate",+ "rand 0.9.5",+ "rangemap",+ "sha2 0.10.9",+ "stringprep",+ "thiserror 2.0.19",+ "ttf-parser 0.25.1",+ "weezl",+]+[[package]]name = "lru-slab"version = "0.1.2"@@ -2179,6 +2242,16 @@ dependencies = ["rayon",]+[[package]]+name = "md-5"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"+dependencies = [+ "cfg-if",+ "digest 0.10.7",+]+[[package]]name = "memchr"version = "2.8.3"@@ -2448,6 +2521,17 @@ dependencies = ["memchr",]+[[package]]+name = "nom_locate"+version = "5.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b577e2d69827c4740cba2b52efaad1c4cc7c73042860b199710b3575c68438d"+dependencies = [+ "bytecount",+ "memchr",+ "nom 8.0.0",+]+[[package]]name = "noop_proc_macro"version = "0.3.0"@@ -2590,7 +2674,7 @@ dependencies = ["regex","serde","serde_json",- "sha2",+ "sha2 0.11.0","thiserror 2.0.19","tokenizers","tracing",@@ -3171,6 +3255,12 @@ dependencies = ["rand_core 0.10.1",]+[[package]]+name = "rangemap"+version = "1.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68"+[[package]]name = "rav1e"version = "0.8.1"@@ -3813,6 +3903,17 @@ dependencies = ["digest 0.10.7",]+[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest 0.10.7",+]+[[package]]name = "sha2"version = "0.11.0"@@ -3994,6 +4095,17 @@ dependencies = ["float-cmp",]+[[package]]+name = "stringprep"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"+dependencies = [+ "unicode-bidi",+ "unicode-normalization",+ "unicode-properties",+]+[[package]]name = "strsim"version = "0.11.1"@@ -4555,6 +4667,15 @@ version = "1.0.24"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"+[[package]]+name = "unicode-normalization"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"+dependencies = [+ "tinyvec",+]+[[package]]name = "unicode-normalization-alignments"version = "0.1.12"diff --git a/README.md b/README.mdindex 3de0792..19a2494 100644--- a/README.md+++ b/README.md@@ -168,6 +168,9 @@ lit parse document.pdf --format json --extract-text-metadata# Include page annotations in structured JSONlit parse document.pdf --format json --extract-annotations+# Include AcroForm widget fields and values (repairs orphaned widgets in memory)+lit parse document.pdf --format json --extract-form-fields+# Parse a remote PDFcurl -sL https://example.com/report.pdf | lit parse -```@@ -307,6 +310,7 @@ Options:--extract-vector-graphics Include page vector shapes and merged H/V lines--no-links Emit link anchor text as plain text (no [text](url)) in markdown--extract-annotations Include PDF annotations in page output+ --extract-form-fields Include AcroForm widget fields and values--preserve-small-text Keep very small text--password <password> Password for encrypted documents--num-workers <n> Concurrent OCR workers [default: CPU cores - 1]diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rsindex c6c28f2..64949d1 100644--- a/crates/liteparse-napi/src/types.rs+++ b/crates/liteparse-napi/src/types.rs@@ -5,7 +5,8 @@ use napi_derive::napi;use liteparse::config::{CropBox, ImageMode, LiteParseConfig, OutputFormat};use liteparse::parser::ParseResult;use liteparse::types::{- DocumentAnnotation, GraphicPrimitive, Page, ParsedPage, Rect, TextItem, VectorGraphics, WordBox,+ DocumentAnnotation, FormField, GraphicPrimitive, Page, ParsedPage, Rect, TextItem,+ VectorGraphics, WordBox,};// ---------------------------------------------------------------------------@@ -56,6 +57,8 @@ pub struct JsLiteParseConfig {pub extract_links: Option<bool>,/// Extract all PDF annotations as page-scoped structured data.pub extract_annotations: Option<bool>,+ /// Extract AcroForm widget fields and values.+ pub extract_form_fields: 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.@@ -161,6 +164,9 @@ impl JsLiteParseConfig {if let Some(v) = self.extract_annotations {cfg.extract_annotations = v;}+ if let Some(v) = self.extract_form_fields {+ cfg.extract_form_fields = v;+ }if let Some(v) = self.ocr_failure_fatal {cfg.ocr_failure_fatal = v;}@@ -225,6 +231,7 @@ impl JsLiteParseConfig {image_output_dir: cfg.image_output_dir.clone(),extract_links: Some(cfg.extract_links),extract_annotations: Some(cfg.extract_annotations),+ extract_form_fields: Some(cfg.extract_form_fields),ocr_failure_fatal: Some(cfg.ocr_failure_fatal),ocr_hedge_delays_ms: Some(cfg.ocr_hedge_delays_ms@@ -484,6 +491,7 @@ impl JsPageInput {struct_nodes: Vec::new(),image_refs: Vec::new(),annotations: None,+ form_fields: None,}}}@@ -504,6 +512,7 @@ pub struct JsParsedPage {pub complexity: Option<JsPageComplexityStats>,pub vector_graphics: Option<JsVectorGraphics>,pub annotations: Option<Vec<JsDocumentAnnotation>>,+ pub form_fields: Option<Vec<JsFormField>>,}#[napi(object)]@@ -619,6 +628,52 @@ pub struct JsDocumentAnnotation {pub uri: Option<String>,}+#[napi(object)]+#[derive(Clone)]+pub struct JsFormField {+ pub id: String,+ pub field_type: String,+ pub page: u32,+ pub annotation_index: i32,+ pub widget_index: i32,+ pub object_number: Option<i32>,+ pub name: Option<String>,+ pub alternate_name: Option<String>,+ pub value: Option<String>,+ pub export_value: Option<String>,+ pub field_flags: i32,+ pub control_count: Option<i32>,+ pub control_index: Option<i32>,+ pub checked: Option<bool>,+ pub rect: Option<JsAnnotationRect>,+ pub options: Vec<String>,+ pub selected_options: Vec<String>,+}++impl JsFormField {+ fn from_rust(field: &FormField) -> Self {+ Self {+ id: field.id.clone(),+ field_type: field.field_type.clone(),+ page: field.page,+ annotation_index: field.annotation_index,+ widget_index: field.widget_index,+ object_number: field.object_number,+ name: field.name.clone(),+ alternate_name: field.alternate_name.clone(),+ value: field.value.clone(),+ export_value: field.export_value.clone(),+ field_flags: field.field_flags,+ control_count: field.control_count,+ control_index: field.control_index,+ checked: field.checked,+ rect: field.rect.as_ref().map(JsAnnotationRect::from_rust),+ options: field.options.clone(),+ selected_options: field.selected_options.clone(),+ }+ }+}+impl JsDocumentAnnotation {fn from_rust(annotation: &DocumentAnnotation) -> Self {Self {@@ -665,6 +720,10 @@ impl JsParsedPage {.map(JsDocumentAnnotation::from_rust).collect()}),+ form_fields: page+ .form_fields+ .as_ref()+ .map(|fields| fields.iter().map(JsFormField::from_rust).collect()),}}}@@ -680,6 +739,7 @@ pub struct JsParseResult {pub text: String,pub images: Vec<JsExtractedImage>,pub image_error_count: u32,+ pub form_type: Option<i32>,}#[napi(object)]@@ -809,6 +869,7 @@ impl JsParseResult {.collect(),text: result.text.clone(),image_error_count: result.image_error_count,+ form_type: result.form_type,images: result.images.iter()diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rsindex 0918b2e..437fb33 100644--- a/crates/liteparse-python/src/cli.rs+++ b/crates/liteparse-python/src/cli.rs@@ -79,6 +79,9 @@ struct ParseCommand {/// Include all PDF annotations as page-scoped structured data.#[arg(long)]extract_annotations: bool,+ /// Include AcroForm widget fields and values.+ #[arg(long)]+ extract_form_fields: bool,/// Include per-page complexity signals as a `complexity` object on each/// page of JSON output. Off by default.#[arg(long)]@@ -248,6 +251,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {image_output_dir: cmd.image_output_dir.clone(),extract_links: !cmd.no_links,extract_annotations: cmd.extract_annotations,+ extract_form_fields: cmd.extract_form_fields,include_complexity: cmd.complexity,extract_text_metadata: cmd.extract_text_metadata,extract_vector_graphics: cmd.extract_vector_graphics,@@ -268,6 +272,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {&result.images,result.image_error_count,lp.config().extract_text_metadata,+ result.form_type,)?,OutputFormat::Text => text::format_text(&result.pages),OutputFormat::Markdown => result.text.clone(),@@ -388,6 +393,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {&result.images,result.image_error_count,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.rsindex b1f2764..eb20191 100644--- a/crates/liteparse-python/src/lib.rs+++ b/crates/liteparse-python/src/lib.rs@@ -177,6 +177,69 @@ impl PyDocumentAnnotation {}}+#[pyclass(frozen, from_py_object)]+#[derive(Clone)]+struct PyFormField {+ #[pyo3(get)]+ id: String,+ #[pyo3(get)]+ field_type: String,+ #[pyo3(get)]+ page: u32,+ #[pyo3(get)]+ annotation_index: i32,+ #[pyo3(get)]+ widget_index: i32,+ #[pyo3(get)]+ object_number: Option<i32>,+ #[pyo3(get)]+ name: Option<String>,+ #[pyo3(get)]+ alternate_name: Option<String>,+ #[pyo3(get)]+ value: Option<String>,+ #[pyo3(get)]+ export_value: Option<String>,+ #[pyo3(get)]+ field_flags: i32,+ #[pyo3(get)]+ control_count: Option<i32>,+ #[pyo3(get)]+ control_index: Option<i32>,+ #[pyo3(get)]+ checked: Option<bool>,+ #[pyo3(get)]+ rect: Option<PyAnnotationRect>,+ #[pyo3(get)]+ options: Vec<String>,+ #[pyo3(get)]+ selected_options: Vec<String>,+}++impl PyFormField {+ fn from_rust(field: liteparse::types::FormField) -> Self {+ Self {+ id: field.id,+ field_type: field.field_type,+ page: field.page,+ annotation_index: field.annotation_index,+ widget_index: field.widget_index,+ object_number: field.object_number,+ name: field.name,+ alternate_name: field.alternate_name,+ value: field.value,+ export_value: field.export_value,+ field_flags: field.field_flags,+ control_count: field.control_count,+ control_index: field.control_index,+ checked: field.checked,+ rect: field.rect.map(PyAnnotationRect::from_rust),+ options: field.options,+ selected_options: field.selected_options,+ }+ }+}+impl PyTextItem {fn to_rust(&self) -> liteparse::types::TextItem {liteparse::types::TextItem {@@ -272,6 +335,8 @@ struct PyParsedPage {vector_graphics: Option<PyVectorGraphics>,#[pyo3(get)]annotations: Option<Vec<PyDocumentAnnotation>>,+ #[pyo3(get)]+ form_fields: Option<Vec<PyFormField>>,}#[pyclass(frozen, from_py_object)]@@ -412,6 +477,9 @@ impl PyParsedPage {.map(PyDocumentAnnotation::from_rust).collect()}),+ form_fields: page+ .form_fields+ .map(|fields| fields.into_iter().map(PyFormField::from_rust).collect()),}}}@@ -427,6 +495,8 @@ struct PyParseResult {images: Vec<PyExtractedImage>,#[pyo3(get)]image_error_count: u32,+ #[pyo3(get)]+ form_type: Option<i32>,}#[pymethods]@@ -465,6 +535,7 @@ impl PyParseResult {.map(PyExtractedImage::from_rust).collect(),image_error_count: result.image_error_count,+ form_type: result.form_type,}}}@@ -737,6 +808,8 @@ struct PyLiteParseConfig {#[pyo3(get)]extract_annotations: bool,#[pyo3(get)]+ extract_form_fields: bool,+ #[pyo3(get)]ocr_failure_fatal: bool,#[pyo3(get)]ocr_hedge_delays_ms: Vec<u64>,@@ -799,6 +872,7 @@ impl PyLiteParseConfig {},extract_links: cfg.extract_links,extract_annotations: cfg.extract_annotations,+ extract_form_fields: cfg.extract_form_fields,ocr_failure_fatal: cfg.ocr_failure_fatal,ocr_hedge_delays_ms: cfg.ocr_hedge_delays_ms.clone(),emit_word_boxes: cfg.emit_word_boxes,@@ -850,6 +924,7 @@ impl LiteParse {image_output_dir = None,extract_links = None,extract_annotations = None,+ extract_form_fields = None,ocr_failure_fatal = None,ocr_hedge_delays_ms = None,emit_word_boxes = None,@@ -878,6 +953,7 @@ impl LiteParse {image_output_dir: Option<String>,extract_links: Option<bool>,extract_annotations: Option<bool>,+ extract_form_fields: Option<bool>,ocr_failure_fatal: Option<bool>,ocr_hedge_delays_ms: Option<Vec<u64>>,emit_word_boxes: Option<bool>,@@ -950,6 +1026,9 @@ impl LiteParse {if let Some(v) = extract_annotations {cfg.extract_annotations = v;}+ if let Some(v) = extract_form_fields {+ cfg.extract_form_fields = v;+ }if let Some(v) = ocr_failure_fatal {cfg.ocr_failure_fatal = v;}@@ -1161,6 +1240,7 @@ fn _liteparse(m: &Bound<'_, PyModule>) -> PyResult<()> {m.add_class::<PyWordBox>()?;m.add_class::<PyAnnotationRect>()?;m.add_class::<PyDocumentAnnotation>()?;+ m.add_class::<PyFormField>()?;m.add_class::<PyScreenshotResult>()?;m.add_class::<PyPageComplexityStats>()?;m.add_class::<PyLayoutComplexityStats>()?;diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rsindex db355ed..8925ba6 100644--- a/crates/liteparse-wasm/src/lib.rs+++ b/crates/liteparse-wasm/src/lib.rs@@ -57,6 +57,7 @@ pub struct LiteParseConfig {extract_images: Option<bool>,extract_links: Option<bool>,extract_annotations: Option<bool>,+ extract_form_fields: Option<bool>,ocr_failure_fatal: Option<bool>,ocr_hedge_delays_ms: Option<Vec<u64>>,preserve_very_small_text: Option<bool>,@@ -146,6 +147,9 @@ impl LiteParseConfig {if let Some(v) = self.extract_annotations {cfg.extract_annotations = v;}+ if let Some(v) = self.extract_form_fields {+ cfg.extract_form_fields = v;+ }if let Some(v) = self.ocr_failure_fatal {cfg.ocr_failure_fatal = v;}@@ -212,6 +216,7 @@ impl LiteParseConfig {extract_images: Some(cfg.extract_images),extract_links: Some(cfg.extract_links),extract_annotations: Some(cfg.extract_annotations),+ extract_form_fields: Some(cfg.extract_form_fields),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),@@ -285,6 +290,8 @@ pub struct ParsedPage {pub vector_graphics: Option<VectorGraphics>,#[serde(skip_serializing_if = "Option::is_none")]pub annotations: Option<Vec<DocumentAnnotation>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub form_fields: Option<Vec<FormField>>,}#[derive(Serialize, Tsify)]@@ -383,6 +390,59 @@ impl DocumentAnnotation {}}+#[derive(Serialize, Tsify)]+#[tsify(into_wasm_abi)]+#[serde(rename_all = "camelCase")]+pub struct FormField {+ pub id: String,+ #[serde(rename = "type")]+ pub field_type: String,+ pub page: u32,+ pub annotation_index: i32,+ pub widget_index: i32,+ pub object_number: Option<i32>,+ pub name: Option<String>,+ pub alternate_name: Option<String>,+ pub value: Option<String>,+ pub export_value: Option<String>,+ pub field_flags: i32,+ pub control_count: Option<i32>,+ pub control_index: Option<i32>,+ pub checked: Option<bool>,+ pub rect: Option<AnnotationRect>,+ pub options: Vec<String>,+ pub selected_options: Vec<String>,+}++impl FormField {+ fn from_rust(field: &liteparse::types::FormField) -> Self {+ Self {+ id: field.id.clone(),+ field_type: field.field_type.clone(),+ page: field.page,+ annotation_index: field.annotation_index,+ widget_index: field.widget_index,+ object_number: field.object_number,+ name: field.name.clone(),+ alternate_name: field.alternate_name.clone(),+ value: field.value.clone(),+ export_value: field.export_value.clone(),+ field_flags: field.field_flags,+ control_count: field.control_count,+ control_index: field.control_index,+ checked: field.checked,+ rect: field.rect.as_ref().map(|rect| AnnotationRect {+ x: rect.x,+ y: rect.y,+ width: rect.width,+ height: rect.height,+ }),+ options: field.options.clone(),+ selected_options: field.selected_options.clone(),+ }+ }+}+#[derive(Serialize, Tsify)]#[tsify(into_wasm_abi)]#[serde(rename_all = "camelCase")]@@ -391,6 +451,8 @@ pub struct ParseResult {pub text: String,pub images: Vec<ExtractedImage>,pub image_error_count: u32,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub form_type: Option<i32>,}#[derive(Serialize, Tsify)]@@ -677,6 +739,10 @@ impl LiteParse {.map(DocumentAnnotation::from_rust).collect()}),+ form_fields: p+ .form_fields+ .as_ref()+ .map(|fields| fields.iter().map(FormField::from_rust).collect()),}).collect();@@ -708,6 +774,7 @@ impl LiteParse {text: result.text.clone(),images,image_error_count: result.image_error_count,+ form_type: result.form_type,})}diff --git a/crates/liteparse/Cargo.toml b/crates/liteparse/Cargo.tomlindex 2ced39c..56a7b60 100644--- a/crates/liteparse/Cargo.toml+++ b/crates/liteparse/Cargo.toml@@ -48,6 +48,7 @@ resvg = "0.44"usvg = "0.44"[target.'cfg(not(target_arch = "wasm32"))'.dependencies]+lopdf = { version = "0.38", default-features = false }oar-ocr = { version = "0.8", optional = true }rmp = "0.8"tokio = { version = "1.52.3", features = ["rt-multi-thread", "fs", "process"] }diff --git a/crates/liteparse/src/acroform_repair.rs b/crates/liteparse/src/acroform_repair.rsnew file mode 100644index 0000000..6aca128--- /dev/null+++ b/crates/liteparse/src/acroform_repair.rs@@ -0,0 +1,238 @@+//! Best-effort repair for PDFs whose page annotations contain form widgets+//! but whose catalog omits `/AcroForm`.++use std::collections::HashSet;++use lopdf::{+ Document as LoDocument, IncrementalDocument, Object, ObjectId, StringFormat, dictionary,+};+use pdfium::Library;++use crate::types::PdfInput;++/// Return a verified in-memory incremental repair, or `None` when the input is+/// already healthy, is ineligible, or cannot be repaired safely.+pub(crate) fn repair_orphaned_widgets(+ lib: &Library,+ input: &PdfInput,+ password: Option<&str>,+) -> Option<PdfInput> {+ let bytes = match input {+ PdfInput::Bytes(bytes) => bytes.clone(),+ #[cfg(not(target_arch = "wasm32"))]+ PdfInput::Path(path) => std::fs::read(path).ok()?,+ #[cfg(target_arch = "wasm32")]+ PdfInput::Path(_) => return None,+ };+ if !bytes+ .windows(b"/Widget".len())+ .any(|window| window == b"/Widget")+ {+ return None;+ }++ let (pages_before, form_type_before) = {+ let document = lib.load_document_from_bytes(&bytes, password).ok()?;+ (document.page_count(), document.form_type())+ };+ if form_type_before != 0 {+ return None;+ }++ let parsed = LoDocument::load_mem(&bytes).ok()?;+ if parsed.trailer.has(b"Encrypt") {+ return None;+ }+ let root_id = parsed.trailer.get(b"Root").ok()?.as_reference().ok()?;+ let catalog = parsed.get_dictionary(root_id).ok()?;+ if catalog.has(b"AcroForm") {+ return None;+ }+ let (field_refs, first_widget_page) = collect_orphaned_fields(&parsed)?;++ let mut update = IncrementalDocument::create_from(bytes, parsed);+ update.opt_clone_object_to_new_document(root_id).ok()?;+ let acroform_id = update.new_document.add_object(dictionary! {+ "Fields" => Object::Array(field_refs.into_iter().map(Object::Reference).collect()),+ "NeedAppearances" => true,+ "DA" => Object::String(b"/Helv 0 Tf 0 g".to_vec(), StringFormat::Literal),+ });+ update+ .new_document+ .get_dictionary_mut(root_id)+ .ok()?+ .set("AcroForm", Object::Reference(acroform_id));++ let mut repaired = Vec::new();+ update.save_to(&mut repaired).ok()?;++ let accepted = {+ let document = lib.load_document_from_bytes(&repaired, password).ok()?;+ if document.page_count() != pages_before || document.form_type() == 0 {+ false+ } else if let Some(form) = document.form_environment() {+ document+ .page(first_widget_page as i32)+ .ok()+ .is_some_and(|page| {+ let view_box = page.view_box().unwrap_or(pdfium::RectF {+ left: 0.0,+ top: page.height(),+ right: page.width(),+ bottom: 0.0,+ });+ !page+ .form_fields(&form, &view_box, first_widget_page + 1)+ .is_empty()+ })+ } else {+ false+ }+ };+ accepted.then_some(PdfInput::Bytes(repaired))+}++fn collect_orphaned_fields(document: &LoDocument) -> Option<(Vec<ObjectId>, u32)> {+ let mut seen = HashSet::new();+ let mut fields = Vec::new();+ let mut first_page = None;++ for (page_number, page_id) in document.get_pages() {+ let page = document.get_dictionary(page_id).ok()?;+ let Ok(annots) = page.get(b"Annots") else {+ continue;+ };+ let (_, annots) = document.dereference(annots).ok()?;+ let Ok(annots) = annots.as_array() else {+ continue;+ };+ for entry in annots {+ let Ok(widget_id) = entry.as_reference() else {+ continue;+ };+ let Ok(widget) = document.get_dictionary(widget_id) else {+ continue;+ };+ if widget+ .get(b"Subtype")+ .ok()+ .and_then(|value| value.as_name().ok())+ != Some(b"Widget")+ {+ continue;+ }+ let field_id = widget+ .get(b"Parent")+ .ok()+ .and_then(|value| value.as_reference().ok())+ .or_else(|| widget.has(b"FT").then_some(widget_id));+ let Some(field_id) = field_id else { continue };+ first_page.get_or_insert(page_number.saturating_sub(1));+ if seen.insert(field_id) {+ fields.push(field_id);+ }+ }+ }+ Some((fields, first_page?))+}++#[cfg(test)]+mod tests {+ use lopdf::{Document, Object, Stream, StringFormat, dictionary};++ use crate::{config::LiteParseConfig, parser::LiteParse, types::PdfInput};++ #[test]+ fn widget_marker_gate_handles_split_positions() {+ let bytes = [b"prefix".as_slice(), b"/Widget", b"suffix"].concat();+ assert!(bytes.windows(7).any(|window| window == b"/Widget"));+ }++ fn form_pdf(include_acroform: bool) -> Vec<u8> {+ let mut doc = Document::with_version("1.7");+ let pages_id = doc.new_object_id();+ let widget_id = doc.add_object(dictionary! {+ "Type" => "Annot",+ "Subtype" => "Widget",+ "FT" => "Tx",+ "T" => Object::String(b"customer_name".to_vec(), StringFormat::Literal),+ "V" => Object::String(b"Ada Lovelace".to_vec(), StringFormat::Literal),+ "Rect" => vec![10.into(), 10.into(), 200.into(), 35.into()],+ "F" => 4,+ });+ let content_id = doc.add_object(Stream::new(dictionary! {}, Vec::new()));+ let page_id = doc.add_object(dictionary! {+ "Type" => "Page",+ "Parent" => pages_id,+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],+ "Annots" => vec![Object::Reference(widget_id)],+ "Contents" => content_id,+ });+ doc.objects.insert(+ pages_id,+ Object::Dictionary(dictionary! {+ "Type" => "Pages",+ "Kids" => vec![Object::Reference(page_id)],+ "Count" => 1,+ }),+ );+ let acroform_id = include_acroform.then(|| {+ doc.add_object(dictionary! {+ "Fields" => vec![Object::Reference(widget_id)],+ "NeedAppearances" => true,+ "DA" => Object::String(b"/Helv 0 Tf 0 g".to_vec(), StringFormat::Literal),+ })+ });+ let mut catalog = dictionary! { "Type" => "Catalog", "Pages" => pages_id };+ if let Some(acroform_id) = acroform_id {+ catalog.set("AcroForm", acroform_id);+ }+ let catalog_id = doc.add_object(catalog);+ doc.trailer.set("Root", catalog_id);+ let mut bytes = Vec::new();+ doc.save_to(&mut bytes).unwrap();+ bytes+ }++ #[tokio::test]+ async fn extracts_healthy_acroform_fields_only_when_enabled() {+ let bytes = form_pdf(true);+ let disabled = LiteParse::new(LiteParseConfig {+ ocr_enabled: false,+ ..Default::default()+ })+ .parse_input(PdfInput::Bytes(bytes.clone()))+ .await+ .unwrap();+ assert!(disabled.pages[0].form_fields.is_none());++ let enabled = LiteParse::new(LiteParseConfig {+ ocr_enabled: false,+ extract_form_fields: true,+ ..Default::default()+ })+ .parse_input(PdfInput::Bytes(bytes))+ .await+ .unwrap();+ let fields = enabled.pages[0].form_fields.as_ref().unwrap();+ assert_eq!(fields.len(), 1);+ assert_eq!(fields[0].name.as_deref(), Some("customer_name"));+ assert_eq!(fields[0].value.as_deref(), Some("Ada Lovelace"));+ assert_eq!(fields[0].field_type, "text");+ }++ #[tokio::test]+ async fn repairs_orphaned_widgets_before_extraction() {+ let result = LiteParse::new(LiteParseConfig {+ ocr_enabled: false,+ extract_form_fields: true,+ ..Default::default()+ })+ .parse_input(PdfInput::Bytes(form_pdf(false)))+ .await+ .unwrap();+ let fields = result.pages[0].form_fields.as_ref().unwrap();+ assert_eq!(fields.len(), 1);+ assert_eq!(fields[0].value.as_deref(), Some("Ada Lovelace"));+ }+}diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rsindex 488534d..bd58d97 100644--- a/crates/liteparse/src/config.rs+++ b/crates/liteparse/src/config.rs@@ -48,6 +48,9 @@ pub struct LiteParseConfig {/// This is independent of `extract_links`, which only controls Markdown/// link reconstruction.pub extract_annotations: bool,+ /// Extract AcroForm widget fields and values. Default `false`.+ #[serde(default)]+ pub extract_form_fields: 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@@ -168,6 +171,7 @@ impl Default for LiteParseConfig {image_output_dir: None,extract_links: true,extract_annotations: false,+ extract_form_fields: 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.rsindex 771ce9b..93c52ad 100644--- a/crates/liteparse/src/extract.rs+++ b/crates/liteparse/src/extract.rs@@ -1,7 +1,7 @@use crate::error::LiteParseError;use crate::glyph_names::resolve_glyph_name;use crate::types::{- DocumentAnnotation, ExtractedImage, GraphicPrimitive, ImageRef, OutlineTarget,+ DocumentAnnotation, ExtractedImage, FormField, GraphicPrimitive, ImageRef, OutlineTarget,Page as LitePage, PdfInput, Rect, StructNode, TextItem, VectorGraphics, VectorLine,VectorShape, WordBox,};@@ -79,6 +79,10 @@ pub(crate) fn extract_pages_and_images(let mut images: Vec<ExtractedImage> = Vec::new();let mut image_cache: Vec<CachedImage> = Vec::new();let mut image_error_count = 0u32;+ let form_environment = output_options+ .extract_form_fields+ .then(|| document.form_environment())+ .flatten();for page_index in 0..page_count {let page_number = page_index as u32 + 1;@@ -142,6 +146,32 @@ pub(crate) fn extract_pages_and_images(}).collect()});+ let form_fields = output_options.extract_form_fields.then(|| {+ form_environment.as_ref().map_or_else(Vec::new, |form| {+ page.form_fields(form, &view_box, page_number)+ .into_iter()+ .map(|field| FormField {+ id: field.id,+ field_type: field.field_type,+ page: field.page,+ annotation_index: field.annotation_index,+ widget_index: field.widget_index,+ object_number: field.object_number,+ name: field.name,+ alternate_name: field.alternate_name,+ value: field.value,+ export_value: field.export_value,+ field_flags: field.field_flags,+ control_count: field.control_count,+ control_index: field.control_index,+ checked: field.checked,+ rect: field.rect.map(rect_from_pdfium),+ options: field.options,+ selected_options: field.selected_options,+ })+ .collect()+ })+ });if output_options.extract_images && !image_refs.is_empty() {let rendered = render_page_images(&page, page_number, &image_refs, &mut image_cache);@@ -163,6 +193,7 @@ pub(crate) fn extract_pages_and_images(struct_nodes,image_refs,annotations,+ form_fields,});}@@ -175,6 +206,7 @@ pub(crate) struct ExtractionOutputOptions {pub extract_images: bool,pub extract_vector_graphics: bool,pub extract_annotations: bool,+ pub extract_form_fields: bool,pub emit_word_boxes: bool,}@@ -2532,6 +2564,7 @@ mod tests {struct_nodes: Vec::new(),image_refs: Vec::new(),annotations: None,+ form_fields: None,}}diff --git a/crates/liteparse/src/lib.rs b/crates/liteparse/src/lib.rsindex 688b23b..56dd89b 100644--- a/crates/liteparse/src/lib.rs+++ b/crates/liteparse/src/lib.rs@@ -24,6 +24,8 @@ pub mod types;// ── Internal modules (available for binding crates, hidden from docs) ──#[cfg(not(target_arch = "wasm32"))]+mod acroform_repair;+#[cfg(not(target_arch = "wasm32"))]#[doc(hidden)]pub mod conversion;#[doc(hidden)]diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rsindex f9df078..d791d93 100644--- a/crates/liteparse/src/main.rs+++ b/crates/liteparse/src/main.rs@@ -127,6 +127,10 @@ struct ParseCommand {#[arg(long)]extract_annotations: bool,+ /// Include AcroForm widget fields and values as page-scoped structured data.+ #[arg(long)]+ extract_form_fields: 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.@@ -244,6 +248,9 @@ struct BatchParseCommand {/// Include all PDF annotations as page-scoped structured JSON/API data.#[arg(long)]extract_annotations: bool,+ /// Include AcroForm widget fields and values as page-scoped structured data.+ #[arg(long)]+ extract_form_fields: bool,}#[derive(Args, Debug)]@@ -364,6 +371,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {image_output_dir: cmd.image_output_dir.clone(),extract_links: !cmd.no_links,extract_annotations: cmd.extract_annotations,+ extract_form_fields: cmd.extract_form_fields,include_complexity: cmd.complexity,extract_text_metadata: cmd.extract_text_metadata,extract_vector_graphics: cmd.extract_vector_graphics,@@ -385,6 +393,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {&result.images,result.image_error_count,lp.config().extract_text_metadata,+ result.form_type,)?,OutputFormat::Text => text::format_text(&result.pages),OutputFormat::Markdown => result.text.clone(),@@ -465,6 +474,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {extract_images: cmd.extract_images,extract_vector_graphics: cmd.extract_vector_graphics,extract_annotations: cmd.extract_annotations,+ extract_form_fields: cmd.extract_form_fields,..Default::default()};if let Some(n) = cmd.num_workers {@@ -513,6 +523,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {&result.images,result.image_error_count,lp.config().extract_text_metadata,+ result.form_type,).map_err(|e| e.into()),OutputFormat::Text => Ok(text::format_text(&result.pages)),@@ -739,4 +750,33 @@ mod tests {})));}++ #[test]+ fn extract_form_fields_flag_is_available_for_parse_and_batch() {+ let cli =+ Cli::try_parse_from(["lit", "parse", "document.pdf", "--extract-form-fields"]).unwrap();+ assert!(matches!(+ cli.command,+ Commands::Parse(ParseCommand {+ extract_form_fields: true,+ ..+ })+ ));++ let cli = Cli::try_parse_from([+ "lit",+ "batch-parse",+ "input",+ "output",+ "--extract-form-fields",+ ])+ .unwrap();+ assert!(matches!(+ cli.command,+ Commands::BatchParse(BatchParseCommand {+ extract_form_fields: true,+ ..+ })+ ));+ }}diff --git a/crates/liteparse/src/markdown_layout/test_helpers.rs b/crates/liteparse/src/markdown_layout/test_helpers.rsindex dc48398..5ed2adc 100644--- a/crates/liteparse/src/markdown_layout/test_helpers.rs+++ b/crates/liteparse/src/markdown_layout/test_helpers.rs@@ -45,6 +45,7 @@ pub(crate) fn page(lines: Vec<ProjectedLine>) -> ParsedPage {image_refs: vec![],complexity: None,annotations: None,+ form_fields: None,}}@@ -198,6 +199,7 @@ pub(crate) fn header_footer_page(n: usize, header: &str, footer: &str, body: &stimage_refs: vec![],complexity: None,annotations: None,+ form_fields: None,}}diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rsindex a369664..6474a1d 100644--- a/crates/liteparse/src/ocr_merge.rs+++ b/crates/liteparse/src/ocr_merge.rs@@ -1166,6 +1166,7 @@ mod tests {struct_nodes: Vec::new(),image_refs: Vec::new(),annotations: None,+ form_fields: None,}}@@ -1200,6 +1201,7 @@ mod tests {struct_nodes: Vec::new(),image_refs: Vec::new(),annotations: None,+ form_fields: None,}}@@ -1225,6 +1227,7 @@ mod tests {struct_nodes: Vec::new(),image_refs: Vec::new(),annotations: None,+ form_fields: None,}}diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rsindex 88645e0..2fa5bf3 100644--- a/crates/liteparse/src/output/json.rs+++ b/crates/liteparse/src/output/json.rs@@ -1,5 +1,7 @@use crate::ocr_merge::PageComplexityStats;-use crate::types::{DocumentAnnotation, ExtractedImage, ParsedPage, Rect, VectorGraphics};+use crate::types::{+ DocumentAnnotation, ExtractedImage, FormField, ParsedPage, Rect, VectorGraphics,+};use serde::Serialize;#[derive(Debug, Serialize)]@@ -54,6 +56,8 @@ pub(crate) struct JsonPage {pub vector_graphics: Option<VectorGraphics>,#[serde(skip_serializing_if = "Option::is_none")]pub annotations: Option<Vec<DocumentAnnotation>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub form_fields: Option<Vec<FormField>>,}#[derive(Debug, Serialize)]@@ -63,6 +67,8 @@ pub(crate) struct ParseResultJson {pub images: Vec<JsonImage>,#[serde(skip_serializing_if = "is_zero")]pub image_error_count: u32,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub form_type: Option<i32>,}fn is_zero(value: &u32) -> bool {@@ -90,6 +96,7 @@ pub(crate) fn build_json(pages: &[ParsedPage], extract_text_metadata: bool) -> PParseResultJson {images: Vec::new(),image_error_count: 0,+ form_type: None,pages: pages.iter().map(|page| JsonPage {@@ -135,6 +142,7 @@ pub(crate) fn build_json(pages: &[ParsedPage], extract_text_metadata: bool) -> Pcomplexity: page.complexity.clone(),vector_graphics: page.vector_graphics.clone(),annotations: page.annotations.clone(),+ form_fields: page.form_fields.clone(),}).collect(),}@@ -147,6 +155,7 @@ pub fn format_json_result(images: &[ExtractedImage],image_error_count: u32,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@@ -165,6 +174,7 @@ pub fn format_json_result(}).collect();result.image_error_count = image_error_count;+ result.form_type = form_type;serde_json::to_string_pretty(&result)}@@ -185,7 +195,7 @@ pub fn format_json_with_text_metadata(#[cfg(test)]mod tests {use super::*;- use crate::types::{DocumentAnnotation, ParsedPage, Rect, TextItem};+ use crate::types::{DocumentAnnotation, FormField, ParsedPage, Rect, TextItem};fn item(text: &str, conf: Option<f32>) -> TextItem {TextItem {@@ -218,6 +228,7 @@ mod tests {image_refs: vec![],complexity: None,annotations: None,+ form_fields: None,}}@@ -325,7 +336,8 @@ mod tests {bytes: vec![1, 2, 3],};let value: serde_json::Value =- serde_json::from_str(&format_json_result(&[], &[image], 2, false).unwrap()).unwrap();+ serde_json::from_str(&format_json_result(&[], &[image], 2, false, None).unwrap())+ .unwrap();assert_eq!(value["images"][0]["bbox"]["x"], 10.0);assert_eq!(value["images"][0]["width"], 640);assert_eq!(value["images"][0]["rotation"], 90.0);@@ -390,4 +402,34 @@ mod tests {assert_eq!(value["pages"][0]["annotations"][0]["subtype"], "highlight");assert_eq!(value["pages"][0]["annotations"][0]["rect"]["width"], 90.0);}++ #[test]+ fn form_fields_use_the_public_snake_case_schema() {+ let mut parsed_page = page(vec![]);+ parsed_page.form_fields = Some(vec![FormField {+ id: "full_name".into(),+ field_type: "text".into(),+ page: 1,+ annotation_index: 2,+ widget_index: 0,+ object_number: Some(42),+ name: Some("full_name".into()),+ alternate_name: Some("Full name".into()),+ value: Some("Ada".into()),+ export_value: None,+ field_flags: 0,+ control_count: None,+ control_index: None,+ checked: None,+ rect: None,+ options: vec![],+ selected_options: vec![],+ }]);+ let value = serde_json::to_value(build_json(&[parsed_page], false)).unwrap();+ let field = &value["pages"][0]["form_fields"][0];+ assert_eq!(field["type"], "text");+ assert_eq!(field["annotation_index"], 2);+ assert_eq!(field["alternate_name"], "Full name");+ assert!(field.get("field_type").is_none());+ }}diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rsindex 2edc340..8022ae8 100644--- a/crates/liteparse/src/output/markdown.rs+++ b/crates/liteparse/src/output/markdown.rs@@ -161,6 +161,7 @@ mod tests {image_refs: vec![],complexity: None,annotations: None,+ form_fields: None,}}@@ -212,6 +213,7 @@ mod tests {image_refs: vec![],complexity: None,annotations: None,+ form_fields: 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.rsindex d548610..eb1305c 100644--- a/crates/liteparse/src/output/text.rs+++ b/crates/liteparse/src/output/text.rs@@ -30,6 +30,7 @@ mod tests {image_refs: vec![],complexity: None,annotations: None,+ form_fields: None,}}diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rsindex cc9f938..878f206 100644--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@ -33,6 +33,9 @@ pub struct ParseResult {/// Number of embedded image objects that could not be extracted. A bad/// image does not fail the rest of the document parse.pub image_error_count: u32,+ /// 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>,}/// Result of rendering a single page screenshot.@@ -352,9 +355,29 @@ 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) = {+ let (pages, ocr_rendered, outline, mut images, image_error_count, complexity, form_type) = {let lib = Library::init();- let document = extract::load_document_from_input(&lib, &validated_input, password)?;+ #[cfg(not(target_arch = "wasm32"))]+ let repaired_input = self+ .config+ .extract_form_fields+ .then(|| {+ crate::acroform_repair::repair_orphaned_widgets(+ &lib,+ &validated_input,+ password,+ )+ })+ .flatten();+ #[cfg(not(target_arch = "wasm32"))]+ let document_input = repaired_input.as_ref().unwrap_or(&validated_input);+ #[cfg(target_arch = "wasm32")]+ let document_input = &validated_input;+ let document = extract::load_document_from_input(&lib, document_input, password)?;+ let form_type = self+ .config+ .extract_form_fields+ .then(|| document.form_type());let outline = extract::extract_outline(&document);let (pages, images, image_error_count) = extract::extract_pages_and_images(&document,@@ -369,6 +392,7 @@ impl LiteParse {extract_text_metadata: self.config.extract_text_metadata,extract_vector_graphics: self.config.extract_vector_graphics,extract_annotations: self.config.extract_annotations,+ extract_form_fields: self.config.extract_form_fields,},)?;let t_extract = web_time::Instant::now();@@ -416,6 +440,7 @@ impl LiteParse {images,image_error_count,complexity,+ form_type,)};let mut pages = pages;@@ -501,6 +526,7 @@ impl LiteParse {outline,images,image_error_count,+ form_type,})}@@ -537,6 +563,7 @@ impl LiteParse {outline,images: Vec::new(),image_error_count: 0,+ form_type: None,}}@@ -634,6 +661,7 @@ mod tests {struct_nodes: vec![],image_refs: vec![],annotations: None,+ form_fields: None,}}diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rsindex 9dc0aba..837e8c5 100644--- a/crates/liteparse/src/projection.rs+++ b/crates/liteparse/src/projection.rs@@ -2916,6 +2916,7 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {image_refs: page.image_refs,complexity: None,annotations: page.annotations,+ form_fields: page.form_fields,}}).collect()@@ -5008,6 +5009,7 @@ mod tests {struct_nodes: Vec::new(),image_refs: Vec::new(),annotations: None,+ form_fields: None,};let projection_boxes = vec![projected_item("", 10.0, 0.0, 10.0),@@ -5311,6 +5313,7 @@ mod tests {struct_nodes: Vec::new(),image_refs: Vec::new(),annotations: None,+ form_fields: None,}];let parsed = project_pages_to_grid(pages);@@ -5350,6 +5353,7 @@ mod tests {struct_nodes: Vec::new(),image_refs: Vec::new(),annotations: None,+ form_fields: None,}];let parsed = project_pages_to_grid(pages);@@ -5412,6 +5416,7 @@ mod tests {struct_nodes: Vec::new(),image_refs: Vec::new(),annotations: None,+ form_fields: None,}];let parsed = project_pages_to_grid(pages);@@ -5454,6 +5459,7 @@ mod tests {struct_nodes: Vec::new(),image_refs: Vec::new(),annotations: None,+ form_fields: None,}];let parsed = project_pages_to_grid(pages);diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rsindex 5c2a522..32c740c 100644--- a/crates/liteparse/src/types.rs+++ b/crates/liteparse/src/types.rs@@ -127,6 +127,9 @@ pub struct Page {/// disabled extraction from an enabled page with no annotations.#[serde(skip)]pub annotations: Option<Vec<DocumentAnnotation>>,+ /// AcroForm widgets when explicitly requested.+ #[serde(skip)]+ pub form_fields: Option<Vec<FormField>>,}/// One PDF page annotation. Coordinates use the same top-left, 72-DPI@@ -150,6 +153,40 @@ pub struct DocumentAnnotation {pub uri: Option<String>,}+/// One AcroForm widget and its resolved field metadata.+#[derive(Debug, Clone, Serialize)]+pub struct FormField {+ pub id: String,+ #[serde(rename = "type")]+ pub field_type: String,+ pub page: u32,+ pub annotation_index: i32,+ pub widget_index: i32,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub object_number: Option<i32>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub alternate_name: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub value: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub export_value: Option<String>,+ pub field_flags: i32,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub control_count: Option<i32>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub control_index: Option<i32>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub checked: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub rect: Option<Rect>,+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub options: Vec<String>,+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub selected_options: Vec<String>,+}+/// 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.@@ -231,6 +268,9 @@ pub struct ParsedPage {/// annotations on this page.#[serde(skip_serializing_if = "Option::is_none")]pub annotations: Option<Vec<DocumentAnnotation>>,+ /// AcroForm widgets when `extract_form_fields` is true.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub form_fields: Option<Vec<FormField>>,}/// One embedded raster image on a page. `id` is a stable, page-scoped slug@@ -538,6 +578,7 @@ mod tests {struct_nodes: vec![],image_refs: vec![],annotations: None,+ form_fields: 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.rsindex 0ad7ad5..c7a9948 100644--- a/crates/pdfium-sys/src/dynamic.rs+++ b/crates/pdfium-sys/src/dynamic.rs@@ -41,6 +41,10 @@ pub struct PdfiumBindings {) -> FPDF_DOCUMENT,pub FPDF_CloseDocument: unsafe extern "C" fn(FPDF_DOCUMENT),pub FPDF_GetPageCount: unsafe extern "C" fn(FPDF_DOCUMENT) -> std::os::raw::c_int,+ pub FPDF_GetFormType: unsafe extern "C" fn(FPDF_DOCUMENT) -> std::os::raw::c_int,+ pub FPDFDOC_InitFormFillEnvironment:+ unsafe extern "C" fn(FPDF_DOCUMENT, *mut FPDF_FORMFILLINFO) -> FPDF_FORMHANDLE,+ pub FPDFDOC_ExitFormFillEnvironment: unsafe extern "C" fn(FPDF_FORMHANDLE),// -- Page --pub FPDF_LoadPage: unsafe extern "C" fn(FPDF_DOCUMENT, std::os::raw::c_int) -> FPDF_PAGE,@@ -323,6 +327,53 @@ pub struct PdfiumBindings {pub FPDFAnnot_GetAttachmentPoints:unsafe extern "C" fn(FPDF_ANNOTATION, usize, *mut FS_QUADPOINTSF) -> FPDF_BOOL,pub FPDFAnnot_GetLink: unsafe extern "C" fn(FPDF_ANNOTATION) -> FPDF_LINK,+ pub FPDFAnnot_GetLinkedAnnot:+ unsafe extern "C" fn(FPDF_ANNOTATION, FPDF_BYTESTRING) -> FPDF_ANNOTATION,+ pub FPDFAnnot_GetObjNum: unsafe extern "C" fn(FPDF_ANNOTATION) -> std::os::raw::c_int,+ pub FPDFAnnot_GetFormFieldFlags:+ unsafe extern "C" fn(FPDF_FORMHANDLE, FPDF_ANNOTATION) -> std::os::raw::c_int,+ pub FPDFAnnot_GetFormFieldName: unsafe extern "C" fn(+ FPDF_FORMHANDLE,+ FPDF_ANNOTATION,+ *mut FPDF_WCHAR,+ std::os::raw::c_ulong,+ ) -> std::os::raw::c_ulong,+ pub FPDFAnnot_GetFormFieldAlternateName: unsafe extern "C" fn(+ FPDF_FORMHANDLE,+ FPDF_ANNOTATION,+ *mut FPDF_WCHAR,+ std::os::raw::c_ulong,+ ) -> std::os::raw::c_ulong,+ pub FPDFAnnot_GetFormFieldType:+ unsafe extern "C" fn(FPDF_FORMHANDLE, FPDF_ANNOTATION) -> std::os::raw::c_int,+ pub FPDFAnnot_GetFormFieldValue: unsafe extern "C" fn(+ FPDF_FORMHANDLE,+ FPDF_ANNOTATION,+ *mut FPDF_WCHAR,+ std::os::raw::c_ulong,+ ) -> std::os::raw::c_ulong,+ pub FPDFAnnot_GetFormFieldExportValue: unsafe extern "C" fn(+ FPDF_FORMHANDLE,+ FPDF_ANNOTATION,+ *mut FPDF_WCHAR,+ std::os::raw::c_ulong,+ ) -> std::os::raw::c_ulong,+ pub FPDFAnnot_GetOptionCount:+ unsafe extern "C" fn(FPDF_FORMHANDLE, FPDF_ANNOTATION) -> std::os::raw::c_int,+ pub FPDFAnnot_GetOptionLabel: unsafe extern "C" fn(+ FPDF_FORMHANDLE,+ FPDF_ANNOTATION,+ std::os::raw::c_int,+ *mut FPDF_WCHAR,+ std::os::raw::c_ulong,+ ) -> std::os::raw::c_ulong,+ pub FPDFAnnot_IsOptionSelected:+ unsafe extern "C" fn(FPDF_FORMHANDLE, FPDF_ANNOTATION, std::os::raw::c_int) -> FPDF_BOOL,+ pub FPDFAnnot_IsChecked: unsafe extern "C" fn(FPDF_FORMHANDLE, FPDF_ANNOTATION) -> FPDF_BOOL,+ pub FPDFAnnot_GetFormControlCount:+ unsafe extern "C" fn(FPDF_FORMHANDLE, FPDF_ANNOTATION) -> std::os::raw::c_int,+ pub FPDFAnnot_GetFormControlIndex:+ unsafe extern "C" fn(FPDF_FORMHANDLE, FPDF_ANNOTATION) -> std::os::raw::c_int,pub FPDFDest_GetDestPageIndex:unsafe extern "C" fn(FPDF_DOCUMENT, FPDF_DEST) -> std::os::raw::c_int,pub FPDFDest_GetLocationInPage: unsafe extern "C" fn(@@ -385,6 +436,9 @@ impl PdfiumBindings {FPDF_LoadMemDocument: load_fn!(lib, "FPDF_LoadMemDocument"),FPDF_CloseDocument: load_fn!(lib, "FPDF_CloseDocument"),FPDF_GetPageCount: load_fn!(lib, "FPDF_GetPageCount"),+ FPDF_GetFormType: load_fn!(lib, "FPDF_GetFormType"),+ FPDFDOC_InitFormFillEnvironment: load_fn!(lib, "FPDFDOC_InitFormFillEnvironment"),+ FPDFDOC_ExitFormFillEnvironment: load_fn!(lib, "FPDFDOC_ExitFormFillEnvironment"),FPDF_LoadPage: load_fn!(lib, "FPDF_LoadPage"),FPDF_ClosePage: load_fn!(lib, "FPDF_ClosePage"),FPDF_GetPageWidthF: load_fn!(lib, "FPDF_GetPageWidthF"),@@ -485,6 +539,23 @@ impl PdfiumBindings {FPDFAnnot_CountAttachmentPoints: load_fn!(lib, "FPDFAnnot_CountAttachmentPoints"),FPDFAnnot_GetAttachmentPoints: load_fn!(lib, "FPDFAnnot_GetAttachmentPoints"),FPDFAnnot_GetLink: load_fn!(lib, "FPDFAnnot_GetLink"),+ FPDFAnnot_GetLinkedAnnot: load_fn!(lib, "FPDFAnnot_GetLinkedAnnot"),+ FPDFAnnot_GetObjNum: load_fn!(lib, "FPDFAnnot_GetObjNum"),+ FPDFAnnot_GetFormFieldFlags: load_fn!(lib, "FPDFAnnot_GetFormFieldFlags"),+ FPDFAnnot_GetFormFieldName: load_fn!(lib, "FPDFAnnot_GetFormFieldName"),+ FPDFAnnot_GetFormFieldAlternateName: load_fn!(+ lib,+ "FPDFAnnot_GetFormFieldAlternateName"+ ),+ FPDFAnnot_GetFormFieldType: load_fn!(lib, "FPDFAnnot_GetFormFieldType"),+ FPDFAnnot_GetFormFieldValue: load_fn!(lib, "FPDFAnnot_GetFormFieldValue"),+ FPDFAnnot_GetFormFieldExportValue: load_fn!(lib, "FPDFAnnot_GetFormFieldExportValue"),+ FPDFAnnot_GetOptionCount: load_fn!(lib, "FPDFAnnot_GetOptionCount"),+ FPDFAnnot_GetOptionLabel: load_fn!(lib, "FPDFAnnot_GetOptionLabel"),+ FPDFAnnot_IsOptionSelected: load_fn!(lib, "FPDFAnnot_IsOptionSelected"),+ FPDFAnnot_IsChecked: load_fn!(lib, "FPDFAnnot_IsChecked"),+ FPDFAnnot_GetFormControlCount: load_fn!(lib, "FPDFAnnot_GetFormControlCount"),+ FPDFAnnot_GetFormControlIndex: load_fn!(lib, "FPDFAnnot_GetFormControlIndex"),FPDFDest_GetDestPageIndex: load_fn!(lib, "FPDFDest_GetDestPageIndex"),FPDFDest_GetLocationInPage: load_fn!(lib, "FPDFDest_GetLocationInPage"),diff --git a/crates/pdfium/src/document.rs b/crates/pdfium/src/document.rsindex c47bdc0..bcd9538 100644--- a/crates/pdfium/src/document.rs+++ b/crates/pdfium/src/document.rs@@ -13,6 +13,15 @@ pub struct Document<'lib> {pub(crate) _lib: std::marker::PhantomData<&'lib Library>,}+/// PDFium's form-fill environment for an open document. The callback table+/// must remain alive until the handle is closed, even though LiteParse leaves+/// every callback null and uses the environment for read-only field access.+pub struct FormEnvironment<'doc, 'lib: 'doc> {+ pub(crate) handle: pdfium_sys::FPDF_FORMHANDLE,+ _callbacks: Box<pdfium_sys::FPDF_FORMFILLINFO>,+ _doc: std::marker::PhantomData<&'doc Document<'lib>>,+}+/// One entry in the document's outline (bookmarks tree).#[derive(Debug, Clone)]pub struct OutlineEntry {@@ -35,6 +44,31 @@ impl<'lib> Document<'lib> {unsafe { ffi!(FPDF_GetPageCount(self.handle)) }}+ pub fn form_type(&self) -> i32 {+ unsafe { ffi!(FPDF_GetFormType(self.handle)) }+ }++ /// Initialize read-only AcroForm access. Returns `None` for documents with+ /// no form catalog or when PDFium rejects the form-fill environment.+ pub fn form_environment(&self) -> Option<FormEnvironment<'_, 'lib>> {+ if self.form_type() == 0 {+ return None;+ }+ let mut callbacks = Box::new(pdfium_sys::FPDF_FORMFILLINFO::default());+ callbacks.version = 1;+ let handle = unsafe {+ ffi!(FPDFDOC_InitFormFillEnvironment(+ self.handle,+ &mut *callbacks+ ))+ };+ (!handle.is_null()).then_some(FormEnvironment {+ handle,+ _callbacks: callbacks,+ _doc: std::marker::PhantomData,+ })+ }+pub fn page(&self, index: i32) -> Result<Page<'_, 'lib>, PdfiumError> {let handle = unsafe { ffi!(FPDF_LoadPage(self.handle, index)) };if handle.is_null() {@@ -91,6 +125,12 @@ impl<'lib> Document<'lib> {}}+impl Drop for FormEnvironment<'_, '_> {+ fn drop(&mut self) {+ unsafe { ffi!(FPDFDOC_ExitFormFillEnvironment(self.handle)) };+ }+}+fn read_bookmark_title(bookmark: pdfium_sys::FPDF_BOOKMARK) -> String {let needed = unsafe { ffi!(FPDFBookmark_GetTitle(bookmark, std::ptr::null_mut(), 0)) } as usize;if needed < 2 {diff --git a/crates/pdfium/src/lib.rs b/crates/pdfium/src/lib.rsindex 2e5de24..2234e6f 100644--- a/crates/pdfium/src/lib.rs+++ b/crates/pdfium/src/lib.rs@@ -9,13 +9,13 @@ mod text_page;mod types;pub use bitmap::Bitmap;-pub use document::{Document, OutlineEntry};+pub use document::{Document, FormEnvironment, OutlineEntry};pub use error::PdfiumError;pub use font::{Font, FontType};pub use library::Library;pub use page::{ImageBounds, ImageObjectInfo, ImageObjects, Page, PathObject, PathSegment, PdfAnnotation,- PdfLink, SegmentKind, ViewportTransform,+ PdfFormField, PdfLink, SegmentKind, ViewportTransform,};pub use struct_tree::StructNode;pub use text_page::{TextChar, TextCharIter, TextPage};diff --git a/crates/pdfium/src/page.rs b/crates/pdfium/src/page.rsindex 54a2d49..58fb393 100644--- a/crates/pdfium/src/page.rs+++ b/crates/pdfium/src/page.rs@@ -1,7 +1,7 @@use std::marker::PhantomData;use crate::bitmap::Bitmap;-use crate::document::Document;+use crate::document::{Document, FormEnvironment};use crate::error::PdfiumError;use crate::ffi;use crate::text_page::TextPage;@@ -195,6 +195,29 @@ pub struct PdfAnnotation {pub uri: Option<String>,}+/// One AcroForm widget with its resolved field metadata. A logical radio or+/// checkbox field may appear more than once when it owns several widgets.+#[derive(Debug, Clone)]+pub struct PdfFormField {+ pub id: String,+ pub field_type: String,+ pub page: u32,+ pub annotation_index: i32,+ pub widget_index: i32,+ pub object_number: Option<i32>,+ pub name: Option<String>,+ pub alternate_name: Option<String>,+ pub value: Option<String>,+ pub export_value: Option<String>,+ pub field_flags: i32,+ pub control_count: Option<i32>,+ pub control_index: Option<i32>,+ pub checked: Option<bool>,+ pub rect: Option<RectF>,+ pub options: Vec<String>,+ pub selected_options: Vec<String>,+}+/// A loaded page within a [`Document`].////// The `'doc` lifetime ties the page to its owning document; `'lib` carries@@ -755,6 +778,235 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {}out}++ /// Enumerate AcroForm widget annotations and resolve their field values+ /// through PDFium's form-fill environment.+ pub fn form_fields(+ &self,+ form: &FormEnvironment<'_, '_>,+ view_box: &RectF,+ page_number: u32,+ ) -> Vec<PdfFormField> {+ let count = unsafe { ffi!(FPDFPage_GetAnnotCount(self.handle)) };+ let mut out = Vec::new();+ let mut widget_index = 0;+ for annotation_index in 0..count {+ let annot = unsafe { ffi!(FPDFPage_GetAnnot(self.handle, annotation_index)) };+ if annot.is_null() {+ continue;+ }+ if unsafe { ffi!(FPDFAnnot_GetSubtype(annot)) } != pdfium_sys::FPDF_ANNOT_WIDGET as i32+ {+ unsafe { ffi!(FPDFPage_CloseAnnot(annot)) };+ continue;+ }++ let parent =+ unsafe { ffi!(FPDFAnnot_GetLinkedAnnot(annot, b"Parent\0".as_ptr().cast())) };+ let name = first_present([+ read_form_string(+ form.handle,+ annot,+ |handle, annotation, buffer, len| unsafe {+ ffi!(FPDFAnnot_GetFormFieldName(handle, annotation, buffer, len))+ },+ ),+ read_annotation_string(annot, b"T\0"),+ (!parent.is_null())+ .then(|| read_annotation_string(parent, b"T\0"))+ .flatten(),+ ]);+ let alternate_name = first_present([+ read_form_string(+ form.handle,+ annot,+ |handle, annotation, buffer, len| unsafe {+ ffi!(FPDFAnnot_GetFormFieldAlternateName(+ handle, annotation, buffer, len+ ))+ },+ ),+ read_annotation_string(annot, b"TU\0"),+ (!parent.is_null())+ .then(|| read_annotation_string(parent, b"TU\0"))+ .flatten(),+ ]);+ let value = first_present([+ read_form_string(+ form.handle,+ annot,+ |handle, annotation, buffer, len| unsafe {+ ffi!(FPDFAnnot_GetFormFieldValue(handle, annotation, buffer, len))+ },+ ),+ read_annotation_string(annot, b"V\0"),+ (!parent.is_null())+ .then(|| read_annotation_string(parent, b"V\0"))+ .flatten(),+ ]);+ let appearance_state = read_annotation_string(annot, b"AS\0");+ let mut export_value = first_present([+ read_form_string(+ form.handle,+ annot,+ |handle, annotation, buffer, len| unsafe {+ ffi!(FPDFAnnot_GetFormFieldExportValue(+ handle, annotation, buffer, len+ ))+ },+ ),+ read_annotation_string(annot, b"V\0"),+ ]);+ if export_value.is_none() {+ export_value = appearance_state+ .as_ref()+ .filter(|state| state.as_str() != "Off")+ .cloned();+ }++ let raw_type = unsafe { ffi!(FPDFAnnot_GetFormFieldType(form.handle, annot)) };+ let object_number = match unsafe { ffi!(FPDFAnnot_GetObjNum(annot)) } {+ number if number > 0 => Some(number),+ _ => None,+ };+ let id = name+ .clone()+ .or_else(|| object_number.map(|n| format!("pdf-object-{n}")))+ .unwrap_or_else(|| format!("page-{page_number}-widget-{widget_index}"));+ let rect = annotation_rect(self, annot, view_box);+ let option_count = unsafe { ffi!(FPDFAnnot_GetOptionCount(form.handle, annot)) };+ let mut options = Vec::new();+ let mut selected_options = Vec::new();+ for option_index in 0..option_count.max(0) {+ if let Some(label) = read_form_option_label(form.handle, annot, option_index) {+ if unsafe { ffi!(FPDFAnnot_IsOptionSelected(form.handle, annot, option_index)) }+ != 0+ {+ selected_options.push(label.clone());+ }+ options.push(label);+ }+ }+ let is_checkable = raw_type == pdfium_sys::FPDF_FORMFIELD_CHECKBOX as i32+ || raw_type == pdfium_sys::FPDF_FORMFIELD_RADIOBUTTON as i32;+ let checked = is_checkable.then(|| {+ (unsafe { ffi!(FPDFAnnot_IsChecked(form.handle, annot)) }) != 0+ || appearance_state+ .as_ref()+ .is_some_and(|state| state != "Off")+ });+ let control_count = is_checkable+ .then(|| unsafe { ffi!(FPDFAnnot_GetFormControlCount(form.handle, annot)) })+ .filter(|value| *value >= 0);+ let control_index = is_checkable+ .then(|| unsafe { ffi!(FPDFAnnot_GetFormControlIndex(form.handle, annot)) })+ .filter(|value| *value >= 0);++ out.push(PdfFormField {+ id,+ field_type: form_field_type_name(raw_type).to_owned(),+ page: page_number,+ annotation_index,+ widget_index,+ object_number,+ name,+ alternate_name,+ value,+ export_value,+ field_flags: unsafe { ffi!(FPDFAnnot_GetFormFieldFlags(form.handle, annot)) },+ control_count,+ control_index,+ checked,+ rect,+ options,+ selected_options,+ });+ if !parent.is_null() {+ unsafe { ffi!(FPDFPage_CloseAnnot(parent)) };+ }+ unsafe { ffi!(FPDFPage_CloseAnnot(annot)) };+ widget_index += 1;+ }+ out+ }+}++fn form_field_type_name(field_type: i32) -> &'static str {+ match field_type as u32 {+ pdfium_sys::FPDF_FORMFIELD_PUSHBUTTON => "pushbutton",+ pdfium_sys::FPDF_FORMFIELD_CHECKBOX => "checkbox",+ pdfium_sys::FPDF_FORMFIELD_RADIOBUTTON => "radio",+ pdfium_sys::FPDF_FORMFIELD_COMBOBOX => "combobox",+ pdfium_sys::FPDF_FORMFIELD_LISTBOX => "listbox",+ pdfium_sys::FPDF_FORMFIELD_TEXTFIELD => "text",+ pdfium_sys::FPDF_FORMFIELD_SIGNATURE => "signature",+ _ => "unknown",+ }+}++fn first_present<const N: usize>(values: [Option<String>; N]) -> Option<String> {+ values.into_iter().flatten().find(|value| !value.is_empty())+}++fn read_form_string(+ form: pdfium_sys::FPDF_FORMHANDLE,+ annot: pdfium_sys::FPDF_ANNOTATION,+ mut getter: impl FnMut(+ pdfium_sys::FPDF_FORMHANDLE,+ pdfium_sys::FPDF_ANNOTATION,+ *mut u16,+ std::os::raw::c_ulong,+ ) -> std::os::raw::c_ulong,+) -> Option<String> {+ let needed = getter(form, annot, std::ptr::null_mut(), 0) as usize;+ if needed < 2 {+ return None;+ }+ let mut buffer = vec![0u16; needed.div_ceil(2)];+ let written = getter(+ form,+ annot,+ buffer.as_mut_ptr(),+ needed as std::os::raw::c_ulong,+ ) as usize;+ if written < 2 {+ return None;+ }+ let units = (written / 2).min(buffer.len());+ let end = units.saturating_sub(usize::from(buffer.get(units.saturating_sub(1)) == Some(&0)));+ let value = String::from_utf16_lossy(&buffer[..end]);+ (!value.is_empty()).then_some(value)+}++fn read_form_option_label(+ form: pdfium_sys::FPDF_FORMHANDLE,+ annot: pdfium_sys::FPDF_ANNOTATION,+ index: i32,+) -> Option<String> {+ read_form_string(form, annot, |handle, annotation, buffer, len| unsafe {+ ffi!(FPDFAnnot_GetOptionLabel(+ handle, annotation, index, buffer, len+ ))+ })+}++fn annotation_rect(+ page: &Page<'_, '_>,+ annot: pdfium_sys::FPDF_ANNOTATION,+ view_box: &RectF,+) -> Option<RectF> {+ let mut rect = pdfium_sys::FS_RECTF::default();+ (unsafe { ffi!(FPDFAnnot_GetRect(annot, &mut rect)) } != 0).then(|| {+ page.bounds_to_viewport(+ view_box,+ &RectF {+ left: rect.left,+ top: rect.top,+ right: rect.right,+ bottom: rect.bottom,+ },+ )+ })}fn annotation_subtype_name(subtype: pdfium_sys::FPDF_ANNOTATION_SUBTYPE) -> &'static str {diff --git a/packages/node/README.md b/packages/node/README.mdindex 711ee27..38a9eff 100644--- a/packages/node/README.md+++ b/packages/node/README.md@@ -63,6 +63,7 @@ const parser = new LiteParse({extractLinks: true, // Render [text](url) links in markdown outputextractVectorGraphics: false, // Opt-in shapes + merged H/V lines per pageextractAnnotations: false, // Include page annotations in structured output+ extractFormFields: false, // Include AcroForm widget fields and valuespreserveVerySmallText: false, // Keep tiny textextractTextMetadata: false, // Opt in to MCID, font metrics, colors, char codes, and trailingSpaceGeneratedpassword: undefined, // Password for protected documents@@ -157,6 +158,7 @@ The npm package includes the `lit` CLI:lit parse document.pdflit parse document.pdf --format json -o output.jsonlit parse document.pdf --format json --extract-annotations+lit parse document.pdf --format json --extract-form-fieldslit screenshot document.pdf -o ./screenshotslit batch-parse ./input ./outputlit is-complex document.pdfdiff --git a/packages/node/native.d.ts b/packages/node/native.d.tsindex 2da6a88..90e72b7 100644--- a/packages/node/native.d.ts+++ b/packages/node/native.d.ts@@ -53,6 +53,7 @@ export interface JsLiteParseConfig {extractLinks?: boolean/** Extract all PDF annotations as page-scoped structured data. */extractAnnotations?: boolean+ extractFormFields?: boolean/*** Whether a systemic OCR failure aborts the whole parse (default true).* Set false to keep already-recovered native text and return partial@@ -196,6 +197,7 @@ export interface JsParsedPage {complexity?: JsPageComplexityStatsvectorGraphics?: JsVectorGraphicsannotations?: Array<JsDocumentAnnotation>+ formFields?: Array<JsFormField>}export interface JsVectorShape {bbox: JsRect@@ -242,11 +244,32 @@ export interface JsDocumentAnnotation {quadpointRects: Array<JsAnnotationRect>uri?: string}++export interface JsFormField {+ id: string+ fieldType: string+ page: number+ annotationIndex: number+ widgetIndex: number+ objectNumber?: number+ name?: string+ alternateName?: string+ value?: string+ exportValue?: string+ fieldFlags: number+ controlCount?: number+ controlIndex?: number+ checked?: boolean+ rect?: JsAnnotationRect+ options: Array<string>+ selectedOptions: Array<string>+}export interface JsParseResult {pages: Array<JsParsedPage>text: stringimages: Array<JsExtractedImage>imageErrorCount: number+ formType?: number}export interface JsImageRect {x: numberdiff --git a/packages/node/src/cli-json.ts b/packages/node/src/cli-json.tsindex a9df8c4..11e527c 100644--- a/packages/node/src/cli-json.ts+++ b/packages/node/src/cli-json.ts@@ -1,5 +1,6 @@import type {DocumentAnnotation,+ FormField,ExtractedImage,PageComplexityStats,ParseResult,@@ -131,6 +132,28 @@ function annotationToCliJson(annotation: DocumentAnnotation) {};}+function formFieldToCliJson(field: FormField) {+ return {+ id: field.id,+ type: field.type,+ page: field.page,+ annotation_index: field.annotationIndex,+ widget_index: field.widgetIndex,+ ...(field.objectNumber !== undefined ? { object_number: field.objectNumber } : {}),+ ...(field.name !== undefined ? { name: field.name } : {}),+ ...(field.alternateName !== undefined ? { alternate_name: field.alternateName } : {}),+ ...(field.value !== undefined ? { value: field.value } : {}),+ ...(field.exportValue !== undefined ? { export_value: field.exportValue } : {}),+ field_flags: field.fieldFlags,+ ...(field.controlCount !== undefined ? { control_count: field.controlCount } : {}),+ ...(field.controlIndex !== undefined ? { control_index: field.controlIndex } : {}),+ ...(field.checked !== undefined ? { checked: field.checked } : {}),+ ...(field.rect !== undefined ? { rect: field.rect } : {}),+ ...(field.options.length ? { options: field.options } : {}),+ ...(field.selectedOptions.length ? { selected_options: field.selectedOptions } : {}),+ };+}+function imageToCliJson(image: ExtractedImage) {return {id: image.id,@@ -171,6 +194,9 @@ export function parseResultToCliJson(result: ParseResult) {...(page.annotations !== undefined? { annotations: page.annotations.map(annotationToCliJson) }: {}),+ ...(page.formFields !== undefined+ ? { form_fields: page.formFields.map(formFieldToCliJson) }+ : {}),})),...(result.images.length? { images: result.images.map(imageToCliJson) }@@ -178,5 +204,6 @@ export function parseResultToCliJson(result: ParseResult) {...(result.imageErrorCount? { image_error_count: result.imageErrorCount }: {}),+ ...(result.formType !== undefined ? { form_type: result.formType } : {}),};}diff --git a/packages/node/src/cli.ts b/packages/node/src/cli.tsindex 403a5c0..e8a2e6a 100644--- a/packages/node/src/cli.ts+++ b/packages/node/src/cli.ts@@ -66,6 +66,7 @@ program.option("--extract-images", "Extract embedded image bytes and metadata").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("--ocr-server-url <url>", "HTTP OCR server URL").option("--ocr-server-header <header>",@@ -118,6 +119,7 @@ programif (opts.extractImages) config.extractImages = true;if (opts.links === false) config.extractLinks = false;if (opts.extractAnnotations) config.extractAnnotations = true;+ if (opts.extractFormFields) config.extractFormFields = true;if (opts.ocrServerUrl)config.ocrServerUrl = opts.ocrServerUrl as string;if (opts.ocrServerHeader)@@ -316,6 +318,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-vector-graphics","Include page-scoped vector shapes and merged horizontal/vertical lines",@@ -344,6 +347,7 @@ programif (opts.extractTextMetadata) config.extractTextMetadata = true;if (opts.extractImages) config.extractImages = true;if (opts.extractAnnotations) config.extractAnnotations = true;+ if (opts.extractFormFields) config.extractFormFields = 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.tsindex 1a3ee1b..9e157e0 100644--- a/packages/node/src/lib.ts+++ b/packages/node/src/lib.ts@@ -39,6 +39,8 @@ export interface LiteParseConfig {extractLinks: boolean;/** Extract all PDF annotations into each parsed page (default: false). */extractAnnotations: boolean;+ /** Extract AcroForm widget fields and values (default: false). */+ extractFormFields: boolean;preserveVerySmallText: boolean;password?: string;quiet: boolean;@@ -206,6 +208,8 @@ export interface ParsedPage {vectorGraphics?: VectorGraphics;/** Present only when `extractAnnotations` is enabled. */annotations?: DocumentAnnotation[];+ /** Present only when `extractFormFields` is enabled. */+ formFields?: FormField[];}export interface VectorGraphics {@@ -249,6 +253,26 @@ export interface DocumentAnnotation {uri?: string;}+export interface FormField {+ id: string;+ type: string;+ page: number;+ annotationIndex: number;+ widgetIndex: number;+ objectNumber?: number;+ name?: string;+ alternateName?: string;+ value?: string;+ exportValue?: string;+ fieldFlags: number;+ controlCount?: number;+ controlIndex?: number;+ checked?: boolean;+ rect?: AnnotationRect;+ options: string[];+ selectedOptions: string[];+}+export interface ExtractedImage {/** Reference id used in the markdown output (e.g. `` → `"p1_0"`). */id: string;@@ -277,6 +301,8 @@ export interface ParseResult {images: ExtractedImage[];/** Embedded image objects that PDFium could not render or encode. */imageErrorCount: number;+ /** PDFium form type, present only when `extractFormFields` is enabled. */+ formType?: number;}export interface ScreenshotResult {@@ -386,6 +412,7 @@ export class LiteParse {imageOutputDir: userConfig.imageOutputDir,extractLinks: userConfig.extractLinks,extractAnnotations: userConfig.extractAnnotations,+ extractFormFields: userConfig.extractFormFields,preserveVerySmallText: userConfig.preserveVerySmallText,password: userConfig.password,quiet: userConfig.quiet,@@ -419,6 +446,7 @@ export class LiteParse {imageOutputDir: resolved.imageOutputDir ?? undefined,extractLinks: resolved.extractLinks ?? true,extractAnnotations: resolved.extractAnnotations ?? false,+ extractFormFields: resolved.extractFormFields ?? false,preserveVerySmallText: resolved.preserveVerySmallText ?? false,password: resolved.password ?? undefined,quiet: resolved.quiet ?? false,@@ -444,6 +472,7 @@ export class LiteParse {text: result.text,images: (result.images ?? []).map(toImage),imageErrorCount: result.imageErrorCount ?? 0,+ formType: result.formType,};}@@ -547,6 +576,25 @@ function toPage(p: NativeParsedPage): ParsedPage {complexity: p.complexity ? toComplexity(p.complexity) : undefined,vectorGraphics: p.vectorGraphics ?? undefined,annotations: p.annotations,+ formFields: p.formFields?.map((field) => ({+ id: field.id,+ type: field.fieldType,+ page: field.page,+ annotationIndex: field.annotationIndex,+ widgetIndex: field.widgetIndex,+ objectNumber: field.objectNumber,+ name: field.name,+ alternateName: field.alternateName,+ value: field.value,+ exportValue: field.exportValue,+ fieldFlags: field.fieldFlags,+ controlCount: field.controlCount,+ controlIndex: field.controlIndex,+ checked: field.checked,+ rect: field.rect,+ options: field.options,+ selectedOptions: field.selectedOptions,+ })),};}diff --git a/packages/node/src/native.ts b/packages/node/src/native.tsindex 4f66c19..76972a4 100644--- a/packages/node/src/native.ts+++ b/packages/node/src/native.ts@@ -34,6 +34,7 @@ export interface LiteParseNativeConfig {imageOutputDir?: string;extractLinks?: boolean;extractAnnotations?: boolean;+ extractFormFields?: boolean;preserveVerySmallText?: boolean;password?: string;quiet?: boolean;@@ -122,6 +123,7 @@ export interface NativeParsedPage {complexity?: NativePageComplexityStats;vectorGraphics?: NativeVectorGraphics;annotations?: NativeDocumentAnnotation[];+ formFields?: NativeFormField[];}export interface NativeVectorGraphics {@@ -158,6 +160,26 @@ export interface NativeDocumentAnnotation {uri?: string;}+export interface NativeFormField {+ id: string;+ fieldType: string;+ page: number;+ annotationIndex: number;+ widgetIndex: number;+ objectNumber?: number;+ name?: string;+ alternateName?: string;+ value?: string;+ exportValue?: string;+ fieldFlags: number;+ controlCount?: number;+ controlIndex?: number;+ checked?: boolean;+ rect?: NativeAnnotationRect;+ options: string[];+ selectedOptions: string[];+}+export interface NativeExtractedImage {id: string;name: string;@@ -177,6 +199,7 @@ export interface NativeParseResult {text: string;images: NativeExtractedImage[];imageErrorCount: number;+ formType?: number;}export interface NativeScreenshotResult {diff --git a/packages/python/README.md b/packages/python/README.mdindex 40787bc..b81e4ea 100644--- a/packages/python/README.md+++ b/packages/python/README.md@@ -62,6 +62,7 @@ parser = LiteParse(extract_links=True, # Render [text](url) links in markdown outputextract_vector_graphics=False, # Opt-in shapes + merged H/V lines per pageextract_annotations=False, # Include page annotations in structured output+ extract_form_fields=False, # Include AcroForm widget fields and valuespreserve_very_small_text=False, # Keep tiny textextract_text_metadata=False, # Opt in to MCID, font metrics, colors, char codes, and trailing_space_generatedpassword=None, # Password for protected documents@@ -150,6 +151,7 @@ The Python package includes the `lit` CLI:lit parse document.pdflit parse document.pdf --format json -o output.jsonlit parse document.pdf --format json --extract-annotations+lit parse document.pdf --format json --extract-form-fieldslit screenshot document.pdf -o ./screenshotslit batch-parse ./input ./outputlit is-complex document.pdfdiff --git a/packages/python/liteparse/__init__.py b/packages/python/liteparse/__init__.pyindex 801dd8b..c8940e3 100644--- a/packages/python/liteparse/__init__.py+++ b/packages/python/liteparse/__init__.py@@ -4,6 +4,7 @@ from .parser import LiteParse, search_itemsfrom .types import (AnnotationRect,DocumentAnnotation,+ FormField,ExtractedImage,ImageRect,LayoutComplexityStats,@@ -28,6 +29,7 @@ __all__ = ["LiteParse","AnnotationRect","DocumentAnnotation",+ "FormField","LiteParseConfig","ParseResult","ParsedPage",diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.pyindex a4cbee8..b9bb592 100644--- a/packages/python/liteparse/parser.py+++ b/packages/python/liteparse/parser.py@@ -9,6 +9,7 @@ from liteparse._liteparse import search_items as _native_search_itemsfrom .types import (AnnotationRect,DocumentAnnotation,+ FormField,ExtractedImage,ImageRect,LayoutComplexityStats,@@ -101,6 +102,7 @@ def _convert_native_result(native_result: Any) -> ParseResult:native_complexity = getattr(native_page, "complexity", None)native_vectors = getattr(native_page, "vector_graphics", None)native_annotations = getattr(native_page, "annotations", None)+ native_form_fields = getattr(native_page, "form_fields", None)pages.append(ParsedPage(page_num=native_page.page_num,@@ -179,6 +181,32 @@ def _convert_native_result(native_result: Any) -> ParseResult:if native_annotations is not Noneelse None),+ form_fields=(+ [+ FormField(+ id=form.id,+ field_type=form.field_type,+ page=form.page,+ annotation_index=form.annotation_index,+ widget_index=form.widget_index,+ object_number=form.object_number,+ name=form.name,+ alternate_name=form.alternate_name,+ value=form.value,+ export_value=form.export_value,+ field_flags=form.field_flags,+ control_count=form.control_count,+ control_index=form.control_index,+ checked=form.checked,+ rect=(AnnotationRect(form.rect.x, form.rect.y, form.rect.width, form.rect.height) if form.rect is not None else None),+ options=list(form.options),+ selected_options=list(form.selected_options),+ )+ for form in native_form_fields+ ]+ if native_form_fields is not None+ else None+ ),))images = [@@ -207,6 +235,7 @@ def _convert_native_result(native_result: Any) -> ParseResult:text=native_result.text,images=images,image_error_count=getattr(native_result, "image_error_count", 0),+ form_type=getattr(native_result, "form_type", None),)@@ -244,6 +273,7 @@ class LiteParse:image_output_dir: Optional[Union[str, Path]] = None,extract_links: Optional[bool] = None,extract_annotations: Optional[bool] = None,+ extract_form_fields: Optional[bool] = None,ocr_failure_fatal: Optional[bool] = None,ocr_hedge_delays_ms: Optional[List[int]] = None,emit_word_boxes: Optional[bool] = None,@@ -281,6 +311,8 @@ class LiteParse:``image_mode`` controls Markdown presentation independently.extract_annotations: Include all PDF annotations as page-scopedstructured data (default: False).+ extract_form_fields: Include AcroForm widget fields and values as+ page-scoped structured data (default: False).ocr_failure_fatal: Whether a systemic OCR failure (every OCR taskfailed and at least one was a text-sparse page) aborts the wholeparse (default: True). Set False to keep already-recovered native@@ -353,6 +385,8 @@ class LiteParse:kwargs["extract_links"] = extract_linksif extract_annotations is not None:kwargs["extract_annotations"] = extract_annotations+ if extract_form_fields is not None:+ kwargs["extract_form_fields"] = extract_form_fieldsif ocr_failure_fatal is not None:kwargs["ocr_failure_fatal"] = ocr_failure_fatalif ocr_hedge_delays_ms is not None:@@ -505,6 +539,7 @@ class LiteParse:image_output_dir=cfg.image_output_dir,extract_links=cfg.extract_links,extract_annotations=cfg.extract_annotations,+ extract_form_fields=cfg.extract_form_fields,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.pyindex 159955c..b73c485 100644--- a/packages/python/liteparse/types.py+++ b/packages/python/liteparse/types.py@@ -71,6 +71,28 @@ class DocumentAnnotation:uri: Optional[str] = None+@dataclass+class FormField:+ """One AcroForm widget and its resolved field metadata."""+ id: str+ field_type: str+ page: int+ annotation_index: int+ widget_index: int+ field_flags: int+ object_number: Optional[int] = None+ name: Optional[str] = None+ alternate_name: Optional[str] = None+ value: Optional[str] = None+ export_value: Optional[str] = None+ control_count: Optional[int] = None+ control_index: Optional[int] = None+ checked: Optional[bool] = None+ rect: Optional[AnnotationRect] = None+ options: List[str] = field(default_factory=list)+ selected_options: List[str] = field(default_factory=list)++@dataclassclass ParsedPage:"""A parsed page from a document."""@@ -88,6 +110,8 @@ class ParsedPage:vector_graphics: Optional[VectorGraphics] = None#: Present only when parsing with ``extract_annotations=True``.annotations: Optional[List[DocumentAnnotation]] = None+ #: Present only when parsing with ``extract_form_fields=True``.+ form_fields: Optional[List[FormField]] = None@dataclass@@ -157,6 +181,8 @@ class ParseResult:text: strimages: List[ExtractedImage] = field(default_factory=list)image_error_count: int = 0+ #: PDFium form type, present only when ``extract_form_fields=True``.+ form_type: Optional[int] = None@propertydef num_pages(self) -> int:@@ -246,6 +272,7 @@ class LiteParseConfig:image_output_dir: Optional[str]extract_links: boolextract_annotations: bool+ extract_form_fields: boolocr_failure_fatal: boolocr_hedge_delays_ms: List[int]emit_word_boxes: bool