use std::path::{Path, PathBuf};
use anyhow::{Context, Result, anyhow};
use pdfium_render::prelude::*;
pub const PDFIUM_BUILD: &str = "chromium/8179";
fn platform_dir() -> &'static str {
match (std::env::consts::OS, std::env::consts::ARCH) {
("windows", "x86_64") => "win-x64",
("windows", "aarch64") => "win-arm64",
("macos", "aarch64") => "mac-arm64",
("macos", "x86_64") => "mac-x64",
("linux", "aarch64") => "linux-arm64",
_ => "linux-x64",
}
}
fn candidates() -> Vec<PathBuf> {
let mut dirs = Vec::new();
if let Some(p) = std::env::var_os("PDFSIFT_PDFIUM") {
let p = PathBuf::from(p);
if p.is_file() {
return vec![p];
}
dirs.push(p);
}
if let Ok(exe) = std::env::current_exe() {
let resolved = std::fs::symlink_metadata(&exe)
.is_ok_and(|m| m.file_type().is_symlink())
.then(|| std::fs::canonicalize(&exe).ok())
.flatten();
for exe in std::iter::once(exe).chain(resolved) {
if let Some(dir) = exe.parent() {
dirs.push(dir.to_path_buf());
dirs.push(dir.join("pdfium"));
if let Some(prefix) = dir.parent() {
let share = prefix.join("share").join("pdfsift");
dirs.push(prefix.join("lib"));
dirs.push(share.join("pdfium"));
dirs.push(share);
}
}
}
}
if cfg!(debug_assertions) {
let dev = Path::new(".pdfium").join(platform_dir());
dirs.push(dev.join("bin"));
dirs.push(dev.join("lib"));
}
let mut libs: Vec<PathBuf> = dirs
.into_iter()
.map(|d| Pdfium::pdfium_platform_library_name_at_path(&d))
.collect();
libs.dedup();
libs
}
pub fn load() -> Result<Pdfium> {
let libs = candidates();
for lib in &libs {
if lib.is_file() {
let bindings = Pdfium::bind_to_library(lib).with_context(|| {
format!(
"failed to load PDFium from {} (pdfsift needs the PDFium {PDFIUM_BUILD} \
build for this platform from github.com/bblanchon/pdfium-binaries)",
lib.display()
)
})?;
return Ok(Pdfium::new(bindings));
}
}
let system = if cfg!(windows) {
Err("not searched on Windows".to_string())
} else {
Pdfium::bind_to_system_library().map_err(|e| format!("{e:?}"))
};
let bindings = system.map_err(|e| not_found(&libs, &e))?;
Ok(Pdfium::new(bindings))
}
fn not_found(searched: &[PathBuf], system: &str) -> anyhow::Error {
let mut msg = format!(
"PDFium library not found. pdfsift loads {name} at runtime; the release archives \
and the npm/PyPI packages ship it next to the executable, but `cargo install` \
does not.\n\
To fix it, download pdfium-{platform}.tgz from \
https://github.com/bblanchon/pdfium-binaries/releases/tag/{tag} \
and either copy {name} (in its bin/ or lib/ folder) next to the pdfsift \
executable, or set PDFSIFT_PDFIUM to its path.\n\
Searched:",
name = Pdfium::pdfium_platform_library_name().to_string_lossy(),
platform = platform_dir(),
tag = PDFIUM_BUILD.replace('/', "%2F"),
);
for p in searched {
msg.push_str(&format!("\n {}", p.display()));
}
msg.push_str(&format!("\n system library path: {system}"));
anyhow!(msg)
}