Skip to content

A fast, helpful, and open-source document parser

package lib differently

Logan Markewich48f4bd06222d
diff --git a/Cargo.lock b/Cargo.lock
index 4ffd186..924788c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1205,13 +1205,14 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
[[package]]
name = "liteparse"
-version = "2.0.1"
+version = "2.0.2"
dependencies = [
"clap",
"image",
"infer",
"liteparse-pdfium",
"liteparse-pdfium-sys",
+ "ordered-float",
"reqwest 0.13.3",
"serde",
"serde_json",
@@ -1241,17 +1242,18 @@ dependencies = [
[[package]]
name = "liteparse-pdfium"
-version = "1.0.0"
+version = "1.0.1"
dependencies = [
"liteparse-pdfium-sys",
]
[[package]]
name = "liteparse-pdfium-sys"
-version = "1.0.0"
+version = "1.1.0"
dependencies = [
"bindgen",
"flate2",
+ "libloading",
"tar",
"ureq",
]
@@ -1544,6 +1546,15 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "ordered-float"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7d950ca161dc355eaf28f82b11345ed76c6e1f6eb1f4f4479e0323b9e2fbd0e"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "parking_lot"
version = "0.12.5"
diff --git a/crates/liteparse-napi/Cargo.toml b/crates/liteparse-napi/Cargo.toml
index 63654bb..d692e79 100644
--- a/crates/liteparse-napi/Cargo.toml
+++ b/crates/liteparse-napi/Cargo.toml
@@ -14,7 +14,7 @@ default = ["tesseract"]
tesseract = ["liteparse/tesseract"]
[dependencies]
-liteparse = { package = "liteparse", version = "2.0.1", path = "../liteparse", default-features = false }
+liteparse = { package = "liteparse", version = "2.0.2", path = "../liteparse", default-features = false }
pdfium-sys = { package = "liteparse-pdfium-sys", version = "1.0.0", path = "../pdfium-sys" }
napi = { version = "2", features = ["async", "serde-json", "napi9"] }
napi-derive = "2"
diff --git a/crates/liteparse-python/Cargo.toml b/crates/liteparse-python/Cargo.toml
index ddd2501..6b560ba 100644
--- a/crates/liteparse-python/Cargo.toml
+++ b/crates/liteparse-python/Cargo.toml
@@ -15,7 +15,7 @@ default = ["tesseract"]
tesseract = ["liteparse/tesseract"]
[dependencies]
-liteparse = { package = "liteparse", version = "2.0.1", path = "../liteparse", default-features = false }
+liteparse = { package = "liteparse", version = "2.0.2", path = "../liteparse", default-features = false }
pdfium-sys = { package = "liteparse-pdfium-sys", version = "1.0.0", path = "../pdfium-sys" }
pdfium = { package = "liteparse-pdfium", version = "1.0.0", path = "../pdfium" }
clap = { version = "4.5.55", features = ["derive"] }
diff --git a/crates/liteparse/Cargo.toml b/crates/liteparse/Cargo.toml
index 08805f8..03377dd 100644
--- a/crates/liteparse/Cargo.toml
+++ b/crates/liteparse/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "liteparse"
-version = "2.0.1"
+version = "2.0.2"
edition.workspace = true
license.workspace = true
repository.workspace = true
@@ -22,8 +22,9 @@ tesseract = ["dep:tesseract-rs"]
clap = { version = "4.5.55", features = ["derive"] }
image = { version = "0.25", default-features = false, features = ["png"] }
infer = "0.19.0"
-pdfium = { package = "liteparse-pdfium", version = "1.0.0", path = "../pdfium" }
-pdfium-sys = { package = "liteparse-pdfium-sys", version = "1.0.0", path = "../pdfium-sys" }
+ordered-float = "5.3.0"
+pdfium = { package = "liteparse-pdfium", version = "1.0.1", path = "../pdfium" }
+pdfium-sys = { package = "liteparse-pdfium-sys", version = "1.1.0", path = "../pdfium-sys" }
reqwest = { version = "0.13.3", default-features = false, features = ["json", "form", "multipart", "rustls"] }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
diff --git a/crates/liteparse/src/output/mod.rs b/crates/liteparse/src/output/mod.rs
index 1c593c8..c455f4f 100644
--- a/crates/liteparse/src/output/mod.rs
+++ b/crates/liteparse/src/output/mod.rs
@@ -1,2 +1,3 @@
pub mod json;
pub mod text;
+pub mod markdown;
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index c295492..e0d7971 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -1509,7 +1509,7 @@ fn project_to_grid(
page: &Page,
mut projection_boxes: Vec<ProjectedTextItem>,
) -> (Vec<ProjectedTextItem>, String) {
- // Step 1a: Filter out items that are purely dots
+ // Filter out items that are purely dots
let mut dot_count = 0usize;
projection_boxes.iter().for_each(|item| {
if item
@@ -1532,19 +1532,19 @@ fn project_to_grid(
});
}
- // Step 1b: Round dimensions
+ // Round dimensions
for item in projection_boxes.iter_mut() {
item.item.width = item.item.width.round();
item.item.height = item.item.height.round();
}
- // Step 1c: Compute median distances
+ // Compute median distances
let (median_width, median_height) = compute_median_textbox_size(&projection_boxes);
- // Step 1d: Handle reading order rotations
+ // Handle reading order rotations
handle_rotation_reading_order(&mut projection_boxes, page.page_height);
- // Step 1e: Form lines of boxes
+ // Form lines of boxes
let mut lines = form_lines(
&mut projection_boxes,
median_width,
@@ -1555,7 +1555,7 @@ fn project_to_grid(
return (Vec::new(), String::new());
}
- // Step 2: Segment into blocks
+ // Segment into blocks
let blocks = segment_blocks(&lines);
let debug = std::env::var("LITEPARSE_DEBUG").is_ok();
@@ -1573,7 +1573,7 @@ fn project_to_grid(
.collect();
let mut raw_lines = vec![String::new(); lines.len()];
-
+
// Page-scoped forward anchors (carry alignment across blocks)
let mut forward_left: BTreeMap<i32, usize> = BTreeMap::new();
let mut forward_right: BTreeMap<i32, usize> = BTreeMap::new();
diff --git a/crates/pdfium-sys/Cargo.toml b/crates/pdfium-sys/Cargo.toml
index b2d4f9d..3e082da 100644
--- a/crates/pdfium-sys/Cargo.toml
+++ b/crates/pdfium-sys/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "liteparse-pdfium-sys"
-version = "1.0.0"
+version = "1.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
@@ -11,6 +11,9 @@ links = "pdfium"
default = []
bindgen = ["dep:bindgen"]
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+libloading = "0.8"
+
[build-dependencies]
bindgen = { version = "0.71", optional = true }
flate2 = "1"
diff --git a/crates/pdfium-sys/build.rs b/crates/pdfium-sys/build.rs
index e7349f1..40d1b77 100644
--- a/crates/pdfium-sys/build.rs
+++ b/crates/pdfium-sys/build.rs
@@ -22,7 +22,7 @@ fn main() {
)
});
- let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
+ let _target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
println!("cargo:rustc-link-search=native={}", lib_dir.display());
@@ -44,28 +44,11 @@ fn main() {
println!("cargo:rustc-link-lib=static=wasi-emulated-signal");
println!("cargo:lib_path={}", lib_dir.display());
} else {
- // On Windows MSVC the import library is named `pdfium.dll.lib`, so
- // we must pass `pdfium.dll` as the lib name (the linker appends `.lib`).
- if target_os == "windows" {
- println!("cargo:rustc-link-lib=dylib=pdfium.dll");
- } else {
- println!("cargo:rustc-link-lib=dylib=pdfium");
- }
+ // Non-wasm: pdfium is loaded at runtime via libloading (no link-time
+ // dynamic dependency). We bake the lib directory path into the binary
+ // so the runtime loader knows where to find the shared library.
println!("cargo:lib_path={}", lib_dir.display());
-
- // Copy the dylib into OUT_DIR so it's on the rpath that cargo sets
- // for crates with `links = ...`. This is needed on macOS where the
- // dylib's install name is @rpath/libpdfium.dylib.
- // On Windows the DLL lives in bin/, not lib/.
- let dll_dir = if target_os == "windows" {
- lib_dir
- .parent()
- .map(|p| p.join("bin"))
- .unwrap_or(lib_dir.clone())
- } else {
- lib_dir.clone()
- };
- copy_dylib_to_target_deps(&dll_dir);
+ println!("cargo:rustc-env=PDFIUM_LIB_DIR={}", lib_dir.display());
}
run_bindgen(&include_dir);
@@ -214,41 +197,6 @@ fn fix_dylib_install_name(dir: &Path) {
}
}
-/// Copy the pdfium shared library into `target/<profile>/deps/` so the
-/// runtime dynamic linker can find it. Cargo includes this directory in
-/// the rpath of test and binary artifacts.
-fn copy_dylib_to_target_deps(lib_dir: &Path) {
- let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
-
- let dylib_name = match target_os.as_str() {
- "macos" => "libpdfium.dylib",
- "windows" => "pdfium.dll",
- _ => "libpdfium.so",
- };
-
- let src = lib_dir.join(dylib_name);
- if !src.exists() {
- return;
- }
-
- // OUT_DIR is typically target/<profile>/build/<pkg>-<hash>/out
- // We want target/<profile>/deps which is 3 levels up then into deps
- let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
- if let Some(build_dir) = out_dir
- .parent()
- .and_then(|p| p.parent())
- .and_then(|p| p.parent())
- {
- let deps_dir = build_dir.join("deps");
- if deps_dir.is_dir() {
- let dst = deps_dir.join(dylib_name);
- fs::copy(&src, &dst).unwrap_or_else(|e| {
- panic!("failed to copy {} to {}: {e}", src.display(), dst.display())
- });
- }
- }
-}
-
fn run_bindgen(include_dir: &Path) {
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
let out_file = out_path.join("bindings.rs");
diff --git a/crates/pdfium-sys/src/lib.rs b/crates/pdfium-sys/src/lib.rs
index cd503e4..918eaee 100644
--- a/crates/pdfium-sys/src/lib.rs
+++ b/crates/pdfium-sys/src/lib.rs
@@ -4,3 +4,6 @@
#![allow(dead_code)]
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
+
+#[cfg(not(target_arch = "wasm32"))]
+pub mod dynamic;
diff --git a/crates/pdfium/Cargo.toml b/crates/pdfium/Cargo.toml
index 61270bd..74a715f 100644
--- a/crates/pdfium/Cargo.toml
+++ b/crates/pdfium/Cargo.toml
@@ -1,10 +1,10 @@
[package]
name = "liteparse-pdfium"
-version = "1.0.0"
+version = "1.0.1"
edition.workspace = true
license.workspace = true
repository.workspace = true
description = "Safe Rust wrapper around PDFium for liteparse"
[dependencies]
-pdfium-sys = { package = "liteparse-pdfium-sys", version = "1.0.0", path = "../pdfium-sys" }
+pdfium-sys = { package = "liteparse-pdfium-sys", version = "1.1.0", path = "../pdfium-sys" }
diff --git a/crates/pdfium/src/bitmap.rs b/crates/pdfium/src/bitmap.rs
index 2039197..fc48ef5 100644
--- a/crates/pdfium/src/bitmap.rs
+++ b/crates/pdfium/src/bitmap.rs
@@ -1,4 +1,5 @@
use crate::error::PdfiumError;
+use crate::ffi;
pub struct Bitmap {
handle: pdfium_sys::FPDF_BITMAP,
@@ -16,13 +17,13 @@ impl Bitmap {
/// Create a new BGRA bitmap with the given dimensions.
pub fn new(width: i32, height: i32) -> Result<Self, PdfiumError> {
let handle = unsafe {
- pdfium_sys::FPDFBitmap_CreateEx(
+ ffi!(FPDFBitmap_CreateEx(
width,
height,
pdfium_sys::FPDFBitmap_BGRA as i32,
std::ptr::null_mut(),
0, // stride=0 lets pdfium choose
- )
+ ))
};
if handle.is_null() {
return Err(PdfiumError::OperationFailed);
@@ -35,21 +36,21 @@ impl Bitmap {
}
pub fn width(&self) -> i32 {
- unsafe { pdfium_sys::FPDFBitmap_GetWidth(self.handle) }
+ unsafe { ffi!(FPDFBitmap_GetWidth(self.handle)) }
}
pub fn height(&self) -> i32 {
- unsafe { pdfium_sys::FPDFBitmap_GetHeight(self.handle) }
+ unsafe { ffi!(FPDFBitmap_GetHeight(self.handle)) }
}
pub fn stride(&self) -> i32 {
- unsafe { pdfium_sys::FPDFBitmap_GetStride(self.handle) }
+ unsafe { ffi!(FPDFBitmap_GetStride(self.handle)) }
}
/// Fill a rectangle with an ARGB color (0xAARRGGBB).
pub fn fill_rect(&self, left: i32, top: i32, width: i32, height: i32, color: u64) {
unsafe {
- pdfium_sys::FPDFBitmap_FillRect(
+ ffi!(FPDFBitmap_FillRect(
self.handle,
left,
top,
@@ -58,14 +59,14 @@ impl Bitmap {
// necessary for windows -> expected `u32`, found `u64`
#[allow(clippy::useless_conversion)]
color.try_into().unwrap(),
- );
+ ));
}
}
/// Get the raw pixel buffer as a byte slice.
/// Format is BGRA, row-major, with `stride()` bytes per row.
pub fn buffer(&self) -> &[u8] {
- let ptr = unsafe { pdfium_sys::FPDFBitmap_GetBuffer(self.handle) };
+ let ptr = unsafe { ffi!(FPDFBitmap_GetBuffer(self.handle)) };
let len = (self.stride() * self.height()) as usize;
unsafe { std::slice::from_raw_parts(ptr as *const u8, len) }
}
@@ -95,6 +96,6 @@ impl Bitmap {
impl Drop for Bitmap {
fn drop(&mut self) {
- unsafe { pdfium_sys::FPDFBitmap_Destroy(self.handle) };
+ unsafe { ffi!(FPDFBitmap_Destroy(self.handle)) };
}
}
diff --git a/crates/pdfium/src/document.rs b/crates/pdfium/src/document.rs
index b7ed348..221809f 100644
--- a/crates/pdfium/src/document.rs
+++ b/crates/pdfium/src/document.rs
@@ -1,4 +1,5 @@
use crate::error::PdfiumError;
+use crate::ffi;
use crate::page::Page;
pub struct Document {
@@ -7,11 +8,11 @@ pub struct Document {
impl Document {
pub fn page_count(&self) -> i32 {
- unsafe { pdfium_sys::FPDF_GetPageCount(self.handle) }
+ unsafe { ffi!(FPDF_GetPageCount(self.handle)) }
}
pub fn page(&self, index: i32) -> Result<Page<'_>, PdfiumError> {
- let handle = unsafe { pdfium_sys::FPDF_LoadPage(self.handle, index) };
+ let handle = unsafe { ffi!(FPDF_LoadPage(self.handle, index)) };
if handle.is_null() {
return Err(PdfiumError::PageNotFound);
}
@@ -25,6 +26,6 @@ impl Document {
impl Drop for Document {
fn drop(&mut self) {
- unsafe { pdfium_sys::FPDF_CloseDocument(self.handle) };
+ unsafe { ffi!(FPDF_CloseDocument(self.handle)) };
}
}
diff --git a/crates/pdfium/src/error.rs b/crates/pdfium/src/error.rs
index bf2fd1f..e8082cf 100644
--- a/crates/pdfium/src/error.rs
+++ b/crates/pdfium/src/error.rs
@@ -1,5 +1,7 @@
use std::fmt;
+use crate::ffi;
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PdfiumError {
Unknown,
@@ -13,7 +15,7 @@ pub enum PdfiumError {
impl PdfiumError {
pub(crate) fn from_last_error() -> Self {
- let code = unsafe { pdfium_sys::FPDF_GetLastError() };
+ let code = unsafe { ffi!(FPDF_GetLastError()) };
match code as u32 {
pdfium_sys::FPDF_ERR_FILE => PdfiumError::FileNotFound,
pdfium_sys::FPDF_ERR_FORMAT => PdfiumError::InvalidFormat,
diff --git a/crates/pdfium/src/font.rs b/crates/pdfium/src/font.rs
index 3056c18..a32d089 100644
--- a/crates/pdfium/src/font.rs
+++ b/crates/pdfium/src/font.rs
@@ -1,3 +1,5 @@
+use crate::ffi;
+
/// Wrapper around FPDF_FONT obtained from a text object.
/// This is a borrowed handle — it does not own the font and must not outlive
/// the page object it was obtained from.
@@ -24,7 +26,7 @@ impl Font {
/// # Safety
/// `obj` must be a valid `FPDF_PAGEOBJECT` handle obtained from PDFium.
pub unsafe fn from_text_object(obj: pdfium_sys::FPDF_PAGEOBJECT) -> Option<Self> {
- let handle = unsafe { pdfium_sys::FPDFTextObj_GetFont(obj) };
+ let handle = unsafe { ffi!(FPDFTextObj_GetFont(obj)) };
if handle.is_null() {
None
} else {
@@ -39,17 +41,17 @@ impl Font {
/// Get the base font name (PostScript name, subset prefix stripped by PDFium).
pub fn base_name(&self) -> Option<String> {
let len =
- unsafe { pdfium_sys::FPDFFont_GetBaseFontName(self.handle, std::ptr::null_mut(), 0) };
+ unsafe { ffi!(FPDFFont_GetBaseFontName(self.handle, std::ptr::null_mut(), 0)) };
if len == 0 {
return None;
}
let mut buf: Vec<u8> = vec![0; len];
let written = unsafe {
- pdfium_sys::FPDFFont_GetBaseFontName(
+ ffi!(FPDFFont_GetBaseFontName(
self.handle,
buf.as_mut_ptr() as *mut std::ffi::c_char,
len,
- )
+ ))
};
if written == 0 {
return None;
@@ -65,7 +67,7 @@ impl Font {
/// Get font type.
pub fn font_type(&self) -> FontType {
- let t = unsafe { pdfium_sys::FPDFFont_GetType(self.handle) };
+ let t = unsafe { ffi!(FPDFFont_GetType(self.handle)) };
match t {
pdfium_sys::FPDF_FONT_TYPE_FPDF_FONTTYPE_TYPE1 => FontType::Type1,
pdfium_sys::FPDF_FONT_TYPE_FPDF_FONTTYPE_TRUETYPE => FontType::TrueType,
@@ -79,20 +81,20 @@ impl Font {
/// Whether the font is embedded in the PDF.
pub fn is_embedded(&self) -> bool {
- unsafe { pdfium_sys::FPDFFont_GetIsEmbedded(self.handle) != 0 }
+ unsafe { ffi!(FPDFFont_GetIsEmbedded(self.handle)) != 0 }
}
/// Get font ascent for a given em size.
pub fn ascent(&self, font_size: f32) -> Option<f32> {
let mut val: f32 = 0.0;
- let ok = unsafe { pdfium_sys::FPDFFont_GetAscent(self.handle, font_size, &mut val) };
+ let ok = unsafe { ffi!(FPDFFont_GetAscent(self.handle, font_size, &mut val)) };
if ok != 0 { Some(val) } else { None }
}
/// Get font descent for a given em size (typically negative).
pub fn descent(&self, font_size: f32) -> Option<f32> {
let mut val: f32 = 0.0;
- let ok = unsafe { pdfium_sys::FPDFFont_GetDescent(self.handle, font_size, &mut val) };
+ let ok = unsafe { ffi!(FPDFFont_GetDescent(self.handle, font_size, &mut val)) };
if ok != 0 { Some(val) } else { None }
}
@@ -100,12 +102,12 @@ impl Font {
pub fn glyph_width_from_char_code(&self, char_code: u32, font_size: f32) -> Option<f32> {
let mut width: f32 = 0.0;
let ok = unsafe {
- pdfium_sys::FPDFFont_GetGlyphWidthFromCharCode(
+ ffi!(FPDFFont_GetGlyphWidthFromCharCode(
self.handle,
char_code,
font_size,
&mut width,
- )
+ ))
};
if ok != 0 { Some(width) } else { None }
}
@@ -114,7 +116,7 @@ impl Font {
pub fn glyph_width(&self, unicode: u32, font_size: f32) -> Option<f32> {
let mut width: f32 = 0.0;
let ok = unsafe {
- pdfium_sys::FPDFFont_GetGlyphWidth(self.handle, unicode, font_size, &mut width)
+ ffi!(FPDFFont_GetGlyphWidth(self.handle, unicode, font_size, &mut width))
};
if ok != 0 { Some(width) } else { None }
}
diff --git a/crates/pdfium/src/lib.rs b/crates/pdfium/src/lib.rs
index 6410856..f0219ce 100644
--- a/crates/pdfium/src/lib.rs
+++ b/crates/pdfium/src/lib.rs
@@ -15,3 +15,21 @@ pub use library::Library;
pub use page::{ImageBounds, Page, ViewportTransform};
pub use text_page::{TextChar, TextCharIter, TextPage};
pub use types::*;
+
+/// Unified FFI call macro. On wasm, calls pdfium_sys extern functions directly.
+/// On non-wasm, calls through the runtime-loaded function pointers.
+#[cfg(not(target_arch = "wasm32"))]
+macro_rules! ffi {
+ ($fn_name:ident($($args:expr),* $(,)?)) => {
+ (pdfium_sys::dynamic::pdfium().$fn_name)($($args),*)
+ }
+}
+
+#[cfg(target_arch = "wasm32")]
+macro_rules! ffi {
+ ($fn_name:ident($($args:expr),* $(,)?)) => {
+ pdfium_sys::$fn_name($($args),*)
+ }
+}
+
+pub(crate) use ffi;
diff --git a/crates/pdfium/src/library.rs b/crates/pdfium/src/library.rs
index 8788869..d5e2754 100644
--- a/crates/pdfium/src/library.rs
+++ b/crates/pdfium/src/library.rs
@@ -3,6 +3,7 @@ use std::sync::Once;
use crate::document::Document;
use crate::error::PdfiumError;
+use crate::ffi;
static INIT: Once = Once::new();
@@ -12,8 +13,12 @@ pub struct Library {
impl Library {
pub fn init() -> Library {
+ #[cfg(not(target_arch = "wasm32"))]
+ pdfium_sys::dynamic::load_default()
+ .expect("failed to load pdfium shared library");
+
INIT.call_once(|| {
- unsafe { pdfium_sys::FPDF_InitLibrary() };
+ unsafe { ffi!(FPDF_InitLibrary()) };
});
Library { _private: () }
}
@@ -29,10 +34,10 @@ impl Library {
.transpose()?;
let handle = unsafe {
- pdfium_sys::FPDF_LoadDocument(
+ ffi!(FPDF_LoadDocument(
c_path.as_ptr(),
c_password.as_ref().map_or(std::ptr::null(), |p| p.as_ptr()),
- )
+ ))
};
if handle.is_null() {
@@ -52,11 +57,11 @@ impl Library {
.transpose()?;
let handle = unsafe {
- pdfium_sys::FPDF_LoadMemDocument(
+ ffi!(FPDF_LoadMemDocument(
data.as_ptr() as *const std::ffi::c_void,
data.len() as i32,
c_password.as_ref().map_or(std::ptr::null(), |p| p.as_ptr()),
- )
+ ))
};
if handle.is_null() {
diff --git a/crates/pdfium/src/page.rs b/crates/pdfium/src/page.rs
index 95d80e6..8e5e08a 100644
--- a/crates/pdfium/src/page.rs
+++ b/crates/pdfium/src/page.rs
@@ -3,6 +3,7 @@ use std::marker::PhantomData;
use crate::bitmap::Bitmap;
use crate::document::Document;
use crate::error::PdfiumError;
+use crate::ffi;
use crate::text_page::TextPage;
use crate::types::RectF;
@@ -24,15 +25,15 @@ pub struct Page<'doc> {
impl Page<'_> {
pub fn width(&self) -> f32 {
- unsafe { pdfium_sys::FPDF_GetPageWidthF(self.handle) }
+ unsafe { ffi!(FPDF_GetPageWidthF(self.handle)) }
}
pub fn height(&self) -> f32 {
- unsafe { pdfium_sys::FPDF_GetPageHeightF(self.handle) }
+ unsafe { ffi!(FPDF_GetPageHeightF(self.handle)) }
}
pub fn rotation(&self) -> i32 {
- unsafe { pdfium_sys::FPDFPage_GetRotation(self.handle) }
+ unsafe { ffi!(FPDFPage_GetRotation(self.handle)) }
}
/// Get the page bounding box (CropBox, falls back to MediaBox).
@@ -44,7 +45,7 @@ impl Page<'_> {
right: 0.0,
bottom: 0.0,
};
- let ok = unsafe { pdfium_sys::FPDF_GetPageBoundingBox(self.handle, &mut rect) };
+ let ok = unsafe { ffi!(FPDF_GetPageBoundingBox(self.handle, &mut rect)) };
if ok != 0 {
Some(RectF {
left: rect.left,
@@ -75,7 +76,7 @@ impl Page<'_> {
let mut dy: i32 = 0;
unsafe {
- pdfium_sys::FPDF_PageToDevice(
+ ffi!(FPDF_PageToDevice(
self.handle,
0,
0,
@@ -86,7 +87,7 @@ impl Page<'_> {
page_y as f64,
&mut dx,
&mut dy,
- );
+ ));
}
(dx as f32 / 1000.0, dy as f32 / 1000.0)
@@ -107,7 +108,7 @@ impl Page<'_> {
}
pub fn text(&self) -> Result<TextPage<'_>, PdfiumError> {
- let handle = unsafe { pdfium_sys::FPDFText_LoadPage(self.handle) };
+ let handle = unsafe { ffi!(FPDFText_LoadPage(self.handle)) };
if handle.is_null() {
return Err(PdfiumError::OperationFailed);
}
@@ -131,7 +132,7 @@ impl Page<'_> {
let flags = (pdfium_sys::FPDF_ANNOT | pdfium_sys::FPDF_PRINTING) as i32;
unsafe {
- pdfium_sys::FPDF_RenderPageBitmap(
+ ffi!(FPDF_RenderPageBitmap(
bitmap.handle(),
self.handle,
0, // start_x
@@ -140,7 +141,7 @@ impl Page<'_> {
height, // size_y
0, // rotation
flags,
- );
+ ));
}
Ok(bitmap)
@@ -153,16 +154,16 @@ impl Page<'_> {
pub fn image_bounds(&self, min_size_pt: f32, max_page_coverage: f32) -> Vec<ImageBounds> {
let page_width = self.width();
let page_height = self.height();
- let obj_count = unsafe { pdfium_sys::FPDFPage_CountObjects(self.handle) };
+ let obj_count = unsafe { ffi!(FPDFPage_CountObjects(self.handle)) };
let mut results = Vec::new();
for i in 0..obj_count {
- let obj = unsafe { pdfium_sys::FPDFPage_GetObject(self.handle, i) };
+ let obj = unsafe { ffi!(FPDFPage_GetObject(self.handle, i)) };
if obj.is_null() {
continue;
}
- let obj_type = unsafe { pdfium_sys::FPDFPageObj_GetType(obj) };
+ let obj_type = unsafe { ffi!(FPDFPageObj_GetType(obj)) };
if obj_type != pdfium_sys::FPDF_PAGEOBJ_IMAGE as i32 {
continue;
}
@@ -172,7 +173,7 @@ impl Page<'_> {
let mut right: f32 = 0.0;
let mut top: f32 = 0.0;
let ok = unsafe {
- pdfium_sys::FPDFPageObj_GetBounds(obj, &mut left, &mut bottom, &mut right, &mut top)
+ ffi!(FPDFPageObj_GetBounds(obj, &mut left, &mut bottom, &mut right, &mut top))
};
if ok == 0 {
continue;
@@ -203,22 +204,22 @@ impl Page<'_> {
/// Get the rendered bitmap of a specific embedded image object by index.
/// The index corresponds to the order from iterating page objects (image objects only).
pub fn render_image_object(&self, image_obj_index: usize) -> Result<Bitmap, PdfiumError> {
- let obj_count = unsafe { pdfium_sys::FPDFPage_CountObjects(self.handle) };
+ let obj_count = unsafe { ffi!(FPDFPage_CountObjects(self.handle)) };
let mut image_idx = 0usize;
for i in 0..obj_count {
- let obj = unsafe { pdfium_sys::FPDFPage_GetObject(self.handle, i) };
+ let obj = unsafe { ffi!(FPDFPage_GetObject(self.handle, i)) };
if obj.is_null() {
continue;
}
- let obj_type = unsafe { pdfium_sys::FPDFPageObj_GetType(obj) };
+ let obj_type = unsafe { ffi!(FPDFPageObj_GetType(obj)) };
if obj_type != pdfium_sys::FPDF_PAGEOBJ_IMAGE as i32 {
continue;
}
if image_idx == image_obj_index {
let bmp_handle = unsafe {
- pdfium_sys::FPDFImageObj_GetRenderedBitmap(self.doc_handle, self.handle, obj)
+ ffi!(FPDFImageObj_GetRenderedBitmap(self.doc_handle, self.handle, obj))
};
if bmp_handle.is_null() {
return Err(PdfiumError::OperationFailed);
@@ -291,6 +292,6 @@ impl Page<'_> {
impl Drop for Page<'_> {
fn drop(&mut self) {
- unsafe { pdfium_sys::FPDF_ClosePage(self.handle) };
+ unsafe { ffi!(FPDF_ClosePage(self.handle)) };
}
}
diff --git a/crates/pdfium/src/text_page.rs b/crates/pdfium/src/text_page.rs
index d065ddb..a3c8b60 100644
--- a/crates/pdfium/src/text_page.rs
+++ b/crates/pdfium/src/text_page.rs
@@ -1,5 +1,6 @@
use std::marker::PhantomData;
+use crate::ffi;
use crate::page::Page;
use crate::types::{CharBox, Color, Matrix, RectF, TextRect};
@@ -10,7 +11,7 @@ pub struct TextPage<'page> {
impl TextPage<'_> {
pub fn char_count(&self) -> i32 {
- unsafe { pdfium_sys::FPDFText_CountChars(self.handle) }
+ unsafe { ffi!(FPDFText_CountChars(self.handle)) }
}
pub fn chars(&self) -> TextCharIter<'_> {
@@ -44,7 +45,7 @@ impl TextPage<'_> {
/// Count rectangular areas occupied by a text segment.
/// Must be called before `rect()`.
pub fn count_rects(&self, start: i32, count: i32) -> i32 {
- unsafe { pdfium_sys::FPDFText_CountRects(self.handle, start, count) }
+ unsafe { ffi!(FPDFText_CountRects(self.handle, start, count)) }
}
/// Get a rectangle from the last `count_rects()` call.
@@ -54,14 +55,14 @@ impl TextPage<'_> {
let mut right = 0.0;
let mut bottom = 0.0;
let ok = unsafe {
- pdfium_sys::FPDFText_GetRect(
+ ffi!(FPDFText_GetRect(
self.handle,
index,
&mut left,
&mut top,
&mut right,
&mut bottom,
- )
+ ))
};
if ok != 0 {
Some(TextRect {
@@ -79,7 +80,7 @@ impl TextPage<'_> {
pub fn bounded_text(&self, left: f64, top: f64, right: f64, bottom: f64) -> String {
// First call to get required buffer length (in UTF-16 code units, excluding terminator)
let len = unsafe {
- pdfium_sys::FPDFText_GetBoundedText(
+ ffi!(FPDFText_GetBoundedText(
self.handle,
left,
top,
@@ -87,7 +88,7 @@ impl TextPage<'_> {
bottom,
std::ptr::null_mut(),
0,
- )
+ ))
};
if len <= 0 {
return String::new();
@@ -97,7 +98,7 @@ impl TextPage<'_> {
let buf_len = len + 1;
let mut buf: Vec<u16> = vec![0; buf_len as usize];
let written = unsafe {
- pdfium_sys::FPDFText_GetBoundedText(
+ ffi!(FPDFText_GetBoundedText(
self.handle,
left,
top,
@@ -105,7 +106,7 @@ impl TextPage<'_> {
bottom,
buf.as_mut_ptr(),
buf_len,
- )
+ ))
};
if written <= 0 {
@@ -130,7 +131,7 @@ impl TextPage<'_> {
let buf_len = count + 1; // +1 for terminator
let mut buf: Vec<u16> = vec![0; buf_len as usize];
let written =
- unsafe { pdfium_sys::FPDFText_GetText(self.handle, start, count, buf.as_mut_ptr()) };
+ unsafe { ffi!(FPDFText_GetText(self.handle, start, count, buf.as_mut_ptr())) };
if written <= 0 {
return String::new();
}
@@ -145,7 +146,7 @@ impl TextPage<'_> {
impl Drop for TextPage<'_> {
fn drop(&mut self) {
- unsafe { pdfium_sys::FPDFText_ClosePage(self.handle) };
+ unsafe { ffi!(FPDFText_ClosePage(self.handle)) };
}
}
@@ -158,47 +159,47 @@ pub struct TextChar<'tp> {
impl TextChar<'_> {
pub fn unicode(&self) -> u32 {
- unsafe { pdfium_sys::FPDFText_GetUnicode(self.text_page.handle, self.index) }
+ unsafe { ffi!(FPDFText_GetUnicode(self.text_page.handle, self.index)) }
}
/// Raw character code from the PDF content stream (not Unicode).
/// Only meaningful for non-generated characters.
pub fn char_code(&self) -> u32 {
- unsafe { pdfium_sys::FPDFText_GetCharCode(self.text_page.handle, self.index) }
+ unsafe { ffi!(FPDFText_GetCharCode(self.text_page.handle, self.index)) }
}
pub fn font_size(&self) -> f64 {
- unsafe { pdfium_sys::FPDFText_GetFontSize(self.text_page.handle, self.index) }
+ unsafe { ffi!(FPDFText_GetFontSize(self.text_page.handle, self.index)) }
}
pub fn font_weight(&self) -> i32 {
- unsafe { pdfium_sys::FPDFText_GetFontWeight(self.text_page.handle, self.index) }
+ unsafe { ffi!(FPDFText_GetFontWeight(self.text_page.handle, self.index)) }
}
/// Get font info name and flags. Returns (name, flags) or None.
pub fn font_info(&self) -> Option<(String, i32)> {
let mut flags: i32 = 0;
let len = unsafe {
- pdfium_sys::FPDFText_GetFontInfo(
+ ffi!(FPDFText_GetFontInfo(
self.text_page.handle,
self.index,
std::ptr::null_mut(),
0,
&mut flags,
- )
+ ))
};
if len == 0 {
return None;
}
let mut buf: Vec<u8> = vec![0; len as usize];
let written = unsafe {
- pdfium_sys::FPDFText_GetFontInfo(
+ ffi!(FPDFText_GetFontInfo(
self.text_page.handle,
self.index,
buf.as_mut_ptr() as *mut std::ffi::c_void,
len,
&mut flags,
- )
+ ))
};
if written == 0 {
return None;
@@ -217,12 +218,12 @@ impl TextChar<'_> {
/// Angle in radians. Returns -1 on error.
pub fn angle(&self) -> f32 {
- unsafe { pdfium_sys::FPDFText_GetCharAngle(self.text_page.handle, self.index) }
+ unsafe { ffi!(FPDFText_GetCharAngle(self.text_page.handle, self.index)) }
}
/// Get the FPDF_PAGEOBJECT for this character (for font/color extraction).
pub fn text_object(&self) -> Option<pdfium_sys::FPDF_PAGEOBJECT> {
- let obj = unsafe { pdfium_sys::FPDFText_GetTextObject(self.text_page.handle, self.index) };
+ let obj = unsafe { ffi!(FPDFText_GetTextObject(self.text_page.handle, self.index)) };
if obj.is_null() { None } else { Some(obj) }
}
@@ -233,14 +234,14 @@ impl TextChar<'_> {
let mut b = 0u32;
let mut a = 0u32;
let ok = unsafe {
- pdfium_sys::FPDFText_GetStrokeColor(
+ ffi!(FPDFText_GetStrokeColor(
self.text_page.handle,
self.index,
&mut r,
&mut g,
&mut b,
&mut a,
- )
+ ))
};
if ok != 0 {
Some(Color {
@@ -261,14 +262,14 @@ impl TextChar<'_> {
let mut b = 0u32;
let mut a = 0u32;
let ok = unsafe {
- pdfium_sys::FPDFText_GetFillColor(
+ ffi!(FPDFText_GetFillColor(
self.text_page.handle,
self.index,
&mut r,
&mut g,
&mut b,
&mut a,
- )
+ ))
};
if ok != 0 {
Some(Color {
@@ -286,14 +287,14 @@ impl TextChar<'_> {
/// Returns the raw FPDF_TEXT_RENDERMODE value (0=fill, 1=stroke, 2=fill+stroke, 3=invisible, etc.)
pub fn text_render_mode(&self) -> Option<i32> {
let obj = self.text_object()?;
- let mode = unsafe { pdfium_sys::FPDFTextObj_GetTextRenderMode(obj) };
+ let mode = unsafe { ffi!(FPDFTextObj_GetTextRenderMode(obj)) };
if mode >= 0 { Some(mode) } else { None }
}
/// Get marked content ID from the page object (-1 if none).
pub fn marked_content_id(&self) -> Option<i32> {
let obj = self.text_object()?;
- let mcid = unsafe { pdfium_sys::FPDFPageObj_GetMarkedContentID(obj) };
+ let mcid = unsafe { ffi!(FPDFPageObj_GetMarkedContentID(obj)) };
if mcid >= 0 { Some(mcid) } else { None }
}
@@ -303,14 +304,14 @@ impl TextChar<'_> {
let mut bottom = 0.0;
let mut top = 0.0;
let ok = unsafe {
- pdfium_sys::FPDFText_GetCharBox(
+ ffi!(FPDFText_GetCharBox(
self.text_page.handle,
self.index,
&mut left,
&mut right,
&mut bottom,
&mut top,
- )
+ ))
};
if ok != 0 {
Some(CharBox {
@@ -332,7 +333,7 @@ impl TextChar<'_> {
bottom: 0.0,
};
let ok = unsafe {
- pdfium_sys::FPDFText_GetLooseCharBox(self.text_page.handle, self.index, &mut rect)
+ ffi!(FPDFText_GetLooseCharBox(self.text_page.handle, self.index, &mut rect))
};
if ok != 0 {
Some(RectF {
@@ -356,7 +357,7 @@ impl TextChar<'_> {
f: 0.0,
};
let ok =
- unsafe { pdfium_sys::FPDFText_GetMatrix(self.text_page.handle, self.index, &mut m) };
+ unsafe { ffi!(FPDFText_GetMatrix(self.text_page.handle, self.index, &mut m)) };
if ok != 0 {
Some(Matrix {
a: m.a,
@@ -372,11 +373,11 @@ impl TextChar<'_> {
}
pub fn is_generated(&self) -> bool {
- unsafe { pdfium_sys::FPDFText_IsGenerated(self.text_page.handle, self.index) == 1 }
+ unsafe { ffi!(FPDFText_IsGenerated(self.text_page.handle, self.index)) == 1 }
}
pub fn has_unicode_map_error(&self) -> bool {
- unsafe { pdfium_sys::FPDFText_HasUnicodeMapError(self.text_page.handle, self.index) == 1 }
+ unsafe { ffi!(FPDFText_HasUnicodeMapError(self.text_page.handle, self.index)) == 1 }
}
}