Skip to content

A fast, helpful, and open-source document parser

Add page_orientation_corrections: counter-rotate pages by a caller-supplied angle

Logan Markewich52f8bffcefb6
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index 38212b3..f0761df 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -2,7 +2,9 @@ use std::collections::HashMap;
use napi_derive::napi;
-use liteparse::config::{CropBox, ImageMode, LiteParseConfig, OutputFormat};
+use liteparse::config::{
+ CropBox, ImageMode, LiteParseConfig, OutputFormat, PageOrientationCorrection,
+};
use liteparse::layout::{LayoutBlock, LayoutCell};
use liteparse::parser::ParseResult;
use liteparse::types::{
@@ -113,6 +115,13 @@ pub struct JsLiteParseConfig {
/// Drop diagonal text (rotation >2° off the nearest right angle). Default
/// false. Use to exclude rotated watermarks/stamps from the output.
pub skip_diagonal_text: Option<bool>,
+ /// Per-page orientation corrections from an upstream orientation
+ /// classifier. Each entry names a 1-based page and the clockwise angle
+ /// (0/90/180/270) by which its content appears rotated; LiteParse
+ /// counter-rotates that page before extraction so text, reading order,
+ /// page size and OCR rasters come out upright. Applied on top of the PDF's
+ /// own /Rotate. Unlisted or out-of-range pages are left unchanged.
+ pub page_orientation_corrections: Option<Vec<JsPageOrientationCorrection>>,
/// Compute per-page complexity signals during parse and attach them to each
/// page as `ParsedPage.complexity` (the same signals `isComplex` returns).
/// Default false; enabling it runs an extra vector-text detection pass.
@@ -121,6 +130,15 @@ pub struct JsLiteParseConfig {
pub extract_vector_graphics: Option<bool>,
}
+/// One page's orientation correction: `page` is 1-based, `angle` is the
+/// clockwise degrees (0/90/180/270) the content appears rotated.
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsPageOrientationCorrection {
+ pub page: u32,
+ pub angle: u32,
+}
+
/// A page sub-region as the fraction cropped from each side (top-left origin,
/// each in `[0, 1]`).
#[napi(object)]
@@ -253,6 +271,15 @@ impl JsLiteParseConfig {
if let Some(v) = self.skip_diagonal_text {
cfg.skip_diagonal_text = v;
}
+ if let Some(v) = self.page_orientation_corrections {
+ cfg.page_orientation_corrections = v
+ .into_iter()
+ .map(|c| PageOrientationCorrection {
+ page: c.page,
+ angle: u16::try_from(c.angle).unwrap_or(u16::MAX),
+ })
+ .collect();
+ }
if let Some(v) = self.include_complexity {
cfg.include_complexity = v;
}
@@ -321,6 +348,15 @@ impl JsLiteParseConfig {
left: c.left as f64,
}),
skip_diagonal_text: Some(cfg.skip_diagonal_text),
+ page_orientation_corrections: Some(
+ cfg.page_orientation_corrections
+ .iter()
+ .map(|c| JsPageOrientationCorrection {
+ page: c.page,
+ angle: u32::from(c.angle),
+ })
+ .collect(),
+ ),
include_complexity: Some(cfg.include_complexity),
extract_vector_graphics: Some(cfg.extract_vector_graphics),
}
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index bde0421..187917a 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -3,7 +3,9 @@ use std::collections::HashMap;
use pyo3::prelude::*;
use pyo3::types::PyBytes;
-use liteparse::config::{CropBox, ImageMode, LiteParseConfig, OutputFormat};
+use liteparse::config::{
+ CropBox, ImageMode, LiteParseConfig, OutputFormat, PageOrientationCorrection,
+};
use liteparse::types::PdfInput;
mod cli;
@@ -1265,6 +1267,8 @@ struct PyLiteParseConfig {
#[pyo3(get)]
skip_diagonal_text: bool,
#[pyo3(get)]
+ page_orientation_corrections: Vec<(u32, u16)>,
+ #[pyo3(get)]
include_complexity: bool,
#[pyo3(get)]
extract_text_metadata: bool,
@@ -1336,6 +1340,11 @@ impl PyLiteParseConfig {
.as_ref()
.map(|c| (c.top, c.right, c.bottom, c.left)),
skip_diagonal_text: cfg.skip_diagonal_text,
+ page_orientation_corrections: cfg
+ .page_orientation_corrections
+ .iter()
+ .map(|c| (c.page, c.angle))
+ .collect(),
include_complexity: cfg.include_complexity,
extract_text_metadata: cfg.extract_text_metadata,
image_output_dir: cfg.image_output_dir.clone(),
@@ -1466,6 +1475,7 @@ impl LiteParse {
extract_text_metadata = None,
crop_box = None,
skip_diagonal_text = None,
+ page_orientation_corrections = None,
include_complexity = None,
extract_vector_graphics = None,
))]
@@ -1505,6 +1515,7 @@ impl LiteParse {
extract_text_metadata: Option<bool>,
crop_box: Option<(f32, f32, f32, f32)>,
skip_diagonal_text: Option<bool>,
+ page_orientation_corrections: Option<Vec<(u32, u16)>>,
include_complexity: Option<bool>,
extract_vector_graphics: Option<bool>,
) -> PyResult<Self> {
@@ -1627,6 +1638,12 @@ impl LiteParse {
if let Some(v) = skip_diagonal_text {
cfg.skip_diagonal_text = v;
}
+ if let Some(v) = page_orientation_corrections {
+ cfg.page_orientation_corrections = v
+ .into_iter()
+ .map(|(page, angle)| PageOrientationCorrection { page, angle })
+ .collect();
+ }
if let Some(v) = include_complexity {
cfg.include_complexity = v;
}
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index 7d1f7e8..172b002 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -18,6 +18,7 @@ use wasm_bindgen_futures::JsFuture;
use liteparse::config::{
CropBox as CoreCropBox, ImageMode, LiteParseConfig as CoreConfig, OutputFormat,
+ PageOrientationCorrection as CorePageOrientationCorrection,
};
use liteparse::ocr::{OcrEngine, OcrOptions, OcrResult as CoreOcrResult};
use liteparse::parser::LiteParse as CoreLiteParse;
@@ -93,6 +94,13 @@ pub struct LiteParseConfig {
/// Drop diagonal text (rotation >2° off the nearest right angle). Default
/// false. Use to exclude rotated watermarks/stamps from the output.
skip_diagonal_text: Option<bool>,
+ /// Per-page orientation corrections from an upstream orientation
+ /// classifier. Each entry names a 1-based page and the clockwise angle
+ /// (0/90/180/270) by which its content appears rotated; LiteParse
+ /// counter-rotates that page before extraction so text, reading order,
+ /// page size and OCR rasters come out upright. Applied on top of the PDF's
+ /// own /Rotate. Unlisted or out-of-range pages are left unchanged.
+ page_orientation_corrections: Option<Vec<PageOrientationCorrection>>,
/// Compute per-page complexity signals during parse and attach them to each
/// page as `ParsedPage.complexity` (the same signals `isComplex` returns).
/// Default false; enabling it runs an extra vector-text detection pass.
@@ -123,6 +131,16 @@ pub struct CropBox {
left: f32,
}
+/// One page's orientation correction: `page` is 1-based, `angle` is the
+/// clockwise degrees (0/90/180/270) the content appears rotated.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, Tsify)]
+#[tsify(into_wasm_abi, from_wasm_abi)]
+#[serde(rename_all = "camelCase", default)]
+pub struct PageOrientationCorrection {
+ page: u32,
+ angle: u16,
+}
+
impl LiteParseConfig {
fn into_core(self) -> Result<CoreConfig, JsError> {
let mut cfg = CoreConfig::default();
@@ -235,6 +253,15 @@ impl LiteParseConfig {
if let Some(v) = self.skip_diagonal_text {
cfg.skip_diagonal_text = v;
}
+ if let Some(v) = self.page_orientation_corrections {
+ cfg.page_orientation_corrections = v
+ .into_iter()
+ .map(|c| CorePageOrientationCorrection {
+ page: c.page,
+ angle: c.angle,
+ })
+ .collect();
+ }
if let Some(v) = self.include_complexity {
cfg.include_complexity = v;
}
@@ -303,6 +330,15 @@ impl LiteParseConfig {
left: c.left,
}),
skip_diagonal_text: Some(cfg.skip_diagonal_text),
+ page_orientation_corrections: Some(
+ cfg.page_orientation_corrections
+ .iter()
+ .map(|c| PageOrientationCorrection {
+ page: c.page,
+ angle: c.angle,
+ })
+ .collect(),
+ ),
include_complexity: Some(cfg.include_complexity),
extract_vector_graphics: Some(cfg.extract_vector_graphics),
extract_text_metadata: Some(cfg.extract_text_metadata),
diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rs
index ff3a8f7..c56386d 100644
--- a/crates/liteparse/src/config.rs
+++ b/crates/liteparse/src/config.rs
@@ -154,6 +154,17 @@ pub struct LiteParseConfig {
/// Drop diagonal (skewed) text — items whose rotation is more than 2°
/// off the nearest right angle (0/90/180/270). Default `false`.
pub skip_diagonal_text: bool,
+ /// Per-page orientation corrections supplied by the caller, e.g. from an
+ /// upstream orientation classifier that saw the rendered page. Each entry
+ /// names a 1-based page and the clockwise angle (0/90/180/270) by which
+ /// that page's content *appears* rotated in its viewport; LiteParse
+ /// counter-rotates the page by that angle before extraction, so text
+ /// coordinates, reading order, page dimensions and OCR rasters all come out
+ /// upright. Applied on top of the PDF's own `/Rotate`. Pages not listed,
+ /// and pages past the end of the document, are left unchanged. Default
+ /// empty.
+ #[serde(default)]
+ pub page_orientation_corrections: Vec<PageOrientationCorrection>,
/// Compute per-page complexity signals during `parse` and attach them to
/// each `ParsedPage` (surfaced as a `complexity` object per page in JSON).
/// These are the same signals the standalone `is_complex` API returns.
@@ -165,6 +176,35 @@ pub struct LiteParseConfig {
pub extract_vector_graphics: bool,
}
+/// A caller-supplied orientation correction for one page. See
+/// [`LiteParseConfig::page_orientation_corrections`].
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+pub struct PageOrientationCorrection {
+ /// 1-based document page number.
+ pub page: u32,
+ /// Clockwise degrees the page content appears rotated in its viewport;
+ /// must be one of 0, 90, 180, 270.
+ pub angle: u16,
+}
+
+impl PageOrientationCorrection {
+ /// Quarter turns to *add* to the page's `/Rotate` so the content reads
+ /// upright: undoing a clockwise `angle` means rotating the page by
+ /// `360 - angle` clockwise. Errors on a non-cardinal angle.
+ pub fn quarter_turns_to_apply(&self) -> Result<i32, String> {
+ match self.angle {
+ 0 => Ok(0),
+ 90 => Ok(3),
+ 180 => Ok(2),
+ 270 => Ok(1),
+ other => Err(format!(
+ "page_orientation_corrections: page {} has angle {other}; expected 0, 90, 180 or 270",
+ self.page
+ )),
+ }
+ }
+}
+
/// A page sub-region expressed as the fraction cropped from each side.
/// All fields are in `[0, 1]`; `left + right < 1` and `top + bottom < 1`
/// for a non-empty region. Origin is top-left, matching `TextItem` coordinates.
@@ -261,6 +301,7 @@ impl Default for LiteParseConfig {
extract_text_metadata: false,
crop_box: None,
skip_diagonal_text: false,
+ page_orientation_corrections: Vec::new(),
include_complexity: false,
extract_vector_graphics: false,
}
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index b0e8ca4..b258867 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -39,6 +39,37 @@ pub(crate) fn load_document_from_input<'lib>(
}
}
+/// Rewrite `/Rotate` on every page named in `corrections` so its content
+/// reads upright (see `LiteParseConfig::page_orientation_corrections`).
+///
+/// PDFium stores the new rotation in the page dictionary of the open
+/// document, so it survives every later `FPDF_LoadPage` of that page: text
+/// extraction, OCR rasters and screenshots all see the corrected page without
+/// any further plumbing. It does NOT survive reopening the input, which is why
+/// every document open in `parser.rs` goes through
+/// `LiteParse::open_document` rather than this crate's raw loader.
+///
+/// Pages past the end of the document are skipped: a caller that parses a
+/// page slice (`target_pages`) may hand over corrections for the whole
+/// document. A non-cardinal angle is a config error.
+pub(crate) fn apply_page_orientation_corrections(
+ document: &Document,
+ corrections: &[crate::config::PageOrientationCorrection],
+) -> Result<(), LiteParseError> {
+ let page_count = document.page_count().max(0) as u32;
+ for correction in corrections {
+ let quarter_turns = correction
+ .quarter_turns_to_apply()
+ .map_err(LiteParseError::Config)?;
+ if quarter_turns == 0 || correction.page == 0 || correction.page > page_count {
+ continue;
+ }
+ let page = document.page((correction.page - 1) as i32)?;
+ page.set_rotation((page.rotation() + quarter_turns).rem_euclid(4));
+ }
+ Ok(())
+}
+
/// Extract pages from a `PdfInput` (file path or bytes) with filtering.
///
/// This convenience entry point acquires the PDFium lock internally for the
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index e298d39..ed364ce 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -313,6 +313,25 @@ impl LiteParse {
.map_err(|e| format!("invalid --target-pages: {}", e).into())
}
+ /// Open `input` and apply the configured per-page orientation
+ /// corrections. `/Rotate` rewrites live in the open document only, so
+ /// every code path that reopens the input (extraction, OCR rounds, the
+ /// pristine form-render copy, batch sessions) must open through here to
+ /// see the same page geometry.
+ fn open_document<'lib>(
+ &self,
+ lib: &'lib Library,
+ input: &PdfInput,
+ password: Option<&str>,
+ ) -> Result<pdfium::Document<'lib>, LiteParseError> {
+ let document = extract::load_document_from_input(lib, input, password)?;
+ extract::apply_page_orientation_corrections(
+ &document,
+ &self.config.page_orientation_corrections,
+ )?;
+ Ok(document)
+ }
+
fn validate_output_config(&self) -> Result<(), LiteParseError> {
if self.config.image_output_dir.is_some() && !self.config.effective_extract_images() {
return Err(LiteParseError::Config(
@@ -361,7 +380,7 @@ impl LiteParse {
let (pages, mut page_complexities) = {
let lib = Library::init();
- let document = extract::load_document_from_input(&lib, &validated_input, password)?;
+ let document = self.open_document(&lib, &validated_input, password)?;
// Complexity deliberately runs against the flattened document: once
// widget text lives in the content stream it is genuinely within
@@ -604,7 +623,7 @@ impl LiteParse {
let document_input = repaired_input.as_ref().unwrap_or(validated_input);
#[cfg(target_arch = "wasm32")]
let document_input = validated_input;
- let document = extract::load_document_from_input(&lib, document_input, password)?;
+ let document = self.open_document(&lib, document_input, password)?;
let total_pages = document.page_count().max(0) as u32;
let form_type = self
.config
@@ -695,7 +714,7 @@ impl LiteParse {
&& self.config.extract_screenshots
&& self.config.render_form_fields;
let pristine_document = needs_pristine_document
- .then(|| extract::load_document_from_input(&lib, document_input, password))
+ .then(|| self.open_document(&lib, document_input, password))
.transpose()?;
let analysis_document = pristine_document.as_ref().unwrap_or(&document);
let t_extract = web_time::Instant::now();
@@ -796,7 +815,7 @@ impl LiteParse {
while round_start < pages.len() {
let (rendered, next_start) = {
let lib = Library::init();
- let document = extract::load_document_from_input(&lib, ocr_input, password)?;
+ let document = self.open_document(&lib, ocr_input, password)?;
ocr_merge::render_pages_for_ocr(
&document,
&pages,
@@ -1110,6 +1129,7 @@ impl LiteParse {
self.config.password.as_deref(),
self.config.detect_screenshot_rects,
self.config.render_form_fields,
+ &self.config.page_orientation_corrections,
)?;
Ok(rendered
diff --git a/crates/liteparse/src/render.rs b/crates/liteparse/src/render.rs
index 1bd481b..dfce1f8 100644
--- a/crates/liteparse/src/render.rs
+++ b/crates/liteparse/src/render.rs
@@ -1,5 +1,6 @@
+use crate::config::PageOrientationCorrection;
use crate::error::LiteParseError;
-use crate::extract::{encode_png, load_document_from_input};
+use crate::extract::{apply_page_orientation_corrections, encode_png, load_document_from_input};
use crate::types::{PdfInput, ScreenshotRect};
use pdfium::Library;
use serde::Serialize;
@@ -44,9 +45,11 @@ pub fn render_pages_to_png(
password: Option<&str>,
detect_rects: bool,
render_form_fields: bool,
+ page_orientation_corrections: &[PageOrientationCorrection],
) -> Result<Vec<RenderedPage>, LiteParseError> {
let lib = Library::init();
let document = load_document_from_input(&lib, input, password)?;
+ apply_page_orientation_corrections(&document, page_orientation_corrections)?;
render_document_pages(
&document,
page_numbers,
@@ -278,7 +281,7 @@ pub fn screenshot(
password: Option<&str>,
) -> Result<(), LiteParseError> {
let input = PdfInput::Path(pdf_path.to_string());
- let pages = render_pages_to_png(&input, Some(&[page_num]), dpi, password, false, false)?;
+ let pages = render_pages_to_png(&input, Some(&[page_num]), dpi, password, false, false, &[])?;
let page = pages
.into_iter()
.next()
diff --git a/crates/liteparse/tests/integration_test.rs b/crates/liteparse/tests/integration_test.rs
index ba470ca..1b0e5eb 100644
--- a/crates/liteparse/tests/integration_test.rs
+++ b/crates/liteparse/tests/integration_test.rs
@@ -1073,3 +1073,127 @@ fn raw_text_diagonal_grounding_bounds_follow_the_glyph_outlines() {
);
}
}
+
+// ---------------------------------------------------------------------------
+// page_orientation_corrections
+//
+// `sample_rotated_180.pdf` / `sample_rotated_90cw.pdf` are `sample.pdf` with
+// a `/Rotate` applied via `qpdf --rotate`, so their content *appears* rotated
+// in the viewport exactly the way a scanned upside-down / sideways page would
+// to an orientation classifier. A correction equal to that apparent rotation
+// must give back the upright parse.
+// ---------------------------------------------------------------------------
+
+fn text_only_parser(corrections: Vec<liteparse::config::PageOrientationCorrection>) -> LiteParse {
+ LiteParse::new(LiteParseConfig {
+ ocr_enabled: false,
+ quiet: true,
+ page_orientation_corrections: corrections,
+ ..LiteParseConfig::default()
+ })
+}
+
+fn correction(page: u32, angle: u16) -> liteparse::config::PageOrientationCorrection {
+ liteparse::config::PageOrientationCorrection { page, angle }
+}
+
+#[tokio::test]
+async fn test_rotated_fixture_reads_wrong_without_correction() {
+ let upright = text_only_parser(vec![])
+ .parse("../../integration_tests_data/sample.pdf")
+ .await
+ .unwrap();
+ let rotated = text_only_parser(vec![])
+ .parse("../../integration_tests_data/sample_rotated_180.pdf")
+ .await
+ .unwrap();
+ assert_ne!(
+ upright.pages[0].text, rotated.pages[0].text,
+ "fixture is not actually inverted; the correction test below would be vacuous"
+ );
+}
+
+#[tokio::test]
+async fn test_orientation_correction_180_restores_upright_parse() {
+ let upright = text_only_parser(vec![])
+ .parse("../../integration_tests_data/sample.pdf")
+ .await
+ .unwrap();
+ let corrected = text_only_parser(vec![correction(1, 180)])
+ .parse("../../integration_tests_data/sample_rotated_180.pdf")
+ .await
+ .unwrap();
+ assert_eq!(corrected.pages[0].text, upright.pages[0].text);
+ assert_eq!(corrected.pages[0].page_width, upright.pages[0].page_width);
+ assert_eq!(corrected.pages[0].page_height, upright.pages[0].page_height);
+}
+
+#[tokio::test]
+async fn test_orientation_correction_90_restores_upright_parse() {
+ let upright = text_only_parser(vec![])
+ .parse("../../integration_tests_data/sample.pdf")
+ .await
+ .unwrap();
+ // `--rotate=+90` displays the page turned 90° clockwise, so the content
+ // appears rotated 90° clockwise: the correction angle is 90.
+ let corrected = text_only_parser(vec![correction(1, 90)])
+ .parse("../../integration_tests_data/sample_rotated_90cw.pdf")
+ .await
+ .unwrap();
+ assert_eq!(corrected.pages[0].text, upright.pages[0].text);
+ assert_eq!(corrected.pages[0].page_width, upright.pages[0].page_width);
+ assert_eq!(corrected.pages[0].page_height, upright.pages[0].page_height);
+}
+
+#[tokio::test]
+async fn test_orientation_correction_applies_to_screenshots() {
+ let upright = LiteParse::new(LiteParseConfig {
+ ocr_enabled: false,
+ quiet: true,
+ ..LiteParseConfig::default()
+ })
+ .screenshot("../../integration_tests_data/sample.pdf", None)
+ .await
+ .unwrap();
+ let corrected = LiteParse::new(LiteParseConfig {
+ ocr_enabled: false,
+ quiet: true,
+ page_orientation_corrections: vec![correction(1, 90)],
+ ..LiteParseConfig::default()
+ })
+ .screenshot("../../integration_tests_data/sample_rotated_90cw.pdf", None)
+ .await
+ .unwrap();
+ // A sideways page renders landscape; the correction must turn it back.
+ assert_eq!(
+ (corrected[0].width, corrected[0].height),
+ (upright[0].width, upright[0].height)
+ );
+}
+
+#[tokio::test]
+async fn test_orientation_correction_ignores_out_of_range_pages() {
+ let upright = text_only_parser(vec![])
+ .parse("../../integration_tests_data/sample.pdf")
+ .await
+ .unwrap();
+ let corrected = text_only_parser(vec![correction(7, 180), correction(1, 0)])
+ .parse("../../integration_tests_data/sample.pdf")
+ .await
+ .unwrap();
+ assert_eq!(corrected.pages[0].text, upright.pages[0].text);
+}
+
+#[tokio::test]
+async fn test_orientation_correction_rejects_non_cardinal_angle() {
+ let result = text_only_parser(vec![correction(1, 45)])
+ .parse("../../integration_tests_data/sample.pdf")
+ .await;
+ match result {
+ Err(liteparse::LiteParseError::Config(message)) => {
+ assert!(message.contains("45"), "{message}")
+ }
+ Err(other) => panic!("expected a config error, got {other}"),
+ Ok(_) => panic!("45° is not a valid correction and must be rejected"),
+ }
+}
diff --git a/crates/pdfium-sys/src/dynamic.rs b/crates/pdfium-sys/src/dynamic.rs
index b7ebda7..9a242f9 100644
--- a/crates/pdfium-sys/src/dynamic.rs
+++ b/crates/pdfium-sys/src/dynamic.rs
@@ -126,6 +126,7 @@ 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,
+ pub FPDFPage_SetRotation: unsafe extern "C" fn(FPDF_PAGE, std::os::raw::c_int),
pub FPDFPage_SetCropBox: unsafe extern "C" fn(FPDF_PAGE, f32, f32, f32, f32),
/// LlamaParse fork API (absent from stock pdfium and older fork
/// releases); callers fall back to the raw-byte `/UserUnit` scan.
@@ -623,6 +624,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_SetRotation: load_fn!(lib, "FPDFPage_SetRotation"),
FPDFPage_SetCropBox: load_fn!(lib, "FPDFPage_SetCropBox"),
FPDFPage_GetUserUnit: load_fn_opt!(lib, "FPDFPage_GetUserUnit"),
FPDFPage_Flatten: load_fn_opt!(lib, "FPDFPage_Flatten"),
diff --git a/crates/pdfium/src/page.rs b/crates/pdfium/src/page.rs
index e8e661b..23aab6c 100644
--- a/crates/pdfium/src/page.rs
+++ b/crates/pdfium/src/page.rs
@@ -269,10 +269,22 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
self.user_unit
}
+ /// The page's `/Rotate` in quarter turns clockwise (0..=3), as PDFium
+ /// reports it.
pub fn rotation(&self) -> i32 {
unsafe { ffi!(FPDFPage_GetRotation(self.handle)) }
}
+ /// Overwrite the page's `/Rotate` with `quarter_turns` (0..=3, clockwise
+ /// when displayed). PDFium writes the value into the page dictionary and
+ /// recomputes the page size, so [`Self::width`] / [`Self::height`], the
+ /// viewport mapping, and every later `FPDF_LoadPage` of this page in the
+ /// same document see the new rotation. Values outside 0..=3 are ignored
+ /// by PDFium.
+ pub fn set_rotation(&self, quarter_turns: i32) {
+ unsafe { ffi!(FPDFPage_SetRotation(self.handle, quarter_turns)) }
+ }
+
/// Replace the page's `/CropBox` (PDF user space, points, bottom-left origin).
/// pdfium recomputes the page size, so [`Self::width`], [`Self::height`],
/// [`Self::view_box`] and any later render see the new box. This is how a
diff --git a/docs/src/content/docs/liteparse/guides/browser-usage.md b/docs/src/content/docs/liteparse/guides/browser-usage.md
index 1118a13..8cf5815 100644
--- a/docs/src/content/docs/liteparse/guides/browser-usage.md
+++ b/docs/src/content/docs/liteparse/guides/browser-usage.md
@@ -97,6 +97,7 @@ All optional, camelCase:
| `preserveVerySmallText` | `boolean` | `false` | Keep tiny text that's normally filtered |
| `skipDiagonalText` | `boolean` | `false` | Drop text more than 2° off the nearest right angle |
| `cropBox` | `{ top, right, bottom, left }` | — | Fraction to crop from each side of every page |
+| `pageOrientationCorrections` | `{ page, angle }[]` | — | Counter-rotate listed pages (1-based) by the clockwise `angle` (0/90/180/270) their content appears rotated |
| `password` | `string` | — | Password for protected PDFs |
| `quiet` | `boolean` | `false` | Suppress progress logging |
| `imageMode` | `"off" \| "placeholder" \| "embed"` | `"placeholder"` | How image references appear in markdown. Also accepts `"none"` for `off` |
diff --git a/docs/src/content/docs/liteparse/guides/extraction.mdx b/docs/src/content/docs/liteparse/guides/extraction.mdx
index 1f08d12..f17e7a6 100644
--- a/docs/src/content/docs/liteparse/guides/extraction.mdx
+++ b/docs/src/content/docs/liteparse/guides/extraction.mdx
@@ -427,6 +427,7 @@ A few config options are only reachable from the library and bindings:
| `emit_word_boxes` | Per-word sub-boxes (see above). |
| `crop_box` | Restrict output to a sub-region of each page. A text item is kept only if it falls entirely inside. |
| `skip_diagonal_text` | Drop text rotated more than 2° off the nearest right angle — watermarks and diagonal stamps. |
+| `page_orientation_corrections` | Counter-rotate specific pages before extraction, using angles from your own orientation classifier (see below). |
| `detect_screenshot_rects` | Populate `rects` on screenshot results. |
| `render_form_fields` | Draw form-field appearances into rendered pages. |
| `ocr_failure_fatal` | When `false`, a systemic OCR failure returns partial results instead of erroring. Defaults to `true`. |
@@ -455,6 +456,42 @@ parser = LiteParse(crop_box=(0.1, 0.0, 0.05, 0.0))
</TabItem>
</Tabs>
+### Correcting page orientation
+
+LiteParse honours a page's `/Rotate` entry, but a scanned page whose *content* is
+upside down or sideways carries no such hint: its text layer (or OCR raster) reads
+bottom-up, so reading order and label/value pairs come out inverted. If you run an
+orientation classifier on the rendered page, hand its verdict to
+`page_orientation_corrections`. Each entry names a 1-based page and the clockwise
+angle (`0`, `90`, `180` or `270`) by which that page's content appears rotated;
+LiteParse counter-rotates the page before extraction, so text coordinates, reading
+order, page dimensions, OCR rasters and screenshots all come out upright. Pages not
+listed, or past the end of the document, are left unchanged.
+
+<Tabs>
+<TabItem label="TypeScript" value="typescript">
+
+```typescript
+// Page 3 was scanned upside down, page 7 sideways (content rotated 90° clockwise)
+const parser = new LiteParse({
+ pageOrientationCorrections: [
+ { page: 3, angle: 180 },
+ { page: 7, angle: 90 },
+ ],
+});
+```
+
+</TabItem>
+<TabItem label="Python" value="python">
+
+```python
+# (page, angle) pairs
+parser = LiteParse(page_orientation_corrections=[(3, 180), (7, 90)])
+```
+
+</TabItem>
+</Tabs>
+
## Next steps
- [Document complexity](/liteparse/guides/complexity/): Route documents before you parse them.
diff --git a/integration_tests_data/sample_rotated_180.pdf b/integration_tests_data/sample_rotated_180.pdf
new file mode 100644
index 0000000..d41bb21
Binary files /dev/null and b/integration_tests_data/sample_rotated_180.pdf differ
diff --git a/integration_tests_data/sample_rotated_90cw.pdf b/integration_tests_data/sample_rotated_90cw.pdf
new file mode 100644
index 0000000..ce48da4
Binary files /dev/null and b/integration_tests_data/sample_rotated_90cw.pdf differ
diff --git a/packages/node/native.d.ts b/packages/node/native.d.ts
index 3a6f4dd..f129b6f 100644
--- a/packages/node/native.d.ts
+++ b/packages/node/native.d.ts
@@ -71,8 +71,7 @@ export interface JsLiteParseConfig {
/**
* Emit each page's classified layout blocks (headings, paragraphs, list
* items, tables with per-cell boxes, code, rules, figures) with bounding
- * boxes as `ParsedPage.blocks`. Default false. Independent of
- * `outputFormat`; enabling it never changes the rendered markdown.
+ * boxes as `ParsedPage.blocks`. Default false.
*/
extractBlocks?: boolean
/** Extract AcroForm widget fields and values. */
@@ -136,6 +135,15 @@ export interface JsLiteParseConfig {
* false. Use to exclude rotated watermarks/stamps from the output.
*/
skipDiagonalText?: boolean
+ /**
+ * Per-page orientation corrections from an upstream orientation
+ * classifier. Each entry names a 1-based page and the clockwise angle
+ * (0/90/180/270) by which its content appears rotated; LiteParse
+ * counter-rotates that page before extraction so text, reading order,
+ * page size and OCR rasters come out upright. Applied on top of the PDF's
+ * own /Rotate. Unlisted or out-of-range pages are left unchanged.
+ */
+ pageOrientationCorrections?: Array<JsPageOrientationCorrection>
/**
* Compute per-page complexity signals during parse and attach them to each
* page as `ParsedPage.complexity` (the same signals `isComplex` returns).
@@ -145,6 +153,14 @@ export interface JsLiteParseConfig {
/** Expose page-scoped vector path extraction. Default false. */
extractVectorGraphics?: boolean
}
+/**
+ * One page's orientation correction: `page` is 1-based, `angle` is the
+ * clockwise degrees (0/90/180/270) the content appears rotated.
+ */
+export interface JsPageOrientationCorrection {
+ page: number
+ angle: number
+}
/**
* A page sub-region as the fraction cropped from each side (top-left origin,
* each in `[0, 1]`).
@@ -241,6 +257,12 @@ export interface JsPageInput {
}
export interface JsParsedPage {
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; fall back to `page_num` when absent.
+ */
+ pageLabel?: string
width: number
height: number
/**
diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.ts
index d78a793..5767161 100644
--- a/packages/node/src/lib.ts
+++ b/packages/node/src/lib.ts
@@ -130,6 +130,17 @@ export interface LiteParseConfig {
* watermarks/stamps from the output.
*/
skipDiagonalText: boolean;
+ /**
+ * Per-page orientation corrections from an upstream orientation classifier
+ * (one that saw the rendered page). Each entry names a 1-based page and the
+ * clockwise angle (0/90/180/270) by which that page's content *appears*
+ * rotated in its viewport; LiteParse counter-rotates the page before
+ * extraction, so text coordinates, reading order, page dimensions and OCR
+ * rasters all come out upright. Applied on top of the PDF's own `/Rotate`.
+ * Pages not listed, or past the end of the document, are left unchanged.
+ * Default: none.
+ */
+ pageOrientationCorrections?: PageOrientationCorrection[];
/**
* Compute per-page complexity signals during {@link LiteParse.parse} and
* attach them to each page as {@link ParsedPage.complexity} (the same signals
@@ -152,6 +163,17 @@ export interface CropBox {
left: number;
}
+/**
+ * One page's orientation correction (see
+ * {@link LiteParseConfig.pageOrientationCorrections}).
+ */
+export interface PageOrientationCorrection {
+ /** 1-based document page number. */
+ page: number;
+ /** Clockwise degrees the content appears rotated: 0, 90, 180 or 270. */
+ angle: 0 | 90 | 180 | 270;
+}
+
/**
* One word's bounding box within a {@link TextItem}, in the same viewport space
* (top-left origin, 72 DPI). `text` excludes inter-word spaces.
@@ -671,6 +693,7 @@ export class LiteParse {
extractTextMetadata: userConfig.extractTextMetadata,
cropBox: userConfig.cropBox,
skipDiagonalText: userConfig.skipDiagonalText,
+ pageOrientationCorrections: userConfig.pageOrientationCorrections,
includeComplexity: userConfig.includeComplexity,
extractVectorGraphics: userConfig.extractVectorGraphics,
};
@@ -731,6 +754,8 @@ export class LiteParse {
extractTextMetadata: resolved.extractTextMetadata ?? false,
cropBox: resolved.cropBox ?? undefined,
skipDiagonalText: resolved.skipDiagonalText ?? false,
+ pageOrientationCorrections:
+ (resolved.pageOrientationCorrections as PageOrientationCorrection[] | undefined) ?? undefined,
includeComplexity: resolved.includeComplexity ?? false,
extractVectorGraphics: resolved.extractVectorGraphics ?? false,
};
diff --git a/packages/node/src/native.ts b/packages/node/src/native.ts
index 5100a5d..ce8b6e8 100644
--- a/packages/node/src/native.ts
+++ b/packages/node/src/native.ts
@@ -55,6 +55,7 @@ export interface LiteParseNativeConfig {
extractTextMetadata?: boolean;
cropBox?: NativeCropBox;
skipDiagonalText?: boolean;
+ pageOrientationCorrections?: NativePageOrientationCorrection[];
includeComplexity?: boolean;
extractVectorGraphics?: boolean;
}
@@ -66,6 +67,11 @@ export interface NativeCropBox {
left: number;
}
+export interface NativePageOrientationCorrection {
+ page: number;
+ angle: number;
+}
+
export interface NativeWordBox {
text: string;
x: number;
diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.py
index c3e081d..a56f023 100644
--- a/packages/python/liteparse/parser.py
+++ b/packages/python/liteparse/parser.py
@@ -490,6 +490,7 @@ class LiteParse:
extract_text_metadata: Optional[bool] = None,
crop_box: Optional[Tuple[float, float, float, float]] = None,
skip_diagonal_text: Optional[bool] = None,
+ page_orientation_corrections: Optional[List[Tuple[int, int]]] = None,
include_complexity: Optional[bool] = None,
extract_vector_graphics: Optional[bool] = None,
pool_size: Optional[int] = None,
@@ -566,6 +567,14 @@ class LiteParse:
skip_diagonal_text: Drop diagonal text — items whose rotation is
more than 2° off the nearest right angle (0/90/180/270).
Default False. Use to exclude rotated watermarks/stamps.
+ page_orientation_corrections: Per-page orientation corrections
+ from an upstream orientation classifier, as ``(page, angle)``
+ pairs: the 1-based page and the clockwise degrees (0, 90, 180
+ or 270) by which its content appears rotated. LiteParse
+ counter-rotates those pages before extraction so text,
+ reading order, page size and OCR rasters come out upright.
+ Applied on top of the PDF's own ``/Rotate``; unlisted or
+ out-of-range pages are left unchanged. Default None.
include_complexity: Compute per-page complexity signals during
:meth:`parse` and attach them to each page as
``ParsedPage.complexity`` (the same :meth:`is_complex` returns).
@@ -651,6 +660,10 @@ class LiteParse:
kwargs["crop_box"] = crop_box
if skip_diagonal_text is not None:
kwargs["skip_diagonal_text"] = skip_diagonal_text
+ if page_orientation_corrections is not None:
+ kwargs["page_orientation_corrections"] = [
+ (int(page), int(angle)) for page, angle in page_orientation_corrections
+ ]
if include_complexity is not None:
kwargs["include_complexity"] = include_complexity
if extract_vector_graphics is not None:
@@ -962,6 +975,7 @@ class LiteParse:
emit_word_boxes=cfg.emit_word_boxes,
crop_box=cfg.crop_box,
skip_diagonal_text=cfg.skip_diagonal_text,
+ page_orientation_corrections=list(cfg.page_orientation_corrections),
include_complexity=cfg.include_complexity,
extract_text_metadata=cfg.extract_text_metadata,
extract_images=cfg.extract_images,
diff --git a/packages/python/liteparse/types.py b/packages/python/liteparse/types.py
index 4e6cfcf..a56722d 100644
--- a/packages/python/liteparse/types.py
+++ b/packages/python/liteparse/types.py
@@ -483,6 +483,9 @@ class LiteParseConfig:
crop_box: Optional[Tuple[float, float, float, float]]
skip_diagonal_text: bool
include_complexity: bool
+ #: ``(page, angle)`` pairs: 1-based page and the clockwise degrees
+ #: (0/90/180/270) its content appears rotated. Empty when none.
+ page_orientation_corrections: List[Tuple[int, int]] = field(default_factory=list)
extract_text_metadata: bool = False
#: Keep running headers/footers in markdown output instead of stripping
#: repeated page-band lines and page chrome.