Skip to content

A fast, helpful, and open-source document parser

fix: several quadratic complexity issues

Logan Markewiche233847b1f89
diff --git a/Cargo.lock b/Cargo.lock
index f3d80ad..8a25d67 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2016,7 +2016,7 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
[[package]]
name = "liteparse"
-version = "2.13.1"
+version = "2.14.0"
dependencies = [
"blake3",
"clap",
@@ -2048,7 +2048,7 @@ dependencies = [
[[package]]
name = "liteparse-napi"
-version = "2.13.1"
+version = "2.14.0"
dependencies = [
"image",
"liteparse",
@@ -2083,7 +2083,7 @@ dependencies = [
[[package]]
name = "liteparse-python"
-version = "2.13.1"
+version = "2.14.0"
dependencies = [
"anyhow",
"clap",
@@ -2099,7 +2099,7 @@ dependencies = [
[[package]]
name = "liteparse-wasm"
-version = "2.13.1"
+version = "2.14.0"
dependencies = [
"console_error_panic_hook",
"js-sys",
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index d84d2ef..bebc23d 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -2955,6 +2955,101 @@ mod tests {
pdf
}
+ /// One normal page plus a `/UserUnit 36` page whose text is written at
+ /// 0.3 pt — real size 10.8 pt. PDFium reports the raw sub-point metrics,
+ /// so without the user-unit rescale every char on page 2 dies in the
+ /// zero-height (< 0.5 pt) filter, which is exactly how spreadsheet-export
+ /// invoices used to parse as completely empty pages.
+ fn user_unit_pdf() -> Vec<u8> {
+ let normal = b"BT /F1 10 Tf 20 40 Td (NORMALMARK) Tj ET";
+ let tiny = b"BT /F1 0.3 Tf 2 50 Td (TINYMARK) Tj ET";
+ let objects: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Resources << /Font << /F1 7 0 R >> >> /Contents 5 0 R >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 40 100] /UserUnit 36 /Resources << /Font << /F1 7 0 R >> >> /Contents 6 0 R >>".to_vec(),
+ [
+ format!("<< /Length {} >>\nstream\n", normal.len()).as_bytes(),
+ normal.as_slice(),
+ b"\nendstream",
+ ]
+ .concat(),
+ [
+ format!("<< /Length {} >>\nstream\n", tiny.len()).as_bytes(),
+ tiny.as_slice(),
+ b"\nendstream",
+ ]
+ .concat(),
+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
+ ];
+ 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", index + 1).as_bytes());
+ pdf.extend_from_slice(object);
+ pdf.extend_from_slice(b"\nendobj\n");
+ }
+ 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(),
+ );
+ pdf
+ }
+
+ #[test]
+ fn user_unit_page_extracts_text_at_real_scale() {
+ let pages =
+ extract_pages_from_input(&PdfInput::Bytes(user_unit_pdf()), None, usize::MAX, None)
+ .unwrap();
+
+ assert_eq!(pages.len(), 2);
+
+ // The normal page is untouched by the user-unit machinery.
+ assert_eq!((pages[0].page_width, pages[0].page_height), (200.0, 300.0));
+ let normal_text: String = pages[0]
+ .text_items
+ .iter()
+ .map(|i| i.text.as_str())
+ .collect();
+ assert!(normal_text.contains("NORMALMARK"), "page 1: {normal_text}");
+
+ // The /UserUnit 36 page reports its real dimensions...
+ assert_eq!(
+ (pages[1].page_width, pages[1].page_height),
+ (40.0 * 36.0, 100.0 * 36.0)
+ );
+ // ...and its 0.3 pt-written text survives extraction at ~10.8 pt.
+ let tiny_items: Vec<_> = pages[1]
+ .text_items
+ .iter()
+ .filter(|i| i.text.contains("TINYMARK"))
+ .collect();
+ assert_eq!(tiny_items.len(), 1, "items: {:?}", pages[1].text_items);
+ let item = tiny_items[0];
+ assert!(
+ item.height > 5.0 && item.height < 20.0,
+ "expected ~10.8pt tall text, got {}",
+ item.height
+ );
+ // Baseline sanity: the text sits in the upper half of the page in
+ // top-left viewport coordinates (written at y=50 of 100, scaled 36x).
+ assert!(
+ (item.y - (100.0 - 50.3) * 36.0).abs() < 36.0,
+ "unexpected y: {}",
+ item.y
+ );
+ }
+
#[test]
fn rotated_pages_use_viewport_dimensions_and_keep_edge_text() {
let pages =
diff --git a/crates/liteparse/src/render.rs b/crates/liteparse/src/render.rs
index 43cb98d..1bd481b 100644
--- a/crates/liteparse/src/render.rs
+++ b/crates/liteparse/src/render.rs
@@ -4,6 +4,13 @@ use crate::types::{PdfInput, ScreenshotRect};
use pdfium::Library;
use serde::Serialize;
+/// Cap on the rendered long edge in pixels. Normal pages never hit this
+/// (a US-Letter page at 150 DPI is ~1,650 px); it exists so freakishly tall
+/// pages — dense PDFs and especially `/UserUnit` spreadsheet exports — can't
+/// request multi-gigabyte bitmaps. 30,000 px keeps the historical behavior
+/// for every page under ~14,400 pt at 150 DPI.
+const MAX_RENDER_LONG_EDGE_PX: f32 = 30_000.0;
+
/// A single rendered page as PNG bytes, plus raster-derived signals.
#[derive(Debug, Clone)]
pub struct RenderedPage {
@@ -81,7 +88,17 @@ pub(crate) fn render_document_pages(
}
let page = document.page((page_num - 1) as i32)?;
- let bitmap = page.render_with_form(dpi, form.as_ref())?;
+ // `/UserUnit` pages (spreadsheet exports hundreds of thousands
+ // of points tall) would render to gigapixel bitmaps at the
+ // requested DPI; cap the long edge like the OCR render does.
+ let page_width = page.width() * page.user_unit();
+ let page_height = page.height() * page.user_unit();
+ let long_edge_pt = page_width.max(page_height);
+ let mut eff_dpi = dpi;
+ if long_edge_pt > 0.0 {
+ eff_dpi = eff_dpi.min(MAX_RENDER_LONG_EDGE_PX * 72.0 / long_edge_pt);
+ }
+ let bitmap = page.render_with_form(eff_dpi, form.as_ref())?;
let width = bitmap.width() as u32;
let height = bitmap.height() as u32;
let rgba = bitmap.to_rgba();
@@ -94,8 +111,8 @@ pub(crate) fn render_document_pages(
&rgba,
width as usize,
height as usize,
- page.width(),
- page.height(),
+ page_width,
+ page_height,
)
} else {
Vec::new()
diff --git a/crates/pdfium-sys/bindings.rs b/crates/pdfium-sys/bindings.rs
index e6f46c1..15d2115 100644
--- a/crates/pdfium-sys/bindings.rs
+++ b/crates/pdfium-sys/bindings.rs
@@ -1091,6 +1091,9 @@ unsafe extern "C" {
unsafe extern "C" {
pub fn FPDFPage_GetRotation(page: FPDF_PAGE) -> ::std::os::raw::c_int;
}
+unsafe extern "C" {
+ pub fn FPDFPage_GetUserUnit(page: FPDF_PAGE) -> f32;
+}
unsafe extern "C" {
pub fn FPDFPage_SetRotation(page: FPDF_PAGE, rotate: ::std::os::raw::c_int);
}
diff --git a/crates/pdfium-sys/build.rs b/crates/pdfium-sys/build.rs
index dc507b4..b0c8107 100644
--- a/crates/pdfium-sys/build.rs
+++ b/crates/pdfium-sys/build.rs
@@ -3,7 +3,7 @@ use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
-const PDFIUM_RELEASE_TAG: &str = "chromium/7897";
+const PDFIUM_RELEASE_TAG: &str = "chromium/8026";
const PDFIUM_RELEASE_URL: &str = "https://github.com/run-llama/pdfium-binaries/releases/download";
fn main() {
diff --git a/crates/pdfium-sys/src/dynamic.rs b/crates/pdfium-sys/src/dynamic.rs
index d0ae476..b07e7a5 100644
--- a/crates/pdfium-sys/src/dynamic.rs
+++ b/crates/pdfium-sys/src/dynamic.rs
@@ -109,6 +109,9 @@ pub struct PdfiumBindings {
*mut std::os::raw::c_ulong,
) -> FPDF_BOOL,
+ pub FPDF_GetPageSizeByIndexF:
+ unsafe extern "C" fn(FPDF_DOCUMENT, std::os::raw::c_int, *mut FS_SIZEF) -> FPDF_BOOL,
+
// -- Page --
pub FPDF_LoadPage: unsafe extern "C" fn(FPDF_DOCUMENT, std::os::raw::c_int) -> FPDF_PAGE,
pub FPDF_ClosePage: unsafe extern "C" fn(FPDF_PAGE),
@@ -116,6 +119,9 @@ pub struct PdfiumBindings {
pub FPDF_GetPageHeightF: unsafe extern "C" fn(FPDF_PAGE) -> f32,
pub FPDF_GetPageBoundingBox: unsafe extern "C" fn(FPDF_PAGE, *mut FS_RECTF) -> FPDF_BOOL,
pub FPDFPage_GetRotation: unsafe extern "C" fn(FPDF_PAGE) -> std::os::raw::c_int,
+ /// LlamaParse fork API (absent from stock pdfium and older fork
+ /// releases); callers fall back to the raw-byte `/UserUnit` scan.
+ pub FPDFPage_GetUserUnit: Option<unsafe extern "C" fn(FPDF_PAGE) -> f32>,
pub FPDFPage_Flatten:
Option<unsafe extern "C" fn(FPDF_PAGE, std::os::raw::c_int) -> std::os::raw::c_int>,
pub FPDF_PageToDevice: unsafe extern "C" fn(
@@ -549,6 +555,7 @@ impl PdfiumBindings {
FPDF_LoadMemDocument: load_fn!(lib, "FPDF_LoadMemDocument"),
FPDF_CloseDocument: load_fn!(lib, "FPDF_CloseDocument"),
FPDF_GetPageCount: load_fn!(lib, "FPDF_GetPageCount"),
+ FPDF_GetPageSizeByIndexF: load_fn!(lib, "FPDF_GetPageSizeByIndexF"),
FPDF_GetFormType: load_fn!(lib, "FPDF_GetFormType"),
FPDFDOC_InitFormFillEnvironment: load_fn!(lib, "FPDFDOC_InitFormFillEnvironment"),
FPDFDOC_ExitFormFillEnvironment: load_fn!(lib, "FPDFDOC_ExitFormFillEnvironment"),
@@ -574,6 +581,7 @@ impl PdfiumBindings {
FPDF_GetPageHeightF: load_fn!(lib, "FPDF_GetPageHeightF"),
FPDF_GetPageBoundingBox: load_fn!(lib, "FPDF_GetPageBoundingBox"),
FPDFPage_GetRotation: load_fn!(lib, "FPDFPage_GetRotation"),
+ FPDFPage_GetUserUnit: load_fn_opt!(lib, "FPDFPage_GetUserUnit"),
FPDFPage_Flatten: load_fn_opt!(lib, "FPDFPage_Flatten"),
FPDF_PageToDevice: load_fn!(lib, "FPDF_PageToDevice"),
FPDFPage_CountObjects: load_fn!(lib, "FPDFPage_CountObjects"),
diff --git a/crates/pdfium/src/document.rs b/crates/pdfium/src/document.rs
index 80d9bf4..826d26a 100644
--- a/crates/pdfium/src/document.rs
+++ b/crates/pdfium/src/document.rs
@@ -10,6 +10,11 @@ use crate::page::Page;
/// process-wide PDFium lock has been released.
pub struct Document<'lib> {
pub(crate) handle: pdfium_sys::FPDF_DOCUMENT,
+ /// Per-page `/UserUnit` multipliers (see [`crate::user_unit`]); empty
+ /// when no page declares one, which is the overwhelmingly common case.
+ /// PDFium ignores `/UserUnit`, so pages carry this multiplier and apply
+ /// it to all viewport-space geometry and rendering.
+ pub(crate) page_user_units: Vec<f32>,
pub(crate) _lib: std::marker::PhantomData<&'lib Library>,
}
@@ -131,13 +136,51 @@ impl<'lib> Document<'lib> {
if handle.is_null() {
return Err(PdfiumError::PageNotFound);
}
+ // Prefer the fork's dict-reading API; the byte-scan table (see
+ // `crate::user_unit`) is the fallback for binaries that predate it.
+ let user_unit = Self::user_unit_from_api(handle).unwrap_or_else(|| {
+ self.page_user_units
+ .get(index as usize)
+ .copied()
+ .unwrap_or(1.0)
+ });
Ok(Page {
handle,
doc_handle: self.handle,
+ user_unit,
_doc: std::marker::PhantomData,
})
}
+ /// Read `/UserUnit` through the fork's `FPDFPage_GetUserUnit` export.
+ /// `None` when the loaded pdfium binary does not provide it.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn user_unit_from_api(page: pdfium_sys::FPDF_PAGE) -> Option<f32> {
+ let get_user_unit = pdfium_sys::dynamic::pdfium().FPDFPage_GetUserUnit?;
+ let user_unit = unsafe { get_user_unit(page) };
+ // The API already clamps to >= 1.0; guard anyway so a misbehaving
+ // binary can't zero out all geometry.
+ Some(if user_unit.is_finite() && user_unit >= 1.0 {
+ user_unit
+ } else {
+ 1.0
+ })
+ }
+
+ /// On wasm the export is statically linked (the pinned pdfium-binaries
+ /// release ships it), so unlike the dynamic path this can never be
+ /// absent at runtime — bumping the pin below a release that carries
+ /// `FPDFPage_GetUserUnit` would be a link error, not a silent fallback.
+ #[cfg(target_arch = "wasm32")]
+ fn user_unit_from_api(page: pdfium_sys::FPDF_PAGE) -> Option<f32> {
+ let user_unit = unsafe { pdfium_sys::FPDFPage_GetUserUnit(page) };
+ Some(if user_unit.is_finite() && user_unit >= 1.0 {
+ user_unit
+ } else {
+ 1.0
+ })
+ }
+
/// Flatten the visible form-widget appearances on `index` into the page
/// content stream and hand back a freshly loaded page reflecting them.
///
diff --git a/crates/pdfium/src/lib.rs b/crates/pdfium/src/lib.rs
index 3ce12e3..3af94c2 100644
--- a/crates/pdfium/src/lib.rs
+++ b/crates/pdfium/src/lib.rs
@@ -7,6 +7,7 @@ mod page;
mod struct_tree;
mod text_page;
mod types;
+mod user_unit;
pub use bitmap::Bitmap;
pub use document::{Document, FormEnvironment, OutlineEntry, SignatureSummary, XfaPacket};
diff --git a/crates/pdfium/src/library.rs b/crates/pdfium/src/library.rs
index b0dbf8f..10ed29f 100644
--- a/crates/pdfium/src/library.rs
+++ b/crates/pdfium/src/library.rs
@@ -106,8 +106,24 @@ impl Library {
return Err(PdfiumError::from_last_error());
}
+ // PDFium ignores `/UserUnit`, so recover it from the raw bytes (see
+ // `crate::user_unit`) when the fork's dict-reading export isn't
+ // available. The chunked containment probe keeps the common
+ // no-UserUnit case to a single streaming pass with no whole-file
+ // allocation.
+ let page_user_units = if !Self::user_unit_api_available()
+ && crate::user_unit::file_mentions_user_unit(path)
+ {
+ std::fs::read(path)
+ .map(|bytes| Self::page_user_units(handle, &bytes))
+ .unwrap_or_default()
+ } else {
+ Vec::new()
+ };
+
Ok(Document {
handle,
+ page_user_units,
_lib: std::marker::PhantomData,
})
}
@@ -139,7 +155,52 @@ impl Library {
// For now, this is the caller's responsibility.
Ok(Document {
handle,
+ page_user_units: if Self::user_unit_api_available() {
+ Vec::new()
+ } else {
+ Self::page_user_units(handle, data)
+ },
_lib: std::marker::PhantomData,
})
}
+
+ /// Whether the loaded pdfium binary exports the fork's
+ /// `FPDFPage_GetUserUnit`. When it does, `Document::page` reads
+ /// `/UserUnit` through it and the byte-scan table is skipped entirely.
+ fn user_unit_api_available() -> bool {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ pdfium_sys::dynamic::pdfium().FPDFPage_GetUserUnit.is_some()
+ }
+ // Statically linked on wasm; a pinned release without the export
+ // would fail at link time, so present-at-runtime is guaranteed.
+ #[cfg(target_arch = "wasm32")]
+ {
+ true
+ }
+ }
+
+ /// Build the per-page `/UserUnit` table by matching scanned page objects
+ /// against PDFium's reported page sizes (see `crate::user_unit`).
+ fn page_user_units(handle: pdfium_sys::FPDF_DOCUMENT, data: &[u8]) -> Vec<f32> {
+ let entries = crate::user_unit::scan_user_units(data);
+ if entries.is_empty() {
+ return Vec::new();
+ }
+ let page_count = unsafe { ffi!(FPDF_GetPageCount(handle)) };
+ (0..page_count.max(0))
+ .map(|index| {
+ let mut size = pdfium_sys::FS_SIZEF {
+ width: 0.0,
+ height: 0.0,
+ };
+ let ok = unsafe { ffi!(FPDF_GetPageSizeByIndexF(handle, index, &mut size)) };
+ if ok != 0 {
+ crate::user_unit::match_user_unit(&entries, size.width, size.height)
+ } else {
+ 1.0
+ }
+ })
+ .collect()
+ }
}
diff --git a/crates/pdfium/src/page.rs b/crates/pdfium/src/page.rs
index 4f0fdad..d848160 100644
--- a/crates/pdfium/src/page.rs
+++ b/crates/pdfium/src/page.rs
@@ -227,27 +227,43 @@ pub struct PdfFormField {
pub struct Page<'doc, 'lib: 'doc> {
pub(crate) handle: pdfium_sys::FPDF_PAGE,
pub(crate) doc_handle: pdfium_sys::FPDF_DOCUMENT,
+ /// `/UserUnit` multiplier (1.0 for normal pages). PDFium reports all
+ /// geometry in raw MediaBox units, so viewport-space output and render
+ /// pixel sizing multiply by this to recover the page's real scale (see
+ /// `crate::user_unit`).
+ pub(crate) user_unit: f32,
pub(crate) _doc: PhantomData<&'doc Document<'lib>>,
}
impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
+ /// Page width in raw MediaBox units, exactly as PDFium reports it
+ /// (ignores `/UserUnit`; multiply by [`Self::user_unit`] for the real
+ /// size, or use [`Self::viewport_size`] which already does).
pub fn width(&self) -> f32 {
unsafe { ffi!(FPDF_GetPageWidthF(self.handle)) }
}
+ /// Page height in raw MediaBox units (see [`Self::width`]).
pub fn height(&self) -> f32 {
unsafe { ffi!(FPDF_GetPageHeightF(self.handle)) }
}
+ /// The page's `/UserUnit` multiplier, 1.0 when absent.
+ pub fn user_unit(&self) -> f32 {
+ self.user_unit
+ }
+
pub fn rotation(&self) -> i32 {
unsafe { ffi!(FPDFPage_GetRotation(self.handle)) }
}
/// Page dimensions in the same rotation-adjusted viewport coordinate
- /// space returned by [`Self::page_to_viewport`].
+ /// space returned by [`Self::page_to_viewport`]. Unlike [`Self::width`]/
+ /// [`Self::height`], this applies the `/UserUnit` multiplier, so the
+ /// result is in real points (1/72 inch).
pub fn viewport_size(&self, view_box: &RectF) -> (f32, f32) {
- let mut width = (view_box.right - view_box.left).abs();
- let mut height = (view_box.top - view_box.bottom).abs();
+ let mut width = (view_box.right - view_box.left).abs() * self.user_unit;
+ let mut height = (view_box.top - view_box.bottom).abs() * self.user_unit;
if matches!(self.rotation(), 1 | 3) {
std::mem::swap(&mut width, &mut height);
}
@@ -281,8 +297,12 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
pub fn page_to_viewport(&self, view_box: &RectF, page_x: f32, page_y: f32) -> (f32, f32) {
let (vw, vh) = self.viewport_size(view_box);
- let device_w = (vw * 1000.0).round() as i32;
- let device_h = (vh * 1000.0).round() as i32;
+ // 1000x is the precision multiplier for the integer device space.
+ // `/UserUnit` pages can be hundreds of thousands of points tall, so
+ // cap the multiplier to keep the device box inside i32 range.
+ let mult = 1000.0f32.min((i32::MAX / 4) as f32 / vw.max(vh).max(1.0));
+ let device_w = (vw * mult).round() as i32;
+ let device_h = (vh * mult).round() as i32;
let mut dx: i32 = 0;
let mut dy: i32 = 0;
@@ -301,7 +321,7 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
));
}
- (dx as f32 / 1000.0, dy as f32 / 1000.0)
+ (dx as f32 / mult, dy as f32 / mult)
}
/// Convert bounds from PDF page space to viewport space (top-left origin).
@@ -374,7 +394,10 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
dpi: f32,
form: Option<&FormEnvironment>,
) -> Result<Bitmap<'lib>, PdfiumError> {
- let scale = dpi / 72.0;
+ // `/UserUnit` scales the physical page, so honoring the requested
+ // DPI means scaling the pixel size by it too — otherwise a UserUnit
+ // page renders at dpi/user_unit and its text rasterizes microscopic.
+ let scale = dpi / 72.0 * self.user_unit;
let width = (self.width() * scale).round() as i32;
let height = (self.height() * scale).round() as i32;
diff --git a/crates/pdfium/src/user_unit.rs b/crates/pdfium/src/user_unit.rs
new file mode 100644
index 0000000..372b872
--- /dev/null
+++ b/crates/pdfium/src/user_unit.rs
@@ -0,0 +1,303 @@
+//! Detection of the PDF `/UserUnit` page key, which PDFium ignores entirely.
+//!
+//! `/UserUnit` rescales a page's coordinate space: 1 unit = `UserUnit`/72
+//! inch instead of 1/72 inch. Generators (notably spreadsheet/report
+//! exporters) use it to exceed the 14,400 pt MediaBox limit by writing a
+//! small MediaBox with a large multiplier — e.g. a 35 × 14,156 pt MediaBox
+//! with `/UserUnit 36` is really a 1,278 × 509,625 pt page whose "0.3 pt"
+//! text is an ordinary 11 pt font. Because PDFium reports the raw MediaBox
+//! units, such pages look like microscopic text on a tiny page and get
+//! filtered out wholesale unless the multiplier is reapplied.
+//!
+//! Stock PDFium's public API has no way to read `/UserUnit`. The primary
+//! source is the LlamaParse fork's `FPDFPage_GetUserUnit` export, which
+//! reads the real page dictionary; when the loaded binary predates that
+//! export (or on wasm, where a static reference to a missing symbol would
+//! be a link error), this module is the fallback: it scans the raw PDF
+//! bytes for page objects that declare the key. Matching a found entry
+//! back to a page index is done by comparing the object's `/MediaBox`
+//! dimensions against PDFium's reported page size — object numbers alone
+//! can't be mapped to page indices without reimplementing the xref/page
+//! tree walk.
+//!
+//! Known limitations of the byte-scan fallback (all fail safe, i.e. behave
+//! as before this module; none apply to the `FPDFPage_GetUserUnit` path):
+//! - `/UserUnit` inside a compressed object stream is invisible to the scan.
+//! - A page object that *inherits* its `/MediaBox` from `/Pages` is skipped
+//! (`/UserUnit` itself is not inheritable, so both keys are normally
+//! written together by the generators that use it).
+//! - Two same-sized pages where only one declares `/UserUnit` would both be
+//! scaled; in practice identical freak page sizes come from the same
+//! generator path and carry the same multiplier.
+
+/// One `/UserUnit` declaration found in the raw bytes, keyed by the
+/// MediaBox dimensions written in the same page object.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub(crate) struct UserUnitEntry {
+ pub media_width: f32,
+ pub media_height: f32,
+ pub user_unit: f32,
+}
+
+/// The spec restricts `/UserUnit` to positive values; Acrobat additionally
+/// treats values below 1.0 as 1.0 and documents 75,000 as the maximum.
+const MIN_USER_UNIT: f32 = 1.0;
+const MAX_USER_UNIT: f32 = 75_000.0;
+
+const NEEDLE: &[u8] = b"/UserUnit";
+
+/// Scan raw PDF bytes for page objects declaring `/UserUnit`.
+///
+/// Returns only entries with a `/MediaBox` in the same `obj … endobj` span
+/// and a user unit that is finite and > 1.0 (1.0 is the default and needs
+/// no rescale).
+pub(crate) fn scan_user_units(data: &[u8]) -> Vec<UserUnitEntry> {
+ let mut entries = Vec::new();
+ let mut from = 0usize;
+ while let Some(rel) = find(&data[from..], NEEDLE) {
+ let pos = from + rel;
+ from = pos + NEEDLE.len();
+ // Reject prefixes of longer names like `/UserUnitFoo`.
+ match data.get(pos + NEEDLE.len()) {
+ Some(next) if is_regular_char(*next) => continue,
+ None => break,
+ _ => {}
+ }
+ let Some(user_unit) = parse_number_at(data, pos + NEEDLE.len()) else {
+ continue;
+ };
+ let user_unit = user_unit as f32;
+ if !user_unit.is_finite() || user_unit <= MIN_USER_UNIT || user_unit > MAX_USER_UNIT {
+ continue;
+ }
+ let Some((obj_start, obj_end)) = enclosing_object(data, pos) else {
+ continue;
+ };
+ let object = &data[obj_start..obj_end];
+ let Some((media_width, media_height)) = parse_media_box(object) else {
+ continue;
+ };
+ if media_width <= 0.0 || media_height <= 0.0 {
+ continue;
+ }
+ entries.push(UserUnitEntry {
+ media_width,
+ media_height,
+ user_unit,
+ });
+ }
+ entries
+}
+
+/// Map scanned entries to a per-page-index multiplier by matching each
+/// page's PDFium-reported size (already available to the caller) against
+/// the entries' MediaBox dimensions. Unmatched pages get 1.0.
+pub(crate) fn match_user_unit(entries: &[UserUnitEntry], width: f32, height: f32) -> f32 {
+ for entry in entries {
+ // FPDF_GetPageSizeByIndexF reflects /Rotate, so compare both ways.
+ if (close(width, entry.media_width) && close(height, entry.media_height))
+ || (close(width, entry.media_height) && close(height, entry.media_width))
+ {
+ return entry.user_unit;
+ }
+ }
+ 1.0
+}
+
+fn close(a: f32, b: f32) -> bool {
+ (a - b).abs() <= 0.5 + a.abs().max(b.abs()) * 1e-4
+}
+
+/// Whether a byte can continue a PDF name (i.e. is not a delimiter or
+/// whitespace per the PDF lexer).
+fn is_regular_char(byte: u8) -> bool {
+ !matches!(
+ byte,
+ b'\0'
+ | b'\t'
+ | b'\n'
+ | b'\x0c'
+ | b'\r'
+ | b' '
+ | b'('
+ | b')'
+ | b'<'
+ | b'>'
+ | b'['
+ | b']'
+ | b'{'
+ | b'}'
+ | b'/'
+ | b'%'
+ )
+}
+
+fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ if needle.is_empty() || haystack.len() < needle.len() {
+ return None;
+ }
+ haystack
+ .windows(needle.len())
+ .position(|window| window == needle)
+}
+
+/// Parse the first number at or after `start`, skipping PDF whitespace.
+fn parse_number_at(data: &[u8], start: usize) -> Option<f64> {
+ let mut i = start;
+ while i < data.len() && matches!(data[i], b'\0' | b'\t' | b'\n' | b'\x0c' | b'\r' | b' ') {
+ i += 1;
+ }
+ let num_start = i;
+ if i < data.len() && matches!(data[i], b'+' | b'-') {
+ i += 1;
+ }
+ let mut seen_digit = false;
+ while i < data.len() && (data[i].is_ascii_digit() || data[i] == b'.') {
+ seen_digit |= data[i].is_ascii_digit();
+ i += 1;
+ }
+ if !seen_digit {
+ return None;
+ }
+ std::str::from_utf8(&data[num_start..i]).ok()?.parse().ok()
+}
+
+/// Find the `N G obj … endobj` span containing `pos`. Returns byte offsets
+/// just after `obj` and at `endobj`.
+fn enclosing_object(data: &[u8], pos: usize) -> Option<(usize, usize)> {
+ // Backwards: nearest `obj` token preceded by whitespace (part of the
+ // `N G obj` header, distinguishing it from `endobj`).
+ let before = &data[..pos];
+ let mut obj_start = None;
+ let mut i = before.len();
+ while i >= 3 {
+ if &before[i - 3..i] == b"obj"
+ && (i < 6 || &before[i - 6..i] != b"endobj")
+ && before
+ .get(i.wrapping_sub(4))
+ .is_some_and(|b| b.is_ascii_whitespace())
+ {
+ obj_start = Some(i);
+ break;
+ }
+ i -= 1;
+ }
+ let obj_start = obj_start?;
+ let after = &data[pos..];
+ let obj_end = pos + find(after, b"endobj")?;
+ Some((obj_start, obj_end))
+}
+
+/// Parse `/MediaBox [a b c d]` inside an object slice into (width, height).
+fn parse_media_box(object: &[u8]) -> Option<(f32, f32)> {
+ let key_pos = find(object, b"/MediaBox")?;
+ let mut i = key_pos + b"/MediaBox".len();
+ while i < object.len() && object[i] != b'[' {
+ // Only whitespace may sit between the key and its array.
+ if !object[i].is_ascii_whitespace() {
+ return None;
+ }
+ i += 1;
+ }
+ i += 1; // past '['
+ let mut values = [0.0f64; 4];
+ for value in &mut values {
+ *value = parse_number_at(object, i)?;
+ // Advance past the parsed number.
+ while i < object.len() && object[i].is_ascii_whitespace() {
+ i += 1;
+ }
+ while i < object.len() && matches!(object[i], b'+' | b'-' | b'.' | b'0'..=b'9') {
+ i += 1;
+ }
+ }
+ Some((
+ (values[2] - values[0]).abs() as f32,
+ (values[3] - values[1]).abs() as f32,
+ ))
+}
+
+/// Cheap containment check for path-loaded documents: stream the file in
+/// chunks looking for `/UserUnit` so the (overwhelmingly common) negative
+/// case never allocates the whole file.
+pub(crate) fn file_mentions_user_unit(path: &str) -> bool {
+ use std::io::Read;
+ let Ok(mut file) = std::fs::File::open(path) else {
+ return false;
+ };
+ let mut buf = vec![0u8; 256 * 1024];
+ let overlap = NEEDLE.len() - 1;
+ let mut filled = 0usize;
+ loop {
+ let read = match file.read(&mut buf[filled..]) {
+ Ok(0) => return false,
+ Ok(n) => n,
+ Err(_) => return false,
+ };
+ let end = filled + read;
+ if find(&buf[..end], NEEDLE).is_some() {
+ return true;
+ }
+ // Keep the tail so a needle spanning the chunk boundary still hits.
+ let keep = end.min(overlap);
+ buf.copy_within(end - keep..end, 0);
+ filled = keep;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn scans_user_unit_with_media_box() {
+ let pdf = b"6 0 obj\n<</Type/Page/Parent 15 0 R/MediaBox[0 0 35.5 14156.25]\n/UserUnit 36/Tabs/S>>\nendobj\n";
+ let entries = scan_user_units(pdf);
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0].user_unit, 36.0);
+ assert!((entries[0].media_width - 35.5).abs() < 1e-3);
+ assert!((entries[0].media_height - 14156.25).abs() < 1e-2);
+ }
+
+ #[test]
+ fn ignores_user_unit_without_media_box_in_object() {
+ let pdf = b"6 0 obj\n<</Type/Page/Parent 15 0 R/UserUnit 36>>\nendobj\n";
+ assert!(scan_user_units(pdf).is_empty());
+ }
+
+ #[test]
+ fn ignores_default_and_invalid_values() {
+ let pdf = b"1 0 obj\n<</MediaBox[0 0 10 10]/UserUnit 1>>\nendobj\n\
+ 2 0 obj\n<</MediaBox[0 0 10 10]/UserUnit -5>>\nendobj\n\
+ 3 0 obj\n<</MediaBox[0 0 10 10]/UserUnit 999999>>\nendobj\n";
+ assert!(scan_user_units(pdf).is_empty());
+ }
+
+ #[test]
+ fn ignores_longer_names() {
+ let pdf = b"1 0 obj\n<</MediaBox[0 0 10 10]/UserUnitCustom 36>>\nendobj\n";
+ assert!(scan_user_units(pdf).is_empty());
+ }
+
+ #[test]
+ fn matches_rotated_dimensions() {
+ let entries = [UserUnitEntry {
+ media_width: 35.5,
+ media_height: 14156.25,
+ user_unit: 36.0,
+ }];
+ assert_eq!(match_user_unit(&entries, 35.5, 14156.25), 36.0);
+ assert_eq!(match_user_unit(&entries, 14156.25, 35.5), 36.0);
+ assert_eq!(match_user_unit(&entries, 612.0, 792.0), 1.0);
+ }
+
+ #[test]
+ fn parses_media_box_with_offsets_and_floats() {
+ let pdf = b"1 0 obj\n<</MediaBox [ -10.5 20 100.5 320 ] /UserUnit 2.5>>\nendobj\n";
+ let entries = scan_user_units(pdf);
+ assert_eq!(entries.len(), 1);
+ assert!((entries[0].media_width - 111.0).abs() < 1e-3);
+ assert!((entries[0].media_height - 300.0).abs() < 1e-3);
+ assert!((entries[0].user_unit - 2.5).abs() < 1e-6);
+ }
+}