use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use anyhow::{Context, Result};
use pdfium_render::prelude::*;
use super::{PageRuns, TextRun, TextSource};
static PDFIUM: OnceLock<std::result::Result<Pdfium, String>> = OnceLock::new();
pub struct PdfiumSource {
pdfium: &'static Pdfium,
}
impl PdfiumSource {
pub fn new() -> Result<Self> {
match PDFIUM.get_or_init(|| {
bind_library()
.map(Pdfium::new)
.map_err(|e| format!("{e:#}"))
}) {
Ok(pdfium) => Ok(Self { pdfium }),
Err(message) => Err(anyhow::anyhow!("{message}")),
}
}
}
fn bind_library() -> Result<Box<dyn PdfiumLibraryBindings>> {
if let Ok(env_path) = std::env::var("PDFIUM_DYNAMIC_LIB_PATH") {
let lib = library_file(Path::new(&env_path));
return Pdfium::bind_to_library(&lib).with_context(|| {
format!(
"PDFIUM_DYNAMIC_LIB_PATH is set but no PDFium library loads from {}",
lib.display()
)
});
}
let local = library_file(Path::new(".pdfium"));
if local.exists() {
if let Ok(bindings) = Pdfium::bind_to_library(&local) {
return Ok(bindings);
}
}
Pdfium::bind_to_system_library().context(
"no PDFium library found (searched PDFIUM_DYNAMIC_LIB_PATH, ./.pdfium/, system paths)",
)
}
fn library_file(path: &Path) -> PathBuf {
if path.is_file() {
path.to_path_buf()
} else {
Pdfium::pdfium_platform_library_name_at_path(path)
}
}
impl TextSource for PdfiumSource {
fn pages(&self, pdf_bytes: &[u8]) -> Result<Vec<PageRuns>> {
let doc = self
.pdfium
.load_pdf_from_byte_slice(pdf_bytes, None)
.context("pdfium could not parse the PDF")?;
let mut pages = Vec::new();
for (index, page) in doc.pages().iter().enumerate() {
let mut runs = Vec::new();
for object in page.objects().iter() {
if let PdfPageObject::Text(ref text_object) = object {
let text = text_object.text();
if text.trim().is_empty() {
continue;
}
let rect = object
.bounds()
.map(|quad| quad.to_rect())
.unwrap_or(PdfRect::ZERO);
let font = text_object.font();
let name = font.name();
let lower = name.to_ascii_lowercase();
let bold = matches!(
font.weight(),
Ok(PdfFontWeight::Weight600
| PdfFontWeight::Weight700Bold
| PdfFontWeight::Weight800
| PdfFontWeight::Weight900)
) || lower.contains("bold");
let italic =
font.is_italic() || lower.contains("italic") || lower.contains("oblique");
runs.push(TextRun {
text,
bbox: (
rect.left().value,
rect.bottom().value,
rect.right().value,
rect.top().value,
),
font_size: text_object.scaled_font_size().value,
bold,
italic,
font: Some(name),
page: index,
});
}
}
pages.push(PageRuns {
width: page.width().value,
height: page.height().value,
runs,
});
}
Ok(pages)
}
}