Skip to content

A fast, helpful, and open-source document parser

feat: async python parse(), output page labels

Logan Markewiche00ac4231e0a
diff --git a/README.md b/README.md
index aaaf091..f0ccba1 100644
--- a/README.md
+++ b/README.md
@@ -117,6 +117,135 @@ flowchart LR
style CLI fill:#FFBFF8,color:#000000,stroke:#FF8DF2,stroke-width:1px
```
+## Benchmarks
+
+LiteParse is measured on three public PDF→Markdown benchmarks, each with its own harness and
+scorer used unmodified. All numbers below are **model-free** (no LLM, no GPU) and were produced on
+the current release from one command (see [Reproducing](#reproducing-the-benchmarks)).
+
+| Benchmark | Metric | LiteParse | + Tesseract OCR | + PaddleOCR | Best other free tool | Commercial reference |
+|---|---|---:|---:|---:|---:|---:|
+| [ParseBench](https://github.com/run-llama/parse-bench) (2,049 docs) | Overall (mean of 5 categories) | 0.371 | 0.380 | **0.389** | pymupdf4llm 0.310 | — |
+| [opendataloader-bench](https://github.com/opendataloader-project/opendataloader-bench) (200 docs) | Overall (NID + TEDS + MHS) | 0.886 | 0.896 | **0.901** | opendataloader 0.831 | nutrient 0.885 |
+| [olmOCR-bench](https://github.com/allenai/olmocr/tree/main/olmocr/bench) (1,403 pages) | % tests passed | 39.6 | 41.1 | **42.2** | pymupdf4llm 32.9 | — |
+
+**Speed** (`lit parse --format markdown`, single process, Apple M2 Max, 10 real-world reports and
+filings totalling 1,266 pages):
+
+| Mode | Pages / second | Seconds per 100-page document |
+|---|---:|---:|
+| No OCR | 183 | 0.5 |
+| Built-in Tesseract | 3.5 | 28 |
+| PaddleOCR server | 1.4 | 70 |
+
+OCR runs only on pages that need it (scans, embedded figures, sparse or garbled text), so
+OCR-mode throughput depends heavily on how image-heavy a document is.
+
+<details>
+<summary><b>ParseBench</b> — tables, charts, content faithfulness, formatting, visual grounding</summary>
+
+Rule-based scoring, no LLM judge. Each column is ParseBench's canonical per-category metric
+(Tables = GriTS/TRM composite; the others are rule pass-rates). Overall is the mean of the five,
+as on the ParseBench leaderboard.
+
+| Pipeline | Overall | Tables | Charts | Content Faithfulness | Semantic Formatting | Visual Grounding |
+|---|---:|---:|---:|---:|---:|---:|
+| **LiteParse + PaddleOCR** | **0.389** | **0.430** | 0.013 | **0.787** | 0.402 | 0.314 |
+| **LiteParse + Tesseract** | 0.380 | 0.428 | 0.012 | 0.751 | 0.399 | 0.307 |
+| **LiteParse (no OCR)** | 0.371 | 0.424 | 0.013 | 0.700 | 0.385 | **0.336** |
+| pymupdf4llm | 0.310 | 0.373 | 0.015 | 0.609 | **0.446** | 0.107 |
+| opendataloader | 0.294 | 0.352 | 0.009 | 0.661 | 0.341 | 0.108 |
+| pdf-inspector | 0.266 | 0.266 | **0.053** | 0.561 | 0.351 | 0.099 |
+| markitdown | 0.186 | 0.158 | 0.020 | 0.645 | 0.009 | 0.099 |
+
+Notes:
+- **Visual Grounding** scores layout blocks with bounding boxes (`lit parse --extract-blocks`).
+ The other tools emit no layout data, so their score is only what the reading-order rules
+ award; treat that column as LiteParse-only.
+- **Charts** is near zero for every model-free tool — none reconstruct chart data.
+- Competitor rows were run on 2026-06-15 with the same harness; LiteParse rows on 2026-09-09.
+
+</details>
+
+<details>
+<summary><b>opendataloader-bench</b> — reading order, table structure, heading hierarchy</summary>
+
+NID = reading-order similarity, TEDS = table structure, MHS = heading hierarchy. Overall is the
+harness's own mean.
+
+| Engine | Overall | NID | TEDS | MHS |
+|---|---:|---:|---:|---:|
+| **LiteParse + PaddleOCR** | **0.901** | **0.932** | **0.832** | **0.840** |
+| **LiteParse + Tesseract** | 0.896 | 0.928 | 0.829 | 0.828 |
+| **LiteParse (no OCR)** | 0.886 | 0.917 | 0.818 | 0.821 |
+| nutrient *(commercial)* | 0.885 | 0.925 | 0.708 | 0.819 |
+| opendataloader | 0.831 | 0.902 | 0.489 | 0.740 |
+| pymupdf4llm | 0.732 | 0.885 | 0.401 | 0.412 |
+| markitdown | 0.589 | 0.844 | 0.273 | 0.000 |
+
+Notes:
+- nutrient and pymupdf4llm have no runnable parser in this harness (commercial / AGPL); their
+ rows are the harness's preserved predictions on the same corpus and ground truth.
+- The corpus is native-text PDFs, so OCR gains come from embedded figures and a handful of
+ scanned pages.
+
+</details>
+
+<details>
+<summary><b>olmOCR-bench</b> — 1,403 single pages, 8,413 unit tests</summary>
+
+Score = average of per-category pass rates. The two math categories require LaTeX output and
+are 0% for every model-free tool; they still count in the average.
+
+| Engine | Overall | baseline | headers_footers | multi_column | table_tests | long_tiny_text | old_scans | arxiv_math | old_scans_math |
+|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
+| **LiteParse + PaddleOCR** | **42.2** | **99.9** | 48.7 | **69.1** | **54.0** | **46.4** | **19.4** | 0.0 | 0.0 |
+| **LiteParse + Tesseract** | 41.1 | **99.9** | 52.1 | 66.2 | **54.1** | 42.5 | 13.9 | 0.0 | 0.0 |
+| **LiteParse (no OCR)** | 39.6 | **99.9** | **55.8** | 66.3 | 52.5 | 29.2 | 13.3 | 0.0 | 0.0 |
+| pymupdf4llm | 32.9 | 84.5 | 39.5 | 66.7 | 46.3 | 12.7 | 13.3 | 0.0 | 0.0 |
+| opendataloader | 32.7 | 86.9 | 37.5 | 62.8 | 25.7 | 35.1 | 13.3 | 0.0 | 0.0 |
+| pdf-inspector | 30.5 | 82.9 | 52.0 | 38.2 | 40.0 | 17.4 | 13.3 | 0.0 | 0.0 |
+| markitdown | 28.7 | 86.8 | 38.8 | 39.3 | 19.9 | 31.2 | 13.3 | 0.0 | 0.0 |
+
+Notes:
+- **headers_footers** expects letterhead and footer text to be *absent*. OCR recovers that text
+ from logo and address images on single-page documents, where the repeated-header filter cannot
+ fire, so the OCR rows score lower there by design — we chose not to drop text by page position.
+- **old_scans** is largely cursive handwriting; Tesseract cannot read it, PaddleOCR partially can.
+
+</details>
+
+<details>
+<summary><b>How the runs are configured</b></summary>
+
+- **Same scorer for every tool.** Each benchmark's own evaluator, unmodified. The ground truth in
+ all three corpora is plain text, so every tool including LiteParse runs with hyperlink syntax
+ off (`--no-links`); everything else is the default `lit parse --format markdown`.
+- **OCR modes.** *No OCR* is `--no-ocr`. *Tesseract* is the built-in engine with no setup.
+ *PaddleOCR* is the PP-OCRv5 mobile detector and English recognizer served over the
+ [OCR HTTP API](OCR_API_SPEC.md) by [`ocr/rapidocr`](ocr/rapidocr), which runs the PaddleOCR
+ models on ONNX Runtime — the same models as [`ocr/paddleocr`](ocr/paddleocr), 20–40× faster
+ per page on CPU-only machines.
+- **Competitors** are the model-free converters we could run locally: pymupdf4llm, markitdown,
+ opendataloader (its non-hybrid mode), pdf-inspector. Numbers from public leaderboards or
+ LLM-assisted modes are not mixed in.
+- **Machine:** Apple M2 Max, 12 cores, 32 GB. LiteParse rows: v2.14.4 (2026-09-09).
+
+</details>
+
+### Reproducing the benchmarks
+
+```sh
+./run_benchmarks.sh --liteparse-only # all three benches, no OCR
+./run_benchmarks.sh --liteparse-only --ocr=tesseract
+( cd ocr/rapidocr && uv run server.py ) & # then:
+./run_benchmarks.sh --liteparse-only --ocr=paddle
+./run_benchmarks.sh # also re-run the model-free competitors
+```
+
+Results and a `SUMMARY.md` land in `bench_results/latest/`. See [BENCHMARKS.md](BENCHMARKS.md)
+for per-harness details and the artifact-freshness checklist.
+
## Installation
Install via your preferred package manager. All versions (except WASM) ship with the same `lit` CLI.
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index 4d7df3d..38212b3 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -556,6 +556,9 @@ impl JsPageInput {
pub fn to_rust(&self) -> Page {
Page {
page_number: self.page_number as usize,
+ // Externally supplied pages carry no source PDF, so there is no
+ // /PageLabels tree to read a label from.
+ page_label: None,
page_width: self.page_width as f32,
page_height: self.page_height as f32,
content_bounds: None,
@@ -583,6 +586,10 @@ impl JsPageInput {
#[derive(Clone)]
pub struct JsParsedPage {
pub page_num: u32,
+ /// The document's `/PageLabels` label for this page ("iv", "A-1"), absent
+ /// when the PDF defines none. This is what a reader displays for the page
+ /// and is not always its position; fall back to `page_num` when absent.
+ pub page_label: Option<String>,
pub width: f64,
pub height: f64,
/// Union bbox of the page's top-level content objects in viewport
@@ -946,6 +953,7 @@ impl JsParsedPage {
pub fn from_rust(page: &ParsedPage, extract_text_metadata: bool) -> Self {
Self {
page_num: page.page_number as u32,
+ page_label: page.page_label.clone(),
width: page.page_width as f64,
height: page.page_height as f64,
content_bounds: page.content_bounds.as_ref().map(|b| JsRect {
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index 5ad832d..bde0421 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -518,6 +518,11 @@ impl PyTextItem {
struct PyParsedPage {
#[pyo3(get)]
page_num: u32,
+ /// The document's `/PageLabels` label for this page ("iv", "A-1"), absent
+ /// when the PDF defines none. This is what a reader displays for the page
+ /// and is not always its position; fall back to `page_num` when absent.
+ #[pyo3(get)]
+ page_label: Option<String>,
#[pyo3(get)]
width: f64,
#[pyo3(get)]
@@ -662,6 +667,7 @@ impl PyParsedPage {
fn from_rust(page: liteparse::types::ParsedPage, extract_text_metadata: bool) -> Self {
Self {
page_num: page.page_number as u32,
+ page_label: page.page_label.clone(),
width: page.page_width as f64,
height: page.page_height as f64,
content_bounds: page.content_bounds.as_ref().map(|b| PyRect {
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index a3d743e..7d1f7e8 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -378,6 +378,11 @@ pub struct TextItem {
#[serde(rename_all = "camelCase")]
pub struct ParsedPage {
pub page_num: usize,
+ /// The document's `/PageLabels` label for this page ("iv", "A-1"), absent
+ /// when the PDF defines none. This is what a reader displays for the page
+ /// and is not always its position; fall back to `page_num` when absent.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub page_label: Option<String>,
pub width: f32,
pub height: f32,
/// Union bbox of the page's top-level content objects in viewport
@@ -1127,6 +1132,7 @@ fn to_js_result(result: &liteparse::ParseResult, extract_text_metadata: bool) ->
.iter()
.map(|p| ParsedPage {
page_num: p.page_number,
+ page_label: p.page_label.clone(),
width: p.page_width,
height: p.page_height,
content_bounds: p.content_bounds.as_ref().map(|b| VectorRect {
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index 8b1bedd..b0e8ca4 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -359,6 +359,7 @@ fn extract_single_page(
Ok(PageExtraction {
page: LitePage {
page_number: page_number as usize,
+ page_label: document.page_label(page_index),
page_width,
page_height,
content_bounds: output_options
@@ -3925,6 +3926,7 @@ mod tests {
fn page_with(items: Vec<TextItem>) -> LitePage {
LitePage {
page_number: 1,
+ page_label: None,
page_width: 100.0,
page_height: 100.0,
content_bounds: None,
diff --git a/crates/liteparse/src/markdown_layout/test_helpers.rs b/crates/liteparse/src/markdown_layout/test_helpers.rs
index aff4f01..9c9eadf 100644
--- a/crates/liteparse/src/markdown_layout/test_helpers.rs
+++ b/crates/liteparse/src/markdown_layout/test_helpers.rs
@@ -32,6 +32,7 @@ pub(crate) fn line(text: &str, x: f32, y: f32, h: f32, size: f32) -> ProjectedLi
pub(crate) fn page(lines: Vec<ProjectedLine>) -> ParsedPage {
ParsedPage {
page_number: 1,
+ page_label: None,
page_width: 612.0,
page_height: 792.0,
content_bounds: None,
@@ -192,6 +193,7 @@ pub(crate) fn header_footer_page(n: usize, header: &str, footer: &str, body: &st
];
ParsedPage {
page_number: n,
+ page_label: None,
page_width: 612.0,
page_height: 100.0,
content_bounds: None,
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index b8f21f9..6ea2cbd 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -1588,6 +1588,7 @@ mod tests {
fn page(items: Vec<TextItem>) -> Page {
Page {
page_number: 1,
+ page_label: None,
page_width: 612.0,
page_height: 792.0,
content_bounds: None,
@@ -1872,6 +1873,7 @@ mod tests {
fn make_blank_page(page_number: usize) -> Page {
Page {
page_number,
+ page_label: None,
page_width: 100.0,
page_height: 100.0,
content_bounds: None,
@@ -2013,6 +2015,7 @@ mod tests {
fn make_native_text_page(page_number: usize) -> Page {
Page {
page_number,
+ page_label: None,
page_width: 100.0,
page_height: 100.0,
content_bounds: None,
@@ -2041,6 +2044,7 @@ mod tests {
fn make_low_coverage_text_page(page_number: usize) -> Page {
Page {
page_number,
+ page_label: None,
page_width: 100.0,
page_height: 100.0,
content_bounds: None,
diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rs
index 467a419..291f625 100644
--- a/crates/liteparse/src/output/json.rs
+++ b/crates/liteparse/src/output/json.rs
@@ -46,6 +46,10 @@ pub(crate) struct JsonTextItem {
#[derive(Debug, Serialize)]
pub(crate) struct JsonPage {
pub page: usize,
+ /// The document's `/PageLabels` label for this page, omitted when the
+ /// PDF defines none. See `ParsedPage::page_label`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub page_label: Option<String>,
pub width: f32,
pub height: f32,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -119,6 +123,7 @@ pub(crate) fn build_json(pages: &[ParsedPage], extract_text_metadata: bool) -> P
.iter()
.map(|page| JsonPage {
page: page.page_number,
+ page_label: page.page_label.clone(),
width: page.page_width,
height: page.page_height,
content_bounds: page.content_bounds.clone(),
@@ -238,6 +243,7 @@ mod tests {
fn page(items: Vec<TextItem>) -> ParsedPage {
ParsedPage {
page_number: 1,
+ page_label: None,
page_width: 612.0,
page_height: 792.0,
content_bounds: None,
diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rs
index 05d202d..c31d229 100644
--- a/crates/liteparse/src/output/markdown.rs
+++ b/crates/liteparse/src/output/markdown.rs
@@ -200,6 +200,7 @@ mod tests {
fn page_with(n: usize, lines: Vec<ProjectedLine>) -> ParsedPage {
ParsedPage {
page_number: n,
+ page_label: None,
page_width: 612.0,
page_height: 792.0,
content_bounds: None,
@@ -259,6 +260,7 @@ mod tests {
fn test_fallback_when_no_projected_lines() {
let p = ParsedPage {
page_number: 1,
+ page_label: None,
page_width: 0.0,
page_height: 0.0,
content_bounds: None,
diff --git a/crates/liteparse/src/output/text.rs b/crates/liteparse/src/output/text.rs
index ff01137..a5c3004 100644
--- a/crates/liteparse/src/output/text.rs
+++ b/crates/liteparse/src/output/text.rs
@@ -16,6 +16,7 @@ mod tests {
fn page(n: usize, text: &str) -> ParsedPage {
ParsedPage {
page_number: n,
+ page_label: None,
page_width: 0.0,
page_height: 0.0,
content_bounds: None,
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index c32ae69..e298d39 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -1250,6 +1250,7 @@ mod tests {
fn page_with_text_metadata() -> Page {
Page {
page_number: 1,
+ page_label: None,
page_width: 100.0,
page_height: 100.0,
content_bounds: None,
@@ -1478,6 +1479,7 @@ mod tests {
let mut pages = vec![ParsedPage {
page_number: 1,
+ page_label: None,
page_width: 612.0,
page_height: 792.0,
content_bounds: None,
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index 62b9f49..98ce646 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -2894,6 +2894,7 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {
let projected_item_frames = projected_item_frames(&projected_items);
ParsedPage {
page_number: page.page_number,
+ page_label: page.page_label,
page_width: page.page_width,
page_height: page.page_height,
content_bounds: page.content_bounds,
@@ -5195,6 +5196,7 @@ mod tests {
fn project_to_grid_handles_text_sparse_zero_width_items() {
let page = Page {
page_number: 1,
+ page_label: None,
page_width: 612.0,
page_height: 792.0,
content_bounds: None,
@@ -5563,6 +5565,7 @@ mod tests {
fn project_pages_to_grid_handles_page_with_no_text_items() {
let pages = vec![Page {
page_number: 1,
+ page_label: None,
page_width: 612.0,
page_height: 792.0,
content_bounds: None,
@@ -5588,6 +5591,7 @@ mod tests {
let y = 50.25;
let pages = vec![Page {
page_number: 1,
+ page_label: None,
page_width: 612.0,
page_height: 792.0,
content_bounds: None,
@@ -5639,6 +5643,7 @@ mod tests {
let y = 50.25;
let pages = vec![Page {
page_number: 1,
+ page_label: None,
page_width: 612.0,
page_height: 792.0,
content_bounds: None,
@@ -5698,6 +5703,7 @@ mod tests {
fn project_pages_to_grid_unions_original_bbox_when_continuous_items_merge() {
let pages = vec![Page {
page_number: 1,
+ page_label: None,
page_width: 612.0,
page_height: 792.0,
content_bounds: None,
diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rs
index 654a521..713ff70 100644
--- a/crates/liteparse/src/types.rs
+++ b/crates/liteparse/src/types.rs
@@ -208,6 +208,12 @@ pub struct WordBox {
#[derive(Debug, Serialize)]
pub struct Page {
pub page_number: usize,
+ /// The document's `/PageLabels` entry for this page ("iv", "A-1"), when
+ /// the PDF defines one. This is what a reader displays for the page and
+ /// is not always its position in the document; `None` means the PDF has
+ /// no label for it and consumers should fall back to `page_number`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub page_label: Option<String>,
pub page_width: f32,
pub page_height: f32,
/// Union bbox of the page's top-level content objects in viewport
@@ -413,6 +419,12 @@ pub struct StructNode {
#[derive(Debug, Serialize)]
pub struct ParsedPage {
pub page_number: usize,
+ /// The document's `/PageLabels` entry for this page ("iv", "A-1"), when
+ /// the PDF defines one. This is what a reader displays for the page and
+ /// is not always its position in the document; `None` means the PDF has
+ /// no label for it and consumers should fall back to `page_number`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub page_label: Option<String>,
pub page_width: f32,
pub page_height: f32,
/// Union bbox of the page's top-level content objects in viewport
@@ -823,6 +835,7 @@ mod tests {
fn page_serializes() {
let p = Page {
page_number: 1,
+ page_label: None,
page_width: 100.0,
page_height: 200.0,
content_bounds: None,
diff --git a/crates/liteparse/tests/integration_test.rs b/crates/liteparse/tests/integration_test.rs
index 183e399..6ca5132 100644
--- a/crates/liteparse/tests/integration_test.rs
+++ b/crates/liteparse/tests/integration_test.rs
@@ -982,3 +982,45 @@ async fn test_negative_font_size_is_not_reported_as_rotated() {
assert!(text.contains("Upright text drawn with a negative font size"));
assert!(text.contains("Second line stays upright too"));
}
+
+/// `page_labels.pdf` carries a `/PageLabels` number tree that maps pages 0-1 to
+/// lowercase roman and pages 2-3 to decimal restarting at 1, so the labels
+/// ("i", "ii", "1", "2") deliberately disagree with the 1-based page numbers.
+/// pypdf reports the same four labels for this file, which is the contract the
+/// LlamaIndex reader's `page_label` metadata has to match.
+#[tokio::test]
+async fn parse_reports_pdf_page_labels() {
+ let parser = LiteParse::new(LiteParseConfig::default());
+ let result = parser
+ .parse("../../integration_tests_data/page_labels.pdf")
+ .await
+ .expect("parse page_labels.pdf");
+
+ let labels: Vec<Option<&str>> = result
+ .pages
+ .iter()
+ .map(|p| p.page_label.as_deref())
+ .collect();
+ assert_eq!(
+ labels,
+ vec![Some("i"), Some("ii"), Some("1"), Some("2")],
+ "page labels must come from /PageLabels, not the page index"
+ );
+}
+
+/// A PDF with no `/PageLabels` tree reports `None` rather than a synthesized
+/// label, so callers can tell "no label" from a label that happens to equal
+/// the page number and fall back to `page_number` themselves.
+#[tokio::test]
+async fn parse_reports_no_page_label_when_pdf_has_none() {
+ let parser = LiteParse::new(LiteParseConfig::default());
+ let result = parser
+ .parse("../../integration_tests_data/sample.pdf")
+ .await
+ .expect("parse sample.pdf");
+
+ assert!(
+ result.pages.iter().all(|p| p.page_label.is_none()),
+ "sample.pdf has no /PageLabels tree"
+ );
+}
diff --git a/crates/pdfium-sys/src/dynamic.rs b/crates/pdfium-sys/src/dynamic.rs
index 35d4900..e978702 100644
--- a/crates/pdfium-sys/src/dynamic.rs
+++ b/crates/pdfium-sys/src/dynamic.rs
@@ -79,6 +79,12 @@ pub struct PdfiumBindings {
*mut std::os::raw::c_void,
std::os::raw::c_ulong,
) -> std::os::raw::c_ulong,
+ pub FPDF_GetPageLabel: unsafe extern "C" fn(
+ FPDF_DOCUMENT,
+ std::os::raw::c_int,
+ *mut std::os::raw::c_void,
+ std::os::raw::c_ulong,
+ ) -> std::os::raw::c_ulong,
pub FPDF_GetFileVersion:
unsafe extern "C" fn(FPDF_DOCUMENT, *mut std::os::raw::c_int) -> FPDF_BOOL,
pub FPDF_GetSecurityHandlerRevision: unsafe extern "C" fn(FPDF_DOCUMENT) -> std::os::raw::c_int,
@@ -578,6 +584,7 @@ impl PdfiumBindings {
FORM_DoPageAAction: load_fn!(lib, "FORM_DoPageAAction"),
FPDF_FFLDraw: load_fn!(lib, "FPDF_FFLDraw"),
FPDF_GetMetaText: load_fn!(lib, "FPDF_GetMetaText"),
+ FPDF_GetPageLabel: load_fn!(lib, "FPDF_GetPageLabel"),
FPDF_GetFileVersion: load_fn!(lib, "FPDF_GetFileVersion"),
FPDF_GetSecurityHandlerRevision: load_fn!(lib, "FPDF_GetSecurityHandlerRevision"),
FPDF_GetDocPermissions: load_fn!(lib, "FPDF_GetDocPermissions"),
diff --git a/crates/pdfium/src/document.rs b/crates/pdfium/src/document.rs
index 285be6f..bc9bd1d 100644
--- a/crates/pdfium/src/document.rs
+++ b/crates/pdfium/src/document.rs
@@ -249,6 +249,52 @@ impl<'lib> Document<'lib> {
Some(String::from_utf16_lossy(&buf[..end]))
}
+ /// The document's `/PageLabels` entry for a zero-based page index, when
+ /// the document defines one.
+ ///
+ /// This is the label a reader displays for the page — `"iv"`, `"A-1"`,
+ /// `"12"` — which is not always the page's position in the document.
+ /// `None` when the document has no `/PageLabels` tree, or none covering
+ /// this page; callers should fall back to the one-based page number.
+ pub fn page_label(&self, page_index: i32) -> Option<String> {
+ if page_index < 0 {
+ return None;
+ }
+ let needed = unsafe {
+ ffi!(FPDF_GetPageLabel(
+ self.handle,
+ page_index,
+ std::ptr::null_mut(),
+ 0
+ ))
+ } as usize;
+ // `needed` is the byte length of the UTF-16 label including its
+ // trailing NUL, so anything under 4 bytes is an empty or absent label.
+ if needed < 4 {
+ return None;
+ }
+ let mut buf: Vec<u16> = vec![0; needed / 2];
+ let written = unsafe {
+ ffi!(FPDF_GetPageLabel(
+ self.handle,
+ page_index,
+ buf.as_mut_ptr() as *mut std::os::raw::c_void,
+ needed as std::os::raw::c_ulong,
+ ))
+ } as usize;
+ if written < 4 {
+ return None;
+ }
+ let chars = written / 2;
+ let end = if buf.get(chars - 1) == Some(&0) {
+ chars - 1
+ } else {
+ chars
+ };
+ let label = String::from_utf16_lossy(&buf[..end]);
+ (!label.is_empty()).then_some(label)
+ }
+
/// Encoded PDF version (`14` means PDF 1.4), when present.
pub fn file_version(&self) -> Option<i32> {
let mut version = 0;
diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.ts
index 709f1d5..d78a793 100644
--- a/packages/node/src/lib.ts
+++ b/packages/node/src/lib.ts
@@ -250,6 +250,12 @@ export interface Rect {
export interface ParsedPage {
pageNum: number;
+ /**
+ * The document's `/PageLabels` label for this page ("iv", "A-1"), absent
+ * when the PDF defines none. This is what a reader displays for the page
+ * and is not always its position, so fall back to `pageNum` when absent.
+ */
+ pageLabel?: string;
width: number;
height: number;
/**
@@ -926,6 +932,7 @@ export function toParseResult(result: NativeParseResult): ParseResult {
function toPage(p: NativeParsedPage): ParsedPage {
return {
pageNum: p.pageNum,
+ pageLabel: p.pageLabel ?? undefined,
width: p.width,
height: p.height,
contentBounds: p.contentBounds,
diff --git a/packages/node/src/native.ts b/packages/node/src/native.ts
index d247d6d..5100a5d 100644
--- a/packages/node/src/native.ts
+++ b/packages/node/src/native.ts
@@ -132,6 +132,7 @@ export interface NativeRect {
export interface NativeParsedPage {
pageNum: number;
+ pageLabel?: string;
width: number;
height: number;
contentBounds?: NativeRect;
diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.py
index cd83ccd..c3e081d 100644
--- a/packages/python/liteparse/parser.py
+++ b/packages/python/liteparse/parser.py
@@ -1,5 +1,7 @@
"""LiteParse Python wrapper - native Rust bindings via PyO3."""
+import asyncio
+from concurrent.futures import Executor
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
@@ -203,6 +205,7 @@ def _convert_native_result(native_result: Any) -> ParseResult:
pages.append(
ParsedPage(
page_num=native_page.page_num,
+ page_label=getattr(native_page, "page_label", None),
width=native_page.width,
height=native_page.height,
content_bounds=(
@@ -738,6 +741,30 @@ class LiteParse:
except Exception as e:
raise ParseError(str(e)) from e
+ async def aparse(
+ self,
+ file_data: Union[str, Path, bytes],
+ *,
+ executor: Optional[Executor] = None,
+ ) -> ParseResult:
+ """
+ Parse a document without blocking the running event loop.
+
+ Args:
+ file_data: Path to the document file, or raw PDF bytes.
+ executor: Executor to run the parse on. Defaults to the running
+ loop's default thread pool.
+
+ Returns:
+ ParseResult containing the parsed document data.
+
+ Raises:
+ The same exceptions as :meth:`parse`, re-raised on the awaiting
+ side.
+ """
+ loop = asyncio.get_running_loop()
+ return await loop.run_in_executor(executor, self.parse, file_data)
+
def parse_batches(
self,
file_data: Union[str, Path, bytes],
diff --git a/packages/python/liteparse/types.py b/packages/python/liteparse/types.py
index ba60687..4e6cfcf 100644
--- a/packages/python/liteparse/types.py
+++ b/packages/python/liteparse/types.py
@@ -174,6 +174,11 @@ class ParsedPage:
height: float
text: str
markdown: str = ""
+ #: The document's ``/PageLabels`` label for this page ("iv", "A-1"),
+ #: or ``None`` when the PDF defines none. This is what a reader displays
+ #: for the page and is not always its position in the document, so fall
+ #: back to ``page_num`` when it is ``None``.
+ page_label: Optional[str] = None
text_items: List[TextItem] = field(default_factory=list)
#: Per-page complexity signals (the same :meth:`LiteParse.is_complex`
#: returns). Populated only when parsing with ``include_complexity=True``;