Skip to content

A fast, helpful, and open-source document parser

feat(python): wire screenshot through core conversion path

AdemBoukhris4571b82003be4cc
diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rs
index 192d87d..d4f1b4f 100644
--- a/crates/liteparse-python/src/cli.rs
+++ b/crates/liteparse-python/src/cli.rs
@@ -21,7 +21,7 @@ struct Cli {
enum Commands {
/// Parse a document file (PDF, DOCX, XLSX, PPTX, images, etc.)
Parse(ParseCommand),
- /// Generate screenshots of PDF pages
+ /// Generate screenshots of document pages (PDF, DOCX, XLSX, images, etc.)
Screenshot(ScreenshotCommand),
/// Parse multiple documents in batch mode
BatchParse(BatchParseCommand),
@@ -175,23 +175,23 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
std::fs::create_dir_all(&cmd.output_dir)?;
- let lib = pdfium::Library::init();
- let document = lib.load_document(&cmd.file, cmd.password.as_deref())?;
- let page_count = document.page_count();
+ let config = LiteParseConfig {
+ target_pages: cmd.target_pages.clone(),
+ dpi: cmd.dpi,
+ password: cmd.password.clone(),
+ quiet: cmd.quiet,
+ ..Default::default()
+ };
+ let lp = LiteParse::new(config);
+ let results = rt.block_on(lp.screenshot(&cmd.file, target_pages))?;
- for page_index in 0..page_count {
- let page_number = page_index as u32 + 1;
- if let Some(ref targets) = target_pages
- && !targets.contains(&page_number)
- {
- continue;
- }
- let output_path = format!("{}/page_{}.png", cmd.output_dir, page_number);
- render::screenshot(&cmd.file, page_number, cmd.dpi, &output_path)?;
+ for result in results {
+ let output_path = format!("{}/page_{}.png", cmd.output_dir, result.page_num);
+ std::fs::write(&output_path, &result.image_bytes)?;
if !cmd.quiet {
eprintln!(
"[liteparse] screenshot page {} → {}",
- page_number, output_path
+ result.page_num, output_path
);
}
}
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index 62e7d84..5fe8d11 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -192,7 +192,6 @@ struct LiteParse {
inner: liteparse::parser::LiteParse,
config: LiteParseConfig,
runtime: tokio::runtime::Runtime,
- pdfium: pdfium::Library,
}
#[pymethods]
@@ -271,13 +270,11 @@ impl LiteParse {
let inner = liteparse::parser::LiteParse::new(cfg.clone());
let runtime = tokio::runtime::Runtime::new()
.map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;
- let pdfium = pdfium::Library::init();
Ok(Self {
inner,
config: cfg,
runtime,
- pdfium,
})
}
@@ -300,6 +297,9 @@ impl LiteParse {
}
/// Take screenshots of document pages. Returns a list of ScreenshotResult.
+ ///
+ /// Non-PDF files are automatically converted to PDF before rendering when
+ /// LibreOffice/ImageMagick are available.
#[pyo3(signature = (input, page_numbers = None))]
fn screenshot(
&self,
@@ -307,58 +307,21 @@ impl LiteParse {
input: String,
page_numbers: Option<Vec<u32>>,
) -> PyResult<Vec<PyScreenshotResult>> {
- let dpi = self.config.dpi;
- let password = self.config.password.clone();
- py.detach(move || {
- let document = self
- .pdfium
- .load_document(&input, password.as_deref())
+ py.detach(|| {
+ let results = self
+ .runtime
+ .block_on(self.inner.screenshot(&input, page_numbers))
.map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;
- let page_count = document.page_count() as u32;
- let pages: Vec<u32> = match page_numbers {
- Some(nums) => nums,
- None => (1..=page_count).collect(),
- };
-
- let mut results = Vec::with_capacity(pages.len());
- for page_num in pages {
- if page_num < 1 || page_num > page_count {
- return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
- "page {page_num} out of range (document has {page_count} pages)"
- )));
- }
- let page = document.page((page_num - 1) as i32).map_err(|e| {
- PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string())
- })?;
- let bitmap = page.render(dpi).map_err(|e| {
- PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string())
- })?;
-
- let width = bitmap.width() as u32;
- let height = bitmap.height() as u32;
- let rgba = bitmap.to_rgba();
-
- let mut png_buf: Vec<u8> = Vec::new();
- let encoder = image::codecs::png::PngEncoder::new(&mut png_buf);
- use image::ImageEncoder;
- encoder
- .write_image(&rgba, width, height, image::ColorType::Rgba8.into())
- .map_err(|e| {
- PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!(
- "PNG encode failed: {e}"
- ))
- })?;
-
- results.push(PyScreenshotResult {
- page_num,
- width,
- height,
- image_buffer: png_buf,
- });
- }
-
- Ok(results)
+ Ok(results
+ .into_iter()
+ .map(|r| PyScreenshotResult {
+ page_num: r.page_num,
+ width: r.width,
+ height: r.height,
+ image_buffer: r.image_bytes,
+ })
+ .collect())
})
}
diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.py
index 5e46e99..af10bf0 100644
--- a/packages/python/liteparse/parser.py
+++ b/packages/python/liteparse/parser.py
@@ -158,8 +158,12 @@ class LiteParse:
"""
Generate screenshots of document pages.
+ Supports PDFs natively. Non-PDF formats (DOCX, XLSX, images, etc.) are
+ automatically converted to PDF before rendering when the required system
+ tools are installed. Plain-text formats cannot be rendered.
+
Args:
- file_path: Path to the document file.
+ file_path: Path to the document file (PDF, DOCX, images, etc.).
page_numbers: Specific page numbers to screenshot (1-indexed).
If None, screenshots all pages.