A fast, helpful, and open-source document parser
Add optional PDF annotation extraction
Pierre-Loic doulcet02e7458bf4e8
diff --git a/README.md b/README.mdindex c11ffda..beb2d96 100644--- a/README.md+++ b/README.md@@ -162,6 +162,9 @@ lit parse document.pdf --no-ocr# Include page-scoped vector path data in JSONlit parse document.pdf --format json --extract-vector-graphics+# Include page annotations in structured JSON+lit parse document.pdf --format json --extract-annotations+# Parse a remote PDFcurl -sL https://example.com/report.pdf | lit parse -```@@ -298,6 +301,7 @@ Options:--image-output-dir <dir> Where to write images when --image-mode embed--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--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 bc9317b..d8df0df 100644--- a/crates/liteparse-napi/src/types.rs+++ b/crates/liteparse-napi/src/types.rs@@ -5,7 +5,7 @@ use napi_derive::napi;use liteparse::config::{CropBox, ImageMode, LiteParseConfig, OutputFormat};use liteparse::parser::ParseResult;use liteparse::types::{- GraphicPrimitive, Page, ParsedPage, Rect, TextItem, VectorGraphics, WordBox,+ DocumentAnnotation, GraphicPrimitive, Page, ParsedPage, Rect, TextItem, VectorGraphics, WordBox,};// ---------------------------------------------------------------------------@@ -54,6 +54,8 @@ pub struct JsLiteParseConfig {/// Render hyperlink annotations as `[text](url)` in markdown output/// (default true). Set false for plain anchor text.pub extract_links: Option<bool>,+ /// Extract all PDF annotations as page-scoped structured data.+ pub extract_annotations: 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.@@ -156,6 +158,9 @@ impl JsLiteParseConfig {if let Some(v) = self.extract_links {cfg.extract_links = v;}+ if let Some(v) = self.extract_annotations {+ cfg.extract_annotations = v;+ }if let Some(v) = self.ocr_failure_fatal {cfg.ocr_failure_fatal = v;}@@ -219,6 +224,7 @@ impl JsLiteParseConfig {extract_images: Some(cfg.extract_images),image_output_dir: cfg.image_output_dir.clone(),extract_links: Some(cfg.extract_links),+ extract_annotations: Some(cfg.extract_annotations),ocr_failure_fatal: Some(cfg.ocr_failure_fatal),ocr_hedge_delays_ms: Some(cfg.ocr_hedge_delays_ms@@ -477,6 +483,7 @@ impl JsPageInput {vector_graphics: None,struct_nodes: Vec::new(),image_refs: Vec::new(),+ annotations: None,}}}@@ -496,6 +503,7 @@ pub struct JsParsedPage {pub text_items: Vec<JsTextItem>,pub complexity: Option<JsPageComplexityStats>,pub vector_graphics: Option<JsVectorGraphics>,+ pub annotations: Option<Vec<JsDocumentAnnotation>>,}#[napi(object)]@@ -518,6 +526,15 @@ pub struct JsRect {pub height: f64,}+#[napi(object)]+#[derive(Clone)]+pub struct JsAnnotationRect {+ pub x: f64,+ pub y: f64,+ pub width: f64,+ pub height: f64,+}+#[napi(object)]#[derive(Clone)]pub struct JsVectorLine {@@ -578,6 +595,49 @@ impl JsVectorGraphics {}}+impl JsAnnotationRect {+ fn from_rust(rect: &Rect) -> Self {+ Self {+ x: rect.x as f64,+ y: rect.y as f64,+ width: rect.width as f64,+ height: rect.height as f64,+ }+ }+}++#[napi(object)]+#[derive(Clone)]+pub struct JsDocumentAnnotation {+ pub subtype: String,+ pub contents: Option<String>,+ pub created: Option<String>,+ pub modified: Option<String>,+ pub title: Option<String>,+ pub rect: Option<JsAnnotationRect>,+ pub quadpoint_rects: Vec<JsAnnotationRect>,+ pub uri: Option<String>,+}++impl JsDocumentAnnotation {+ fn from_rust(annotation: &DocumentAnnotation) -> Self {+ Self {+ subtype: annotation.subtype.clone(),+ contents: annotation.contents.clone(),+ created: annotation.created.clone(),+ modified: annotation.modified.clone(),+ title: annotation.title.clone(),+ rect: annotation.rect.as_ref().map(JsAnnotationRect::from_rust),+ quadpoint_rects: annotation+ .quadpoint_rects+ .iter()+ .map(JsAnnotationRect::from_rust)+ .collect(),+ uri: annotation.uri.clone(),+ }+ }+}+impl JsParsedPage {pub fn from_rust(page: &ParsedPage, include_text_metadata: bool) -> Self {Self {@@ -599,6 +659,12 @@ impl JsParsedPage {.vector_graphics.as_ref().map(JsVectorGraphics::from_rust),+ annotations: page.annotations.as_ref().map(|annotations| {+ annotations+ .iter()+ .map(JsDocumentAnnotation::from_rust)+ .collect()+ }),}}}diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rsindex 9dab222..df90656 100644--- a/crates/liteparse-python/src/cli.rs+++ b/crates/liteparse-python/src/cli.rs@@ -76,6 +76,9 @@ struct ParseCommand {/// `[text](url)` in markdown output; pass this to emit plain anchor text.#[arg(long)]no_links: bool,+ /// Include all PDF annotations as page-scoped structured data.+ #[arg(long)]+ extract_annotations: bool,/// Include per-page complexity signals as a `complexity` object on each/// page of JSON output. Off by default.#[arg(long)]@@ -244,6 +247,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {extract_images: cmd.extract_images,image_output_dir: cmd.image_output_dir.clone(),extract_links: !cmd.no_links,+ extract_annotations: cmd.extract_annotations,include_complexity: cmd.complexity,include_text_metadata: cmd.include_text_metadata,extract_vector_graphics: cmd.extract_vector_graphics,diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rsindex 7ea5678..8ee44bc 100644--- a/crates/liteparse-python/src/lib.rs+++ b/crates/liteparse-python/src/lib.rs@@ -113,6 +113,70 @@ impl PyTextItem {}}+#[pyclass(frozen, from_py_object)]+#[derive(Clone)]+struct PyAnnotationRect {+ #[pyo3(get)]+ x: f64,+ #[pyo3(get)]+ y: f64,+ #[pyo3(get)]+ width: f64,+ #[pyo3(get)]+ height: f64,+}++impl PyAnnotationRect {+ fn from_rust(rect: liteparse::types::Rect) -> Self {+ Self {+ x: rect.x as f64,+ y: rect.y as f64,+ width: rect.width as f64,+ height: rect.height as f64,+ }+ }+}++#[pyclass(frozen, from_py_object)]+#[derive(Clone)]+struct PyDocumentAnnotation {+ #[pyo3(get)]+ subtype: String,+ #[pyo3(get)]+ contents: Option<String>,+ #[pyo3(get)]+ created: Option<String>,+ #[pyo3(get)]+ modified: Option<String>,+ #[pyo3(get)]+ title: Option<String>,+ #[pyo3(get)]+ rect: Option<PyAnnotationRect>,+ #[pyo3(get)]+ quadpoint_rects: Vec<PyAnnotationRect>,+ #[pyo3(get)]+ uri: Option<String>,+}++impl PyDocumentAnnotation {+ fn from_rust(annotation: liteparse::types::DocumentAnnotation) -> Self {+ Self {+ subtype: annotation.subtype,+ contents: annotation.contents,+ created: annotation.created,+ modified: annotation.modified,+ title: annotation.title,+ rect: annotation.rect.map(PyAnnotationRect::from_rust),+ quadpoint_rects: annotation+ .quadpoint_rects+ .into_iter()+ .map(PyAnnotationRect::from_rust)+ .collect(),+ uri: annotation.uri,+ }+ }+}+impl PyTextItem {fn to_rust(&self) -> liteparse::types::TextItem {liteparse::types::TextItem {@@ -186,6 +250,8 @@ struct PyParsedPage {complexity: Option<PyPageComplexityStats>,#[pyo3(get)]vector_graphics: Option<PyVectorGraphics>,+ #[pyo3(get)]+ annotations: Option<Vec<PyDocumentAnnotation>>,}#[pyclass(frozen, from_py_object)]@@ -320,6 +386,12 @@ impl PyParsedPage {.as_ref().map(PyPageComplexityStats::from_rust),vector_graphics: page.vector_graphics.map(PyVectorGraphics::from_rust),+ annotations: page.annotations.map(|annotations| {+ annotations+ .into_iter()+ .map(PyDocumentAnnotation::from_rust)+ .collect()+ }),}}}@@ -643,6 +715,8 @@ struct PyLiteParseConfig {#[pyo3(get)]extract_links: bool,#[pyo3(get)]+ extract_annotations: bool,+ #[pyo3(get)]ocr_failure_fatal: bool,#[pyo3(get)]ocr_hedge_delays_ms: Vec<u64>,@@ -704,6 +778,7 @@ impl PyLiteParseConfig {ImageMode::Embed => "embed".to_string(),},extract_links: cfg.extract_links,+ extract_annotations: cfg.extract_annotations,ocr_failure_fatal: cfg.ocr_failure_fatal,ocr_hedge_delays_ms: cfg.ocr_hedge_delays_ms.clone(),emit_word_boxes: cfg.emit_word_boxes,@@ -754,6 +829,7 @@ impl LiteParse {extract_images = None,image_output_dir = None,extract_links = None,+ extract_annotations = None,ocr_failure_fatal = None,ocr_hedge_delays_ms = None,emit_word_boxes = None,@@ -781,6 +857,7 @@ impl LiteParse {extract_images: Option<bool>,image_output_dir: Option<String>,extract_links: Option<bool>,+ extract_annotations: Option<bool>,ocr_failure_fatal: Option<bool>,ocr_hedge_delays_ms: Option<Vec<u64>>,emit_word_boxes: Option<bool>,@@ -850,6 +927,9 @@ impl LiteParse {if let Some(v) = extract_links {cfg.extract_links = v;}+ if let Some(v) = extract_annotations {+ cfg.extract_annotations = v;+ }if let Some(v) = ocr_failure_fatal {cfg.ocr_failure_fatal = v;}@@ -1053,6 +1133,8 @@ fn _liteparse(m: &Bound<'_, PyModule>) -> PyResult<()> {m.add_class::<PyParsedPage>()?;m.add_class::<PyTextItem>()?;m.add_class::<PyWordBox>()?;+ m.add_class::<PyAnnotationRect>()?;+ m.add_class::<PyDocumentAnnotation>()?;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 a137845..db355ed 100644--- a/crates/liteparse-wasm/src/lib.rs+++ b/crates/liteparse-wasm/src/lib.rs@@ -56,6 +56,7 @@ pub struct LiteParseConfig {image_mode: Option<String>,extract_images: Option<bool>,extract_links: Option<bool>,+ extract_annotations: Option<bool>,ocr_failure_fatal: Option<bool>,ocr_hedge_delays_ms: Option<Vec<u64>>,preserve_very_small_text: Option<bool>,@@ -142,6 +143,9 @@ impl LiteParseConfig {if let Some(v) = self.extract_links {cfg.extract_links = v;}+ if let Some(v) = self.extract_annotations {+ cfg.extract_annotations = v;+ }if let Some(v) = self.ocr_failure_fatal {cfg.ocr_failure_fatal = v;}@@ -207,6 +211,7 @@ impl LiteParseConfig {}),extract_images: Some(cfg.extract_images),extract_links: Some(cfg.extract_links),+ extract_annotations: Some(cfg.extract_annotations),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),@@ -278,6 +283,8 @@ pub struct ParsedPage {pub complexity: Option<PageComplexityStats>,#[serde(skip_serializing_if = "Option::is_none")]pub vector_graphics: Option<VectorGraphics>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub annotations: Option<Vec<DocumentAnnotation>>,}#[derive(Serialize, Tsify)]@@ -310,6 +317,16 @@ pub struct VectorRect {pub height: f32,}+#[derive(Serialize, Tsify)]+#[tsify(into_wasm_abi)]+#[serde(rename_all = "camelCase")]+pub struct AnnotationRect {+ pub x: f32,+ pub y: f32,+ pub width: f32,+ pub height: f32,+}+#[derive(Serialize, Tsify)]#[tsify(into_wasm_abi)]#[serde(rename_all = "camelCase")]@@ -325,6 +342,47 @@ pub struct VectorLine {pub fill_color: Option<String>,}+#[derive(Serialize, Tsify)]+#[tsify(into_wasm_abi)]+#[serde(rename_all = "camelCase")]+pub struct DocumentAnnotation {+ pub subtype: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub contents: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub created: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub modified: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub rect: Option<AnnotationRect>,+ pub quadpoint_rects: Vec<AnnotationRect>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub uri: Option<String>,+}++impl DocumentAnnotation {+ fn from_rust(annotation: &liteparse::types::DocumentAnnotation) -> Self {+ let to_rect = |rect: &liteparse::types::Rect| AnnotationRect {+ x: rect.x,+ y: rect.y,+ width: rect.width,+ height: rect.height,+ };+ Self {+ subtype: annotation.subtype.clone(),+ contents: annotation.contents.clone(),+ created: annotation.created.clone(),+ modified: annotation.modified.clone(),+ title: annotation.title.clone(),+ rect: annotation.rect.as_ref().map(to_rect),+ quadpoint_rects: annotation.quadpoint_rects.iter().map(to_rect).collect(),+ uri: annotation.uri.clone(),+ }+ }+}+#[derive(Serialize, Tsify)]#[tsify(into_wasm_abi)]#[serde(rename_all = "camelCase")]@@ -613,6 +671,12 @@ impl LiteParse {}).collect(),}),+ annotations: p.annotations.as_ref().map(|annotations| {+ annotations+ .iter()+ .map(DocumentAnnotation::from_rust)+ .collect()+ }),}).collect();diff --git a/crates/liteparse/README.md b/crates/liteparse/README.mdindex c42e768..8016450 100644--- a/crates/liteparse/README.md+++ b/crates/liteparse/README.md@@ -56,6 +56,7 @@ let config = LiteParseConfig {target_pages: Some("1-5,10".into()), // Specific pages (optional)dpi: 150.0, // Rendering DPIoutput_format: OutputFormat::Json, // Json | Text | Markdown+ extract_annotations: false, // Include page annotations in outputpreserve_very_small_text: false, // Keep tiny textinclude_text_metadata: false, // Opt in to rich PDF text metadatapassword: None, // Password for protected documents@@ -66,6 +67,12 @@ let config = LiteParseConfig {let parser = LiteParse::new(config);```+Set `extract_annotations: true` to populate `ParsedPage::annotations` with+annotation subtype, contents, author/title, PDF date strings, viewport-space+rectangle and quadpoint rectangles, and external link URI. It is independent+of `extract_links`, which controls Markdown link rendering. The field is+`None` when extraction is disabled.+## Markdown OutputLiteParse can render documents directly to Markdown, including headings, tables, lists,diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rsindex d8ae2e2..1cbabbe 100644--- a/crates/liteparse/src/config.rs+++ b/crates/liteparse/src/config.rs@@ -45,6 +45,10 @@ pub struct LiteParseConfig {/// markdown output. Default on. Disable for benchmark parity with/// plain-text ground truth (the GT corpora never use link syntax).pub extract_links: bool,+ /// Extract all PDF annotations into each parsed page. Default `false`.+ /// This is independent of `extract_links`, which only controls Markdown+ /// link reconstruction.+ pub extract_annotations: 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@@ -164,6 +168,7 @@ impl Default for LiteParseConfig {extract_images: false,image_output_dir: None,extract_links: true,+ extract_annotations: 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 7ea49b3..f9591dd 100644--- a/crates/liteparse/src/extract.rs+++ b/crates/liteparse/src/extract.rs@@ -1,8 +1,9 @@use crate::error::LiteParseError;use crate::glyph_names::resolve_glyph_name;use crate::types::{- ExtractedImage, GraphicPrimitive, ImageRef, OutlineTarget, Page as LitePage, PdfInput, Rect,- StructNode, TextItem, VectorGraphics, VectorLine, VectorShape, WordBox,+ DocumentAnnotation, ExtractedImage, GraphicPrimitive, ImageRef, OutlineTarget,+ Page as LitePage, PdfInput, Rect, StructNode, TextItem, VectorGraphics, VectorLine,+ VectorShape, WordBox,};use image::ImageEncoder;use pdfium::{@@ -122,6 +123,25 @@ pub(crate) fn extract_pages_and_images(let extracted_refs = extract_page_image_refs(&page, page_number, render_images);let mut image_refs = extracted_refs.refs;image_error_count += extracted_refs.error_count;+ let annotations = output_options.extract_annotations.then(|| {+ page.annotations(&view_box)+ .into_iter()+ .map(|annotation| DocumentAnnotation {+ subtype: annotation.subtype,+ contents: annotation.contents,+ created: annotation.created,+ modified: annotation.modified,+ title: annotation.title,+ rect: annotation.rect.map(rect_from_pdfium),+ quadpoint_rects: annotation+ .quadpoint_rects+ .into_iter()+ .map(rect_from_pdfium)+ .collect(),+ uri: annotation.uri,+ })+ .collect()+ });if render_images && !image_refs.is_empty() {let rendered = render_page_images(&page, page_number, &image_refs, &mut image_cache);@@ -142,6 +162,7 @@ pub(crate) fn extract_pages_and_images(vector_graphics,struct_nodes,image_refs,+ annotations,});}@@ -152,6 +173,16 @@ pub(crate) fn extract_pages_and_images(pub(crate) struct ExtractionOutputOptions {pub emit_word_boxes: bool,pub extract_vector_graphics: bool,+ pub extract_annotations: bool,+}++fn rect_from_pdfium(rect: RectF) -> Rect {+ Rect {+ x: rect.left,+ y: rect.top,+ width: rect.right - rect.left,+ height: rect.bottom - rect.top,+ }}/// Assign hyperlink URIs to text items whose bbox center falls inside a link@@ -2464,6 +2495,7 @@ mod tests {vector_graphics: None,struct_nodes: Vec::new(),image_refs: Vec::new(),+ annotations: None,}}diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rsindex a3e00b1..f82c294 100644--- a/crates/liteparse/src/main.rs+++ b/crates/liteparse/src/main.rs@@ -123,6 +123,10 @@ struct ParseCommand {#[arg(long)]no_links: bool,+ /// Include all PDF annotations as page-scoped structured JSON/API data.+ #[arg(long)]+ extract_annotations: 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.@@ -236,6 +240,10 @@ struct BatchParseCommand {/// Include page-scoped vector shapes and merged horizontal/vertical lines.#[arg(long)]extract_vector_graphics: bool,++ /// Include all PDF annotations as page-scoped structured JSON/API data.+ #[arg(long)]+ extract_annotations: bool,}#[derive(Args, Debug)]@@ -355,6 +363,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {extract_images: cmd.extract_images,image_output_dir: cmd.image_output_dir.clone(),extract_links: !cmd.no_links,+ extract_annotations: cmd.extract_annotations,include_complexity: cmd.complexity,include_text_metadata: cmd.include_text_metadata,extract_vector_graphics: cmd.extract_vector_graphics,@@ -455,6 +464,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {include_text_metadata: cmd.include_text_metadata,extract_images: cmd.extract_images,extract_vector_graphics: cmd.extract_vector_graphics,+ extract_annotations: cmd.extract_annotations,..Default::default()};if let Some(n) = cmd.num_workers {diff --git a/crates/liteparse/src/markdown_layout/test_helpers.rs b/crates/liteparse/src/markdown_layout/test_helpers.rsindex 1d3e990..dc48398 100644--- a/crates/liteparse/src/markdown_layout/test_helpers.rs+++ b/crates/liteparse/src/markdown_layout/test_helpers.rs@@ -44,6 +44,7 @@ pub(crate) fn page(lines: Vec<ProjectedLine>) -> ParsedPage {struct_nodes: vec![],image_refs: vec![],complexity: None,+ annotations: None,}}@@ -196,6 +197,7 @@ pub(crate) fn header_footer_page(n: usize, header: &str, footer: &str, body: &ststruct_nodes: vec![],image_refs: vec![],complexity: None,+ annotations: None,}}diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rsindex c17ad29..a369664 100644--- a/crates/liteparse/src/ocr_merge.rs+++ b/crates/liteparse/src/ocr_merge.rs@@ -1165,6 +1165,7 @@ mod tests {vector_graphics: None,struct_nodes: Vec::new(),image_refs: Vec::new(),+ annotations: None,}}@@ -1198,6 +1199,7 @@ mod tests {vector_graphics: None,struct_nodes: Vec::new(),image_refs: Vec::new(),+ annotations: None,}}@@ -1222,6 +1224,7 @@ mod tests {vector_graphics: None,struct_nodes: Vec::new(),image_refs: Vec::new(),+ annotations: None,}}diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rsindex 106b4c5..6ecc458 100644--- a/crates/liteparse/src/output/json.rs+++ b/crates/liteparse/src/output/json.rs@@ -1,5 +1,5 @@use crate::ocr_merge::PageComplexityStats;-use crate::types::{ExtractedImage, ParsedPage, Rect, VectorGraphics};+use crate::types::{DocumentAnnotation, ExtractedImage, ParsedPage, Rect, VectorGraphics};use serde::Serialize;#[derive(Debug, Serialize)]@@ -52,6 +52,8 @@ pub(crate) struct JsonPage {pub complexity: Option<PageComplexityStats>,#[serde(skip_serializing_if = "Option::is_none")]pub vector_graphics: Option<VectorGraphics>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub annotations: Option<Vec<DocumentAnnotation>>,}#[derive(Debug, Serialize)]@@ -131,6 +133,7 @@ pub(crate) fn build_json(pages: &[ParsedPage], include_text_metadata: bool) -> P.collect(),complexity: page.complexity.clone(),vector_graphics: page.vector_graphics.clone(),+ annotations: page.annotations.clone(),}).collect(),}@@ -181,7 +184,7 @@ pub fn format_json_with_text_metadata(#[cfg(test)]mod tests {use super::*;- use crate::types::{ParsedPage, TextItem};+ use crate::types::{DocumentAnnotation, ParsedPage, Rect, TextItem};fn item(text: &str, conf: Option<f32>) -> TextItem {TextItem {@@ -213,6 +216,7 @@ mod tests {struct_nodes: vec![],image_refs: vec![],complexity: None,+ annotations: None,}}@@ -356,4 +360,33 @@ mod tests {assert!(enabled_json.contains("\"has_curve\": true"));assert!(enabled_json.contains("\"stroke_color\": \"ff000000\""));}++ #[test]+ fn test_annotations_are_omitted_when_disabled() {+ let value = serde_json::to_value(build_json(&[page(vec![])], false)).unwrap();+ assert!(value["pages"][0].get("annotations").is_none());+ }++ #[test]+ fn test_annotations_are_serialized_when_enabled() {+ let mut parsed_page = page(vec![]);+ parsed_page.annotations = Some(vec![DocumentAnnotation {+ subtype: "highlight".into(),+ contents: Some("review this".into()),+ created: None,+ modified: None,+ title: Some("Reviewer".into()),+ rect: Some(Rect {+ x: 10.0,+ y: 20.0,+ width: 90.0,+ height: 20.0,+ }),+ quadpoint_rects: vec![],+ uri: None,+ }]);+ let value = serde_json::to_value(build_json(&[parsed_page], false)).unwrap();+ assert_eq!(value["pages"][0]["annotations"][0]["subtype"], "highlight");+ assert_eq!(value["pages"][0]["annotations"][0]["rect"]["width"], 90.0);+ }}diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rsindex 2b1606d..2edc340 100644--- a/crates/liteparse/src/output/markdown.rs+++ b/crates/liteparse/src/output/markdown.rs@@ -160,6 +160,7 @@ mod tests {struct_nodes: vec![],image_refs: vec![],complexity: None,+ annotations: None,}}@@ -210,6 +211,7 @@ mod tests {struct_nodes: vec![],image_refs: vec![],complexity: None,+ annotations: 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 190494e..d548610 100644--- a/crates/liteparse/src/output/text.rs+++ b/crates/liteparse/src/output/text.rs@@ -29,6 +29,7 @@ mod tests {struct_nodes: vec![],image_refs: vec![],complexity: None,+ annotations: None,}}diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rsindex ca525c9..5366eaf 100644--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@ -364,6 +364,7 @@ impl LiteParse {extract::ExtractionOutputOptions {emit_word_boxes: self.config.emit_word_boxes,extract_vector_graphics: self.config.extract_vector_graphics,+ extract_annotations: self.config.extract_annotations,},)?;let t_extract = web_time::Instant::now();diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rsindex d627899..9dc0aba 100644--- a/crates/liteparse/src/projection.rs+++ b/crates/liteparse/src/projection.rs@@ -2915,6 +2915,7 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {struct_nodes: page.struct_nodes,image_refs: page.image_refs,complexity: None,+ annotations: page.annotations,}}).collect()@@ -5006,6 +5007,7 @@ mod tests {text_items: Vec::new(),struct_nodes: Vec::new(),image_refs: Vec::new(),+ annotations: None,};let projection_boxes = vec![projected_item("", 10.0, 0.0, 10.0),@@ -5308,6 +5310,7 @@ mod tests {vector_graphics: None,struct_nodes: Vec::new(),image_refs: Vec::new(),+ annotations: None,}];let parsed = project_pages_to_grid(pages);@@ -5346,6 +5349,7 @@ mod tests {vector_graphics: None,struct_nodes: Vec::new(),image_refs: Vec::new(),+ annotations: None,}];let parsed = project_pages_to_grid(pages);@@ -5407,6 +5411,7 @@ mod tests {vector_graphics: None,struct_nodes: Vec::new(),image_refs: Vec::new(),+ annotations: None,}];let parsed = project_pages_to_grid(pages);@@ -5448,6 +5453,7 @@ mod tests {vector_graphics: None,struct_nodes: Vec::new(),image_refs: Vec::new(),+ annotations: None,}];let parsed = project_pages_to_grid(pages);diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rsindex 1609b08..354c2c1 100644--- a/crates/liteparse/src/types.rs+++ b/crates/liteparse/src/types.rs@@ -123,6 +123,31 @@ pub struct Page {/// images. Threaded through to `ParsedPage.image_refs`.#[serde(skip)]pub image_refs: Vec<ImageRef>,+ /// Public annotation data when explicitly requested. `None` distinguishes+ /// disabled extraction from an enabled page with no annotations.+ #[serde(skip)]+ pub annotations: Option<Vec<DocumentAnnotation>>,+}++/// One PDF page annotation. Coordinates use the same top-left, 72-DPI+/// viewport space as [`TextItem`].+#[derive(Debug, Clone, Serialize)]+pub struct DocumentAnnotation {+ pub subtype: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub contents: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub created: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub modified: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub rect: Option<Rect>,+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub quadpoint_rects: Vec<Rect>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub uri: Option<String>,}/// One entry in the document outline (bookmarks). Coordinates are in PDF@@ -201,6 +226,11 @@ pub struct ParsedPage {/// `None` otherwise. Surfaced as a per-page `complexity` object in JSON.#[serde(skip_serializing_if = "Option::is_none")]pub complexity: Option<crate::ocr_merge::PageComplexityStats>,+ /// Page annotations when `LiteParseConfig::extract_annotations` is true.+ /// `None` means extraction was disabled; `Some([])` means enabled with no+ /// annotations on this page.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub annotations: Option<Vec<DocumentAnnotation>>,}/// One embedded raster image on a page. `id` is a stable, page-scoped slug@@ -507,6 +537,7 @@ mod tests {vector_graphics: None,struct_nodes: vec![],image_refs: vec![],+ annotations: 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 194692f..0ad7ad5 100644--- a/crates/pdfium-sys/src/dynamic.rs+++ b/crates/pdfium-sys/src/dynamic.rs@@ -306,6 +306,23 @@ pub struct PdfiumBindings {pub FPDFLink_CountQuadPoints: unsafe extern "C" fn(FPDF_LINK) -> std::os::raw::c_int,pub FPDFLink_GetQuadPoints:unsafe extern "C" fn(FPDF_LINK, std::os::raw::c_int, *mut FS_QUADPOINTSF) -> FPDF_BOOL,+ // -- Annotations --+ pub FPDFPage_GetAnnotCount: unsafe extern "C" fn(FPDF_PAGE) -> std::os::raw::c_int,+ pub FPDFPage_GetAnnot: unsafe extern "C" fn(FPDF_PAGE, std::os::raw::c_int) -> FPDF_ANNOTATION,+ pub FPDFPage_CloseAnnot: unsafe extern "C" fn(FPDF_ANNOTATION),+ pub FPDFAnnot_GetSubtype: unsafe extern "C" fn(FPDF_ANNOTATION) -> FPDF_ANNOTATION_SUBTYPE,+ pub FPDFAnnot_GetStringValue: unsafe extern "C" fn(+ FPDF_ANNOTATION,+ FPDF_BYTESTRING,+ *mut FPDF_WCHAR,+ std::os::raw::c_ulong,+ ) -> std::os::raw::c_ulong,+ pub FPDFAnnot_GetRect: unsafe extern "C" fn(FPDF_ANNOTATION, *mut FS_RECTF) -> FPDF_BOOL,+ pub FPDFAnnot_HasAttachmentPoints: unsafe extern "C" fn(FPDF_ANNOTATION) -> FPDF_BOOL,+ pub FPDFAnnot_CountAttachmentPoints: unsafe extern "C" fn(FPDF_ANNOTATION) -> usize,+ 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 FPDFDest_GetDestPageIndex:unsafe extern "C" fn(FPDF_DOCUMENT, FPDF_DEST) -> std::os::raw::c_int,pub FPDFDest_GetLocationInPage: unsafe extern "C" fn(@@ -458,6 +475,16 @@ impl PdfiumBindings {FPDFLink_GetAnnotRect: load_fn!(lib, "FPDFLink_GetAnnotRect"),FPDFLink_CountQuadPoints: load_fn!(lib, "FPDFLink_CountQuadPoints"),FPDFLink_GetQuadPoints: load_fn!(lib, "FPDFLink_GetQuadPoints"),+ FPDFPage_GetAnnotCount: load_fn!(lib, "FPDFPage_GetAnnotCount"),+ FPDFPage_GetAnnot: load_fn!(lib, "FPDFPage_GetAnnot"),+ FPDFPage_CloseAnnot: load_fn!(lib, "FPDFPage_CloseAnnot"),+ FPDFAnnot_GetSubtype: load_fn!(lib, "FPDFAnnot_GetSubtype"),+ FPDFAnnot_GetStringValue: load_fn!(lib, "FPDFAnnot_GetStringValue"),+ FPDFAnnot_GetRect: load_fn!(lib, "FPDFAnnot_GetRect"),+ FPDFAnnot_HasAttachmentPoints: load_fn!(lib, "FPDFAnnot_HasAttachmentPoints"),+ FPDFAnnot_CountAttachmentPoints: load_fn!(lib, "FPDFAnnot_CountAttachmentPoints"),+ FPDFAnnot_GetAttachmentPoints: load_fn!(lib, "FPDFAnnot_GetAttachmentPoints"),+ FPDFAnnot_GetLink: load_fn!(lib, "FPDFAnnot_GetLink"),FPDFDest_GetDestPageIndex: load_fn!(lib, "FPDFDest_GetDestPageIndex"),FPDFDest_GetLocationInPage: load_fn!(lib, "FPDFDest_GetLocationInPage"),diff --git a/crates/pdfium/src/lib.rs b/crates/pdfium/src/lib.rsindex 6cdbc6f..2e5de24 100644--- a/crates/pdfium/src/lib.rs+++ b/crates/pdfium/src/lib.rs@@ -14,8 +14,8 @@ pub use error::PdfiumError;pub use font::{Font, FontType};pub use library::Library;pub use page::{- ImageBounds, ImageObjectInfo, ImageObjects, Page, PathObject, PathSegment, PdfLink,- SegmentKind, ViewportTransform,+ ImageBounds, ImageObjectInfo, ImageObjects, Page, PathObject, PathSegment, PdfAnnotation,+ 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 166f588..54a2d49 100644--- a/crates/pdfium/src/page.rs+++ b/crates/pdfium/src/page.rs@@ -181,6 +181,20 @@ pub struct PdfLink {pub uri: String,}+/// One PDF annotation with geometry normalized to viewport space (top-left+/// origin, 72 DPI). String fields mirror the standard annotation dictionary.+#[derive(Debug, Clone)]+pub struct PdfAnnotation {+ pub subtype: String,+ pub contents: Option<String>,+ pub created: Option<String>,+ pub modified: Option<String>,+ pub title: Option<String>,+ pub rect: Option<RectF>,+ pub quadpoint_rects: Vec<RectF>,+ pub uri: Option<String>,+}+/// A loaded page within a [`Document`].////// The `'doc` lifetime ties the page to its owning document; `'lib` carries@@ -662,6 +676,162 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {}out}++ /// Enumerate all page annotations. Unlike [`Page::links`], this preserves+ /// non-link subtypes and annotation dictionary metadata for public output.+ pub fn annotations(&self, view_box: &RectF) -> Vec<PdfAnnotation> {+ let count = unsafe { ffi!(FPDFPage_GetAnnotCount(self.handle)) };+ let mut out = Vec::with_capacity(count.max(0) as usize);+ for index in 0..count {+ let annot = unsafe { ffi!(FPDFPage_GetAnnot(self.handle, index)) };+ if annot.is_null() {+ continue;+ }++ let subtype = unsafe { ffi!(FPDFAnnot_GetSubtype(annot)) };+ let mut rect = pdfium_sys::FS_RECTF::default();+ let rect = if unsafe { ffi!(FPDFAnnot_GetRect(annot, &mut rect)) } != 0 {+ Some(self.bounds_to_viewport(+ view_box,+ &RectF {+ left: rect.left,+ top: rect.top,+ right: rect.right,+ bottom: rect.bottom,+ },+ ))+ } else {+ None+ };++ let mut quadpoint_rects = Vec::new();+ if unsafe { ffi!(FPDFAnnot_HasAttachmentPoints(annot)) } != 0 {+ let quad_count = unsafe { ffi!(FPDFAnnot_CountAttachmentPoints(annot)) };+ quadpoint_rects.reserve(quad_count);+ for quad_index in 0..quad_count {+ let mut quad = pdfium_sys::FS_QUADPOINTSF::default();+ if unsafe { ffi!(FPDFAnnot_GetAttachmentPoints(annot, quad_index, &mut quad)) }+ == 0+ {+ continue;+ }+ let bounds = RectF {+ left: quad.x1.min(quad.x2).min(quad.x3).min(quad.x4),+ bottom: quad.y1.min(quad.y2).min(quad.y3).min(quad.y4),+ right: quad.x1.max(quad.x2).max(quad.x3).max(quad.x4),+ top: quad.y1.max(quad.y2).max(quad.y3).max(quad.y4),+ };+ quadpoint_rects.push(self.bounds_to_viewport(view_box, &bounds));+ }+ }++ let uri = if subtype == pdfium_sys::FPDF_ANNOT_LINK as i32 {+ let link = unsafe { ffi!(FPDFAnnot_GetLink(annot)) };+ if link.is_null() {+ None+ } else {+ let action = unsafe { ffi!(FPDFLink_GetAction(link)) };+ if action.is_null() {+ None+ } else {+ read_uri_path(self.doc_handle, action)+ }+ }+ } else {+ None+ };++ out.push(PdfAnnotation {+ subtype: annotation_subtype_name(subtype).to_string(),+ contents: read_annotation_string(annot, b"Contents\0"),+ created: read_annotation_string(annot, b"CreationDate\0"),+ modified: read_annotation_string(annot, b"M\0"),+ title: read_annotation_string(annot, b"T\0"),+ rect,+ quadpoint_rects,+ uri,+ });+ unsafe { ffi!(FPDFPage_CloseAnnot(annot)) };+ }+ out+ }+}++fn annotation_subtype_name(subtype: pdfium_sys::FPDF_ANNOTATION_SUBTYPE) -> &'static str {+ const NAMES: [&str; 29] = [+ "unknown",+ "text",+ "link",+ "freetext",+ "line",+ "square",+ "circle",+ "polygon",+ "polyline",+ "highlight",+ "underline",+ "squiggly",+ "strikeout",+ "stamp",+ "caret",+ "ink",+ "popup",+ "fileattachment",+ "sound",+ "movie",+ "widget",+ "screen",+ "printermark",+ "trapnet",+ "watermark",+ "threed",+ "richmedia",+ "xfawidget",+ "redact",+ ];+ usize::try_from(subtype)+ .ok()+ .and_then(|index| NAMES.get(index))+ .copied()+ .unwrap_or("unknown")+}++fn read_annotation_string(+ annot: pdfium_sys::FPDF_ANNOTATION,+ key: &'static [u8],+) -> Option<String> {+ let key = key.as_ptr().cast();+ let needed = unsafe {+ ffi!(FPDFAnnot_GetStringValue(+ annot,+ key,+ std::ptr::null_mut(),+ 0+ ))+ } as usize;+ if needed < 2 {+ return None;+ }+ let mut buf = vec![0u16; needed.div_ceil(2)];+ let written = unsafe {+ ffi!(FPDFAnnot_GetStringValue(+ annot,+ key,+ buf.as_mut_ptr(),+ needed as std::os::raw::c_ulong+ ))+ } as usize;+ if written < 2 {+ return None;+ }+ let units = (written / 2).min(buf.len());+ let end = if buf.get(units.saturating_sub(1)) == Some(&0) {+ units.saturating_sub(1)+ } else {+ units+ };+ let value = String::from_utf16_lossy(&buf[..end]);+ if value.is_empty() { None } else { Some(value) }}/// Read a link action's URI path. PDFium returns the URI as a NUL-terminated@@ -1119,6 +1289,7 @@ impl Drop for Page<'_, '_> {#[cfg(test)]mod tests {use super::*;+ use crate::Library;#[test]fn nested_form_matrix_composition_transforms_path_points_in_order() {@@ -1164,4 +1335,63 @@ mod tests {};assert_eq!(viewport.transform_point(x, y), (110.0, 159.0));}++ fn annotation_pdf() -> Vec<u8> {+ let objects = [+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [4 0 R 5 0 R] >>",+ "<< /Type /Annot /Subtype /Highlight /Rect [10 20 100 40] /QuadPoints [10 40 100 40 10 20 100 20] /Contents (review this) /T (Reviewer) /CreationDate (D:20260102030405Z) /M (D:20260103040506Z) >>",+ "<< /Type /Annot /Subtype /Link /Rect [10 50 100 70] /Border [0 0 0] /A << /S /URI /URI (https://example.com) >> >>",+ ];+ let mut pdf = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::with_capacity(objects.len());+ for (index, object) in objects.iter().enumerate() {+ offsets.push(pdf.len());+ pdf.extend_from_slice(format!("{} 0 obj\n{}\nendobj\n", index + 1, object).as_bytes());+ }+ let xref = pdf.len();+ pdf.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());+ pdf.extend_from_slice(b"0000000000 65535 f \n");+ for offset in offsets {+ pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());+ }+ pdf.extend_from_slice(+ format!(+ "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",+ objects.len() + 1+ )+ .as_bytes(),+ );+ }++ #[test]+ fn extracts_annotation_metadata_geometry_and_link_uri() {+ let bytes = annotation_pdf();+ let library = Library::init();+ let document = library.load_document_from_bytes(&bytes, None).unwrap();+ let page = document.page(0).unwrap();+ let view_box = page.view_box().unwrap();+ let annotations = page.annotations(&view_box);++ assert_eq!(annotations.len(), 2);+ let highlight = &annotations[0];+ assert_eq!(highlight.subtype, "highlight");+ assert_eq!(highlight.contents.as_deref(), Some("review this"));+ assert_eq!(highlight.title.as_deref(), Some("Reviewer"));+ assert_eq!(highlight.created.as_deref(), Some("D:20260102030405Z"));+ assert_eq!(highlight.modified.as_deref(), Some("D:20260103040506Z"));+ let rect = highlight.rect.as_ref().unwrap();+ assert_eq!(+ (rect.left, rect.top, rect.right, rect.bottom),+ (10.0, 160.0, 100.0, 180.0)+ );+ assert_eq!(highlight.quadpoint_rects.len(), 1);++ let link = &annotations[1];+ assert_eq!(link.subtype, "link");+ assert_eq!(link.uri.as_deref(), Some("https://example.com"));+ assert_eq!(link.rect.as_ref().unwrap().top, 130.0);+ }}diff --git a/packages/node/README.md b/packages/node/README.mdindex c699cb6..db5dd9f 100644--- a/packages/node/README.md+++ b/packages/node/README.md@@ -62,6 +62,7 @@ const parser = new LiteParse({imageOutputDir: './images', // Write images and return name/path metadata (optional)extractLinks: true, // Render [text](url) links in markdown outputextractVectorGraphics: false, // Opt-in shapes + merged H/V lines per page+ extractAnnotations: false, // Include page annotations in structured outputpreserveVerySmallText: false, // Keep tiny textincludeTextMetadata: false, // Opt in to MCID, font metrics, colors, char codes, and tsgpassword: undefined, // Password for protected documents@@ -78,6 +79,12 @@ one file, and JSON CLI output contains metadata only—never base64 image data.(`imageMode: "placeholder"`, `extractImages: false`), only lightweight Markdownplacement refs are collected and `result.images` stays empty.+When `extractAnnotations` is enabled, each parsed page has an `annotations`+array containing the subtype, contents, author/title, PDF date strings,+viewport-space rectangle and quadpoint rectangles, and URI for external link+annotations. It is independent of `extractLinks`, which controls Markdown link+rendering. The field is omitted when extraction is disabled.+## Parsing from BytesPass a `Buffer` or `Uint8Array` directly — useful for HTTP responses or in-memory data:@@ -145,6 +152,7 @@ The npm package includes the `lit` CLI:```bashlit parse document.pdflit parse document.pdf --format json -o output.json+lit parse document.pdf --format json --extract-annotationslit 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 85f71a7..cb0bcd2 100644--- a/packages/node/native.d.ts+++ b/packages/node/native.d.ts@@ -46,6 +46,8 @@ export interface JsLiteParseConfig {* (default true). Set false for plain anchor text.*/extractLinks?: boolean+ /** Extract all PDF annotations as page-scoped structured data. */+ extractAnnotations?: boolean/*** Whether a systemic OCR failure aborts the whole parse (default true).* Set false to keep already-recovered native text and return partial@@ -185,6 +187,23 @@ export interface JsParsedPage {markdown: stringtextItems: Array<JsTextItem>complexity?: JsPageComplexityStats+ annotations?: Array<JsDocumentAnnotation>+}+export interface JsAnnotationRect {+ x: number+ y: number+ width: number+ height: number+}+export interface JsDocumentAnnotation {+ subtype: string+ contents?: string+ created?: string+ modified?: string+ title?: string+ rect?: JsAnnotationRect+ quadpointRects: Array<JsAnnotationRect>+ uri?: string}export interface JsParseResult {pages: Array<JsParsedPage>@@ -217,6 +236,16 @@ export interface JsScreenshotResult {height: numberimageBuffer: Buffer}+export interface JsLayoutComplexityStats {+ columnCount: number+ ruledTableCount: number+ ruledTableCoverage: number+ textTableRunCount: number+ figureCount: number+ figureCoverage: number+ isComplex: boolean+ reasons: Array<string>+}export interface JsPageComplexityStats {pageNumber: numbertextLength: number@@ -231,6 +260,7 @@ export interface JsPageComplexityStats {pageArea: numberneedsOcr: booleanreasons: Array<string>+ layout?: JsLayoutComplexityStats}/** Search text items for phrase matches, returning merged items with combined bounding boxes. */export declare function searchItems(items: Array<JsTextItem>, phrase: string, caseSensitive?: boolean | undefined | null): Array<JsTextItem>diff --git a/packages/node/src/cli.ts b/packages/node/src/cli.tsindex bdf3fa8..80bdff5 100644--- a/packages/node/src/cli.ts+++ b/packages/node/src/cli.ts@@ -64,6 +64,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("--ocr-server-url <url>", "HTTP OCR server URL").option("--ocr-server-header <header>",@@ -115,6 +116,7 @@ programconfig.imageOutputDir = opts.imageOutputDir as string;if (opts.extractImages) config.extractImages = true;if (opts.links === false) config.extractLinks = false;+ if (opts.extractAnnotations) config.extractAnnotations = true;if (opts.ocrServerUrl)config.ocrServerUrl = opts.ocrServerUrl as string;if (opts.ocrServerHeader)@@ -149,6 +151,7 @@ programtext: p.text,textItems: p.textItems,...(p.vectorGraphics ? { vectorGraphics: p.vectorGraphics } : {}),+ ...(p.annotations ? { annotations: p.annotations } : {}),})),images: result.images.map(({ bytes: _bytes, ...image }) => image),imageErrorCount: result.imageErrorCount,diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.tsindex 7c1890d..0449f6a 100644--- a/packages/node/src/lib.ts+++ b/packages/node/src/lib.ts@@ -37,6 +37,8 @@ export interface LiteParseConfig {imageOutputDir?: string;/** Render hyperlink annotations as `[text](url)` in markdown output (default: true). */extractLinks: boolean;+ /** Extract all PDF annotations into each parsed page (default: false). */+ extractAnnotations: boolean;preserveVerySmallText: boolean;password?: string;quiet: boolean;@@ -202,6 +204,8 @@ export interface ParsedPage {complexity?: PageComplexityStats;/** Present only when parsing with `extractVectorGraphics: true`. */vectorGraphics?: VectorGraphics;+ /** Present only when `extractAnnotations` is enabled. */+ annotations?: DocumentAnnotation[];}export interface VectorGraphics {@@ -227,6 +231,24 @@ export interface VectorLine {fillColor?: string;}+export interface AnnotationRect {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface DocumentAnnotation {+ subtype: string;+ contents?: string;+ created?: string;+ modified?: string;+ title?: string;+ rect?: AnnotationRect;+ quadpointRects: AnnotationRect[];+ uri?: string;+}+export interface ExtractedImage {/** Reference id used in the markdown output (e.g. `` → `"p1_0"`). */id: string;@@ -363,6 +385,7 @@ export class LiteParse {extractImages: userConfig.extractImages,imageOutputDir: userConfig.imageOutputDir,extractLinks: userConfig.extractLinks,+ extractAnnotations: userConfig.extractAnnotations,preserveVerySmallText: userConfig.preserveVerySmallText,password: userConfig.password,quiet: userConfig.quiet,@@ -395,6 +418,7 @@ export class LiteParse {extractImages: resolved.extractImages ?? false,imageOutputDir: resolved.imageOutputDir ?? undefined,extractLinks: resolved.extractLinks ?? true,+ extractAnnotations: resolved.extractAnnotations ?? false,preserveVerySmallText: resolved.preserveVerySmallText ?? false,password: resolved.password ?? undefined,quiet: resolved.quiet ?? false,@@ -522,6 +546,7 @@ function toPage(p: NativeParsedPage): ParsedPage {textItems: p.textItems.map(toTextItem),complexity: p.complexity ? toComplexity(p.complexity) : undefined,vectorGraphics: p.vectorGraphics ?? undefined,+ annotations: p.annotations,};}diff --git a/packages/node/src/native.ts b/packages/node/src/native.tsindex 86fa186..da44ef1 100644--- a/packages/node/src/native.ts+++ b/packages/node/src/native.ts@@ -33,6 +33,7 @@ export interface LiteParseNativeConfig {extractImages?: boolean;imageOutputDir?: string;extractLinks?: boolean;+ extractAnnotations?: boolean;preserveVerySmallText?: boolean;password?: string;quiet?: boolean;@@ -120,6 +121,7 @@ export interface NativeParsedPage {textItems: NativeTextItem[];complexity?: NativePageComplexityStats;vectorGraphics?: NativeVectorGraphics;+ annotations?: NativeDocumentAnnotation[];}export interface NativeVectorGraphics {@@ -138,6 +140,24 @@ export interface NativeVectorGraphics {}>;}+export interface NativeAnnotationRect {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface NativeDocumentAnnotation {+ subtype: string;+ contents?: string;+ created?: string;+ modified?: string;+ title?: string;+ rect?: NativeAnnotationRect;+ quadpointRects: NativeAnnotationRect[];+ uri?: string;+}+export interface NativeExtractedImage {id: string;name: string;diff --git a/packages/python/README.md b/packages/python/README.mdindex 5161536..a4c9103 100644--- a/packages/python/README.md+++ b/packages/python/README.md@@ -61,6 +61,7 @@ parser = LiteParse(image_output_dir="./images", # Write images and return name/path metadata (optional)extract_links=True, # Render [text](url) links in markdown outputextract_vector_graphics=False, # Opt-in shapes + merged H/V lines per page+ extract_annotations=False, # Include page annotations in structured outputpreserve_very_small_text=False, # Keep tiny textinclude_text_metadata=False, # Opt in to MCID, font metrics, colors, char codes, and tsgpassword=None, # Password for protected documents@@ -77,6 +78,12 @@ reuse one file, and JSON CLI output contains metadata only—never base64 image(``image_mode="placeholder"``, ``extract_images=False``), only lightweight Markdownplacement refs are collected and ``result.images`` stays empty.+When `extract_annotations` is enabled, each parsed page has an `annotations`+list containing the subtype, contents, author/title, PDF date strings,+viewport-space rectangle and quadpoint rectangles, and URI for external link+annotations. It is independent of `extract_links`, which controls Markdown+link rendering. The field is `None` when extraction is disabled.+## Parsing from BytesPass raw PDF bytes directly — useful for web uploads or downloaded files:@@ -141,6 +148,7 @@ The Python package includes the `lit` CLI:```bashlit parse document.pdflit parse document.pdf --format json -o output.json+lit parse document.pdf --format json --extract-annotationslit 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 2617d22..801dd8b 100644--- a/packages/python/liteparse/__init__.py+++ b/packages/python/liteparse/__init__.py@@ -2,6 +2,8 @@ from importlib.metadata import PackageNotFoundError, versionfrom .parser import LiteParse, search_itemsfrom .types import (+ AnnotationRect,+ DocumentAnnotation,ExtractedImage,ImageRect,LayoutComplexityStats,@@ -24,6 +26,8 @@ except PackageNotFoundError: # source tree without installed dist metadata__version__ = "0.0.0+unknown"__all__ = ["LiteParse",+ "AnnotationRect",+ "DocumentAnnotation","LiteParseConfig","ParseResult","ParsedPage",diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.pyindex c8a1545..5fd9c97 100644--- a/packages/python/liteparse/parser.py+++ b/packages/python/liteparse/parser.py@@ -7,6 +7,8 @@ from liteparse._liteparse import LiteParse as _NativeLiteParsefrom liteparse._liteparse import search_items as _native_search_itemsfrom .types import (+ AnnotationRect,+ DocumentAnnotation,ExtractedImage,ImageRect,LayoutComplexityStats,@@ -98,6 +100,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)pages.append(ParsedPage(page_num=native_page.page_num,@@ -142,6 +145,40 @@ def _convert_native_result(native_result: Any) -> ParseResult:if native_vectors is not Noneelse None),+ annotations=(+ [+ DocumentAnnotation(+ subtype=annotation.subtype,+ contents=annotation.contents,+ created=annotation.created,+ modified=annotation.modified,+ title=annotation.title,+ rect=(+ AnnotationRect(+ x=annotation.rect.x,+ y=annotation.rect.y,+ width=annotation.rect.width,+ height=annotation.rect.height,+ )+ if annotation.rect is not None+ else None+ ),+ quadpoint_rects=[+ AnnotationRect(+ x=rect.x,+ y=rect.y,+ width=rect.width,+ height=rect.height,+ )+ for rect in annotation.quadpoint_rects+ ],+ uri=annotation.uri,+ )+ for annotation in native_annotations+ ]+ if native_annotations is not None+ else None+ ),))images = [@@ -206,6 +243,7 @@ class LiteParse:extract_images: Optional[bool] = None,image_output_dir: Optional[Union[str, Path]] = None,extract_links: Optional[bool] = None,+ extract_annotations: Optional[bool] = None,ocr_failure_fatal: Optional[bool] = None,ocr_hedge_delays_ms: Optional[List[int]] = None,emit_word_boxes: Optional[bool] = None,@@ -241,6 +279,8 @@ class LiteParse:extract_images: Extract embedded image bytes and metadata. Defaultsto False; ``image_mode="embed"`` and ``image_output_dir`` alsoimply extraction for compatibility.+ extract_annotations: Include all PDF annotations 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@@ -311,6 +351,8 @@ class LiteParse:kwargs["image_output_dir"] = str(image_output_dir)if extract_links is not None:kwargs["extract_links"] = extract_links+ if extract_annotations is not None:+ kwargs["extract_annotations"] = extract_annotationsif ocr_failure_fatal is not None:kwargs["ocr_failure_fatal"] = ocr_failure_fatalif ocr_hedge_delays_ms is not None:@@ -462,6 +504,7 @@ class LiteParse:image_mode=cfg.image_mode,image_output_dir=cfg.image_output_dir,extract_links=cfg.extract_links,+ extract_annotations=cfg.extract_annotations,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 00e8a0a..c6822a3 100644--- a/packages/python/liteparse/types.py+++ b/packages/python/liteparse/types.py@@ -49,6 +49,28 @@ class TextItem:words: List[WordBox] = field(default_factory=list)+@dataclass+class AnnotationRect:+ """Annotation rectangle in top-left, 72-DPI viewport coordinates."""+ x: float+ y: float+ width: float+ height: float+++@dataclass+class DocumentAnnotation:+ """One PDF annotation extracted from a page."""+ subtype: str+ contents: Optional[str] = None+ created: Optional[str] = None+ modified: Optional[str] = None+ title: Optional[str] = None+ rect: Optional[AnnotationRect] = None+ quadpoint_rects: List[AnnotationRect] = field(default_factory=list)+ uri: Optional[str] = None++@dataclassclass ParsedPage:"""A parsed page from a document."""@@ -64,6 +86,8 @@ class ParsedPage:complexity: Optional[PageComplexityStats] = None#: Present only when parsing with ``extract_vector_graphics=True``.vector_graphics: Optional[VectorGraphics] = None+ #: Present only when parsing with ``extract_annotations=True``.+ annotations: Optional[List[DocumentAnnotation]] = None@dataclass@@ -221,6 +245,7 @@ class LiteParseConfig:image_mode: strimage_output_dir: Optional[str]extract_links: bool+ extract_annotations: boolocr_failure_fatal: boolocr_hedge_delays_ms: List[int]emit_word_boxes: booldiff --git a/packages/wasm/README.md b/packages/wasm/README.mdindex b005364..e5070d1 100644--- a/packages/wasm/README.md+++ b/packages/wasm/README.md@@ -69,6 +69,7 @@ All optional, camelCase:| `imageMode` | `"off" \| "placeholder" \| "embed"` | `"placeholder"` | How raster images are surfaced in markdown output || `extractLinks` | `boolean` | `true` | Render hyperlink annotations as `[text](url)` in markdown output || `extractVectorGraphics` | `boolean` | `false` | Include page-scoped shapes and merged horizontal/vertical lines |+| `extractAnnotations` | `boolean` | `false` | Include page annotations and their metadata/geometry in structured output || `preserveVerySmallText` | `boolean` | `false` | Keep tiny text that's normally filtered || `password` | `string` | — | Password for protected PDFs || `quiet` | `boolean` | `false` | Suppress progress logging |