Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewich88f62005349f
diff --git a/crates/liteparse/Cargo.toml b/crates/liteparse/Cargo.toml
index 861e95a..6aa8f30 100644
--- a/crates/liteparse/Cargo.toml
+++ b/crates/liteparse/Cargo.toml
@@ -76,9 +76,7 @@ tesseract = ["dep:tesseract-rs"]
office-native = []
docx-native = ["dep:liteparse-ooxml", "liteparse-ooxml/raster", "office-native"]
pptx-native = ["dep:liteparse-ooxml", "liteparse-ooxml/raster", "office-native"]
-# Emitter only so far — `parser.rs` routes `.xlsx` through LibreOffice until
-# the XLSX geometry pass lands (`office/mod.rs` says why). No raster needed.
-xlsx-native = ["dep:liteparse-ooxml", "office-native"]
+xlsx-native = ["dep:liteparse-ooxml", "liteparse-ooxml/raster", "office-native"]
[dependencies]
blake3 = "1"
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index bc05ab2..fcb41ae 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -1436,10 +1436,14 @@ impl LiteParse {
///
/// `unit` names the page population in the out-of-range message so a deck
/// says "slides" where a document says "pages"; it is the only thing that
- /// differs between the DOCX and PPTX callers, because by this point both
- /// are just a `[LayoutedPage]`.
+ /// differs between the DOCX, PPTX and XLSX callers, because by this point
+ /// all three are just a `[LayoutedPage]`.
#[cfg(all(
- any(feature = "docx-native", feature = "pptx-native"),
+ any(
+ feature = "docx-native",
+ feature = "pptx-native",
+ feature = "xlsx-native"
+ ),
not(target_arch = "wasm32")
))]
fn rasterize_native_pages(
@@ -1451,6 +1455,18 @@ impl LiteParse {
) -> Result<Vec<ScreenshotResult>, LiteParseError> {
let (container, noun) = unit;
let page_count = layouted.len() as u32;
+ // A zero-page layout is an engine failure, not an empty document:
+ // every reader here gives a sheet, a slide or a section at least one
+ // page, so nothing to draw means nothing was read. Degrading is the
+ // only useful answer — one corpus workbook has 12 KB of junk ahead of
+ // its local headers, which this reader walks to zero sheets and
+ // LibreOffice recovers. Returning "page 1 out of range (0 pages)"
+ // instead would hand the caller a range error it cannot act on.
+ if page_count == 0 {
+ return Err(LiteParseError::Conversion(format!(
+ "native layout produced no {noun}"
+ )));
+ }
let pages: Vec<u32> = match page_numbers {
Some(nums) => nums.to_vec(),
None => (1..=page_count).collect(),
@@ -1532,6 +1548,57 @@ impl LiteParse {
self.rasterize_native_pages(&geo.layouts, &registry, page_numbers, ("deck", "slides"))
}
+ /// Native XLSX screenshot: the DOCX/PPTX contract over the grid painter's
+ /// own commands. `Conversion` means the engine failed and the caller
+ /// should fall back to LibreOffice; anything else is the caller's error.
+ #[cfg(all(feature = "xlsx-native", not(target_arch = "wasm32")))]
+ fn try_screenshot_xlsx_native(
+ &self,
+ data: &[u8],
+ page_numbers: Option<&[u32]>,
+ ) -> Result<Vec<ScreenshotResult>, LiteParseError> {
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ self.screenshot_xlsx_native_inner(data, page_numbers)
+ }))
+ .unwrap_or_else(|_| {
+ Err(LiteParseError::Conversion(
+ "native xlsx layout panicked".to_string(),
+ ))
+ })
+ }
+
+ #[cfg(all(feature = "xlsx-native", not(target_arch = "wasm32")))]
+ fn screenshot_xlsx_native_inner(
+ &self,
+ data: &[u8],
+ page_numbers: Option<&[u32]>,
+ ) -> Result<Vec<ScreenshotResult>, LiteParseError> {
+ use crate::office::{xlsx, xlsx_layout};
+
+ let wb = liteparse_ooxml::xlsx::read(data)
+ .map_err(|e| LiteParseError::Conversion(format!("xlsx parse failed: {e}")))?;
+ // A workbook embeds no fonts, so the registry is the host's — same
+ // construction as the PPTX path, including its no-faces check.
+ let registry = liteparse_ooxml::render::fonts::FontRegistry::build(&[], &[])
+ .map_err(|e| LiteParseError::Conversion(format!("font registry: {e}")))?;
+ // The one call that differs from the parse side: `paint: true` plus a
+ // registry, which is what turns the pass's grid and cell values into
+ // draw commands. Figures and image bytes stay off — the floating
+ // layer does not paint yet, so asking for it would only copy bytes
+ // nothing draws.
+ let nx = xlsx_layout::workbook_to_pages(
+ &wb,
+ xlsx::EmitOptions {
+ links: false,
+ figures: false,
+ images: false,
+ paint: true,
+ },
+ Some(&registry),
+ );
+ self.rasterize_native_pages(&nx.layouts, &registry, page_numbers, ("workbook", "pages"))
+ }
+
/// `parse_from_pages`'s native sibling: no projection — the block model
/// arrives from the DOCX source, so markdown is `render_blocks` per page
/// and page text is a straight reading-order join of the text items.
@@ -1694,6 +1761,23 @@ impl LiteParse {
}
}
+ // Native XLSX raster, same contract again: the grid painter draws the
+ // page the geometry pass already numbered, so a screenshot and the
+ // native `TextItem`s share one coordinate space. LibreOffice paginates
+ // a sheet by its own print rules, so the converted PDF never did.
+ #[cfg(all(feature = "xlsx-native", not(target_arch = "wasm32")))]
+ if self.config.office_native
+ && let Some(bytes) = crate::office::xlsx_bytes(&input)
+ {
+ match self.try_screenshot_xlsx_native(&bytes, page_numbers.as_deref()) {
+ Ok(results) => return Ok(results),
+ Err(LiteParseError::Conversion(e)) => log(&format!(
+ "[liteparse] native xlsx screenshot failed ({e}); falling back to conversion"
+ )),
+ Err(e) => return Err(e),
+ }
+ }
+
let (validated_input, _guard) =
conversion::resolve_pdf_input(input, self.config.password.as_deref(), true).await?;
diff --git a/crates/liteparse/tests/integration_test.rs b/crates/liteparse/tests/integration_test.rs
index 55e0e37..556dbce 100644
--- a/crates/liteparse/tests/integration_test.rs
+++ b/crates/liteparse/tests/integration_test.rs
@@ -851,3 +851,77 @@ async fn test_pptx_native_extracts_images() {
}
assert!(refs > 0, "figure refs reach the markdown");
}
+
+/// Native XLSX screenshots: the sheet is rastered from the grid painter's own
+/// draw commands, over the pages the geometry pass already numbered.
+///
+/// The coordinate-space parity assertion is the load-bearing one, and it means
+/// more here than it did for the deck: LibreOffice paginates a sheet by its own
+/// print rules, so the converted PDF's page 2 was never this pass's page 2. A
+/// native raster and a native `TextItem` now share one page *and* one box.
+#[cfg(feature = "xlsx-native")]
+#[tokio::test]
+#[serial]
+async fn test_screenshot_xlsx_native_integration() {
+ let path = "../../bench/xlsx_corpus/nfs/IC-Accounting-Business-General-Ledger-11334.xlsx";
+ let lit = LiteParse::new(LiteParseConfig {
+ quiet: true,
+ ..Default::default()
+ });
+
+ let shots = lit.screenshot(path, None).await.expect("native raster");
+ let parsed = lit.parse(path).await.expect("native parse succeeds");
+ assert_eq!(
+ shots.len(),
+ parsed.pages.len(),
+ "the raster paginates exactly like the parse"
+ );
+ assert!(
+ shots.iter().all(|s| !s.image_bytes.is_empty()),
+ "every page encodes to PNG"
+ );
+ assert!(
+ shots.iter().any(|s| !s.is_solid_fill),
+ "a painted ledger is not a blank page"
+ );
+
+ // Same coordinate space as the parse: the raster is the page box scaled by
+ // dpi/72, modulo the 32 MP clamp a wide sheet can hit.
+ for (shot, page) in shots.iter().zip(&parsed.pages) {
+ let scale = liteparse_ooxml::render::raster::effective_scale(
+ page.page_width,
+ page.page_height,
+ lit.config().dpi / 72.0,
+ );
+ let expect_w = (page.page_width * scale).round() as u32;
+ let expect_h = (page.page_height * scale).round() as u32;
+ assert!(
+ shot.width.abs_diff(expect_w) <= 1 && shot.height.abs_diff(expect_h) <= 1,
+ "page {}: raster {}x{} vs page {}x{} at {scale}x",
+ shot.page_num,
+ shot.width,
+ shot.height,
+ expect_w,
+ expect_h
+ );
+ }
+
+ let picked = lit
+ .screenshot(path, Some(vec![2, 3]))
+ .await
+ .expect("native raster");
+ assert_eq!(
+ picked.iter().map(|s| s.page_num).collect::<Vec<_>>(),
+ vec![2, 3],
+ "a sheet page number is a page number"
+ );
+
+ let err = lit
+ .screenshot(path, Some(vec![999]))
+ .await
+ .expect_err("out-of-range page is the caller's error, not a fallback");
+ assert!(
+ err.to_string().contains("out of range"),
+ "engine reports the range rather than degrading to LibreOffice: {err}"
+ );
+}