Skip to content

A fast, helpful, and open-source document parser

feat(core): add screenshot conversion via resolve_pdf_input

AdemBoukhris457839c31cb1873
diff --git a/crates/liteparse/src/conversion.rs b/crates/liteparse/src/conversion.rs
index 3e4f3c1..c2b9e22 100644
--- a/crates/liteparse/src/conversion.rs
+++ b/crates/liteparse/src/conversion.rs
@@ -20,6 +20,9 @@ const IMAGE_EXTENSIONS: &[&str] = &[
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "tif", "webp", "svg",
];
+/// Plain-text extensions that cannot be rendered as page images.
+const TEXT_ONLY_EXTENSIONS: &[&str] = &["txt", "md", "markdown", "log"];
+
/// Extensions that require Ghostscript for ImageMagick conversion.
const GHOSTSCRIPT_REQUIRED_EXTENSIONS: &[&str] = &["svg", "eps", "ps", "ai"];
@@ -61,6 +64,104 @@ pub fn is_pdf(path: &str) -> bool {
}
/// Check if a file extension is supported (either PDF or convertible).
+/// Returns true when the extension denotes a plain-text format with no page layout.
+pub fn is_text_only_extension(ext: &str) -> bool {
+ TEXT_ONLY_EXTENSIONS.contains(&ext.to_lowercase().as_str())
+}
+
+pub fn screenshot_text_format_error(ext: &str) -> LiteParseError {
+ LiteParseError::Conversion(format!(
+ "Cannot screenshot text-based format (.{ext}). Convert to PDF first."
+ ))
+}
+
+/// Keeps converted PDF temp directories alive until rendering or parsing completes.
+#[derive(Debug)]
+pub struct PdfInputGuard {
+ /// Conversion output directory; kept alive until this guard is dropped.
+ #[allow(dead_code)]
+ conv_tmp: Option<TempDir>,
+ /// Set when non-PDF bytes were staged and converted; requires explicit staging cleanup.
+ pub bytes_converted: bool,
+}
+
+impl PdfInputGuard {
+ pub fn cleanup_bytes_staging(&self, input: &crate::types::PdfInput) {
+ if self.bytes_converted {
+ if let crate::types::PdfInput::Path(p) = input
+ && let Some(parent) = Path::new(p).parent()
+ {
+ let _ = std::fs::remove_dir_all(parent);
+ }
+ }
+ }
+}
+
+/// Resolve a document input to a PDF suitable for rendering or text extraction.
+///
+/// When `reject_text_formats` is true, plain-text files (`.txt`, etc.) return a
+/// clear error instead of attempting conversion.
+pub async fn resolve_pdf_input(
+ input: crate::types::PdfInput,
+ password: Option<&str>,
+ reject_text_formats: bool,
+) -> Result<(crate::types::PdfInput, PdfInputGuard), LiteParseError> {
+ use crate::types::PdfInput;
+
+ match input {
+ PdfInput::Path(p) => {
+ let ext = Path::new(&p)
+ .extension()
+ .and_then(|e| e.to_str())
+ .unwrap_or("");
+ if reject_text_formats && is_text_only_extension(ext) {
+ return Err(screenshot_text_format_error(ext));
+ }
+ if is_pdf(&p) {
+ Ok((
+ PdfInput::Path(p),
+ PdfInputGuard {
+ conv_tmp: None,
+ bytes_converted: false,
+ },
+ ))
+ } else {
+ let (converted, tmp_dir) = convert_to_pdf(&p, password, false).await?;
+ Ok((
+ PdfInput::Path(converted.pdf_path),
+ PdfInputGuard {
+ conv_tmp: tmp_dir,
+ bytes_converted: false,
+ },
+ ))
+ }
+ }
+ PdfInput::Bytes(b) => {
+ let ext = guess_extension_from_data(&b);
+ if ext.as_deref() == Some("pdf") {
+ return Ok((
+ PdfInput::Bytes(b),
+ PdfInputGuard {
+ conv_tmp: None,
+ bytes_converted: false,
+ },
+ ));
+ }
+ if reject_text_formats && ext.as_ref().is_some_and(|e| is_text_only_extension(e)) {
+ return Err(screenshot_text_format_error(ext.as_ref().unwrap()));
+ }
+ let (converted, tmp_dir) = convert_data_to_pdf(b, password).await?;
+ Ok((
+ PdfInput::Path(converted.pdf_path),
+ PdfInputGuard {
+ conv_tmp: tmp_dir,
+ bytes_converted: true,
+ },
+ ))
+ }
+ }
+}
+
pub fn is_supported_extension(path: &str) -> bool {
let ext = match Path::new(path).extension().and_then(|e| e.to_str()) {
Some(e) => e.to_lowercase(),
@@ -594,6 +695,38 @@ mod tests {
assert!(!is_path_executable("/no/such/path/zzz").await);
}
+ #[test]
+ fn test_is_text_only_extension() {
+ assert!(is_text_only_extension("txt"));
+ assert!(is_text_only_extension("TXT"));
+ assert!(is_text_only_extension("md"));
+ assert!(!is_text_only_extension("pdf"));
+ assert!(!is_text_only_extension("docx"));
+ }
+
+ #[tokio::test]
+ async fn test_resolve_pdf_input_rejects_text_for_screenshot() {
+ use crate::types::PdfInput;
+
+ let err = resolve_pdf_input(PdfInput::Path("/tmp/readme.txt".into()), None, true)
+ .await
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("Cannot screenshot text-based format"));
+ }
+
+ #[tokio::test]
+ async fn test_resolve_pdf_input_pdf_bytes_zero_disk() {
+ use crate::types::PdfInput;
+
+ let pdf_bytes = b"%PDF-1.4\n";
+ let (input, guard) = resolve_pdf_input(PdfInput::Bytes(pdf_bytes.to_vec()), None, true)
+ .await
+ .unwrap();
+ assert!(matches!(input, PdfInput::Bytes(_)));
+ assert!(!guard.bytes_converted);
+ }
+
#[tokio::test]
async fn test_convert_to_pdf_passthrough_pdf() {
let (res, _) = convert_to_pdf("/some/file.pdf", None, false).await.unwrap();
diff --git a/crates/liteparse/src/lib.rs b/crates/liteparse/src/lib.rs
index 5594830..f96e47c 100644
--- a/crates/liteparse/src/lib.rs
+++ b/crates/liteparse/src/lib.rs
@@ -7,7 +7,7 @@
// ── Public API re-exports ──────────────────────────────────────────────
pub use config::{LiteParseConfig, OutputFormat};
pub use error::LiteParseError;
-pub use parser::{LiteParse, ParseResult};
+pub use parser::{LiteParse, ParseResult, ScreenshotResult};
pub use search::{SearchOptions, search_items};
pub use types::{ParsedPage, TextItem};
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index be046e8..73bc114 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -1,10 +1,6 @@
-use std::path::Path;
-
use crate::config::{LiteParseConfig, parse_target_pages};
#[cfg(not(target_arch = "wasm32"))]
use crate::conversion;
-#[cfg(not(target_arch = "wasm32"))]
-use crate::conversion::convert_data_to_pdf;
use crate::error::LiteParseError;
use crate::extract;
use crate::ocr::OcrEngine;
@@ -14,6 +10,8 @@ use crate::ocr::http_simple::HttpOcrEngine;
use crate::ocr::tesseract::TesseractOcrEngine;
use crate::ocr_merge;
use crate::projection;
+#[cfg(not(target_arch = "wasm32"))]
+use crate::render;
use crate::types::{ParsedPage, PdfInput};
/// Result of parsing a document.
@@ -24,6 +22,15 @@ pub struct ParseResult {
pub text: String,
}
+/// Result of rendering a single page screenshot.
+#[derive(Debug, Clone)]
+pub struct ScreenshotResult {
+ pub page_num: u32,
+ pub width: u32,
+ pub height: u32,
+ pub image_bytes: Vec<u8>,
+}
+
/// Main LiteParse orchestrator.
pub struct LiteParse {
config: LiteParseConfig,
@@ -74,42 +81,12 @@ impl LiteParse {
let t0 = web_time::Instant::now();
- let mut is_converted = false;
#[cfg(not(target_arch = "wasm32"))]
- let _tmp_dir: Option<tempfile::TempDir>;
- #[cfg(not(target_arch = "wasm32"))]
- let _conv_tmp_dir: Option<tempfile::TempDir>;
+ let (validated_input, guard) =
+ conversion::resolve_pdf_input(input, self.config.password.as_deref(), false).await?;
- let validated_input = {
- #[cfg(target_arch = "wasm32")]
- {
- input
- }
-
- #[cfg(not(target_arch = "wasm32"))]
- match input {
- PdfInput::Path(p) => {
- if conversion::is_pdf(&p) {
- PdfInput::Path(p)
- } else {
- let (converted, tmp_dir) =
- conversion::convert_to_pdf(&p, self.config.password.as_deref(), false)
- .await?;
- _conv_tmp_dir = tmp_dir;
- // The on-disk source isn't ours to delete; only the
- // converted temp file should be cleaned up by `tmp_dir`.
- PdfInput::Path(converted.pdf_path)
- }
- }
- PdfInput::Bytes(b) => {
- let (converted, tmp_dir) =
- convert_data_to_pdf(b, self.config.password.as_deref()).await?;
- _tmp_dir = tmp_dir;
- is_converted = true;
- PdfInput::Path(converted.pdf_path)
- }
- }
- };
+ #[cfg(target_arch = "wasm32")]
+ let validated_input = input;
// Determine which pages to extract
let target_pages = self
@@ -199,13 +176,10 @@ impl LiteParse {
log(&format!("[liteparse] total: {:.1}ms", total));
// Office docs and images that are temporarily created from bytes
- // are removed, but not PDFs, as they pass through the coversion logic
+ // are removed, but not PDFs, as they pass through the conversion logic
// and are used directly as input.
- // With this block, we insure that temporary PDFs created from bytes and/or
- // converted from Office/image files are cleaned up as well.
- if is_converted && let PdfInput::Path(p) = validated_input {
- std::fs::remove_dir_all(Path::new(&p).parent().unwrap())?;
- }
+ #[cfg(not(target_arch = "wasm32"))]
+ guard.cleanup_bytes_staging(&validated_input);
Ok(ParseResult {
pages: parsed_pages,
@@ -213,6 +187,63 @@ impl LiteParse {
})
}
+ /// Generate screenshots of document pages as PNG bytes.
+ ///
+ /// Non-PDF files are automatically converted to PDF first (requires
+ /// LibreOffice/ImageMagick on the system). Plain-text formats cannot be
+ /// rendered and return a clear error.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub async fn screenshot(
+ &self,
+ input: &str,
+ page_numbers: Option<Vec<u32>>,
+ ) -> Result<Vec<ScreenshotResult>, LiteParseError> {
+ self.screenshot_input(PdfInput::Path(input.to_string()), page_numbers)
+ .await
+ }
+
+ /// Generate screenshots from a file path or raw bytes.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub async fn screenshot_input(
+ &self,
+ input: PdfInput,
+ page_numbers: Option<Vec<u32>>,
+ ) -> Result<Vec<ScreenshotResult>, LiteParseError> {
+ let log = |msg: &str| {
+ if !self.config.quiet {
+ eprintln!("{}", msg);
+ }
+ };
+
+ let (validated_input, guard) =
+ conversion::resolve_pdf_input(input, self.config.password.as_deref(), true).await?;
+
+ if let PdfInput::Path(ref path) = validated_input
+ && !conversion::is_pdf(path)
+ {
+ log("[liteparse] converted input to PDF for screenshot rendering");
+ }
+
+ let rendered = render::render_pages_to_png(
+ &validated_input,
+ page_numbers.as_deref(),
+ self.config.dpi,
+ self.config.password.as_deref(),
+ )?;
+
+ guard.cleanup_bytes_staging(&validated_input);
+
+ Ok(rendered
+ .into_iter()
+ .map(|page| ScreenshotResult {
+ page_num: page.page_num,
+ width: page.width,
+ height: page.height,
+ image_bytes: page.png_bytes,
+ })
+ .collect())
+ }
+
pub fn config(&self) -> &LiteParseConfig {
&self.config
}
diff --git a/crates/liteparse/src/render.rs b/crates/liteparse/src/render.rs
index 364d81e..8e3eb80 100644
--- a/crates/liteparse/src/render.rs
+++ b/crates/liteparse/src/render.rs
@@ -1,52 +1,122 @@
use crate::error::LiteParseError;
-use image::{ImageBuffer, Rgba};
+use crate::types::PdfInput;
+use image::ImageEncoder;
use pdfium::Library;
use serde::Serialize;
+/// A single rendered page as PNG bytes.
+#[derive(Debug, Clone)]
+pub struct RenderedPage {
+ pub page_num: u32,
+ pub width: u32,
+ pub height: u32,
+ pub png_bytes: Vec<u8>,
+}
+
+/// Render selected pages from a PDF input to PNG bytes.
+pub fn render_pages_to_png(
+ input: &PdfInput,
+ page_numbers: Option<&[u32]>,
+ dpi: f32,
+ password: Option<&str>,
+) -> Result<Vec<RenderedPage>, LiteParseError> {
+ let lib = Library::init();
+ match input {
+ PdfInput::Path(path) => {
+ let document = lib.load_document(path, password)?;
+ render_document_pages(&document, page_numbers, dpi)
+ }
+ PdfInput::Bytes(data) => {
+ let document = lib.load_document_from_bytes(data, password)?;
+ render_document_pages(&document, page_numbers, dpi)
+ }
+ }
+}
+
+fn render_document_pages(
+ document: &pdfium::Document,
+ page_numbers: Option<&[u32]>,
+ dpi: f32,
+) -> Result<Vec<RenderedPage>, LiteParseError> {
+ let page_count = document.page_count() as u32;
+ let pages: Vec<u32> = match page_numbers {
+ Some(nums) => nums.to_vec(),
+ 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(LiteParseError::Other(format!(
+ "page {page_num} out of range (document has {page_count} pages)"
+ )));
+ }
+
+ let page = document.page((page_num - 1) as i32)?;
+ let bitmap = page.render(dpi)?;
+ let width = bitmap.width() as u32;
+ let height = bitmap.height() as u32;
+ let rgba = bitmap.to_rgba();
+ let png_bytes = encode_png(&rgba, width, height)?;
+
+ results.push(RenderedPage {
+ page_num,
+ width,
+ height,
+ png_bytes,
+ });
+ }
+
+ Ok(results)
+}
+
+fn encode_png(rgba: &[u8], width: u32, height: u32) -> Result<Vec<u8>, LiteParseError> {
+ let mut png_buf = Vec::new();
+ let encoder = image::codecs::png::PngEncoder::new(&mut png_buf);
+ encoder.write_image(rgba, width, height, image::ColorType::Rgba8.into())?;
+ Ok(png_buf)
+}
+
/// Render a single page to a PNG file.
pub fn screenshot(
pdf_path: &str,
page_num: u32,
dpi: f32,
output_path: &str,
+ password: Option<&str>,
) -> Result<(), LiteParseError> {
- let lib = Library::init();
- let document = lib.load_document(pdf_path, None)?;
- let page = document.page((page_num - 1) as i32)?;
- let bitmap = page.render(dpi)?;
-
- let width = bitmap.width() as u32;
- let height = bitmap.height() as u32;
- let rgba = bitmap.to_rgba();
+ let input = PdfInput::Path(pdf_path.to_string());
+ let pages = render_pages_to_png(&input, Some(&[page_num]), dpi, password)?;
+ let page = pages
+ .into_iter()
+ .next()
+ .ok_or_else(|| LiteParseError::Other("no page rendered".into()))?;
- let img: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_raw(width, height, rgba).ok_or(
- LiteParseError::Other("failed to create image buffer".into()),
- )?;
+ std::fs::write(output_path, &page.png_bytes)?;
- img.save(output_path)?;
eprintln!(
- "[rust-bin] rendered page {} at {dpi} DPI → {output_path} ({width}×{height})",
- page_num
+ "[rust-bin] rendered page {} at {dpi} DPI → {output_path} ({}×{})",
+ page_num, page.width, page.height
);
Ok(())
}
/// Render a single page and write raw PNG bytes to stdout.
-pub fn screenshot_to_stdout(pdf_path: &str, page_num: u32, dpi: f32) -> Result<(), LiteParseError> {
- let lib = Library::init();
- let document = lib.load_document(pdf_path, None)?;
- let page = document.page((page_num - 1) as i32)?;
- let bitmap = page.render(dpi)?;
-
- let width = bitmap.width() as u32;
- let height = bitmap.height() as u32;
- let rgba = bitmap.to_rgba();
-
- let encoder = image::codecs::png::PngEncoder::new(std::io::stdout().lock());
- use image::ImageEncoder;
- encoder.write_image(&rgba, width, height, image::ColorType::Rgba8.into())?;
-
+pub fn screenshot_to_stdout(
+ pdf_path: &str,
+ page_num: u32,
+ dpi: f32,
+ 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)?;
+ let page = pages
+ .into_iter()
+ .next()
+ .ok_or_else(|| LiteParseError::Other("no page rendered".into()))?;
+
+ std::io::Write::write_all(&mut std::io::stdout().lock(), &page.png_bytes)?;
Ok(())
}
@@ -118,6 +188,7 @@ mod tests {
1,
72.0,
"/tmp/out.png",
+ None,
);
assert!(r.is_err());
}