50 lines
2.0 KiB
Rust
50 lines
2.0 KiB
Rust
use crate::PdfError;
|
|
use pdfium_render::prelude::*;
|
|
use std::path::Path;
|
|
use std::sync::OnceLock;
|
|
|
|
/// The one pdfium instance of the process (pdfium is not thread-safe; pdfium-render's `thread_safe` feature
|
|
/// serialises calls). Load it once with [`Engine::load`].
|
|
pub struct Engine {
|
|
pub(crate) pdfium: Pdfium,
|
|
}
|
|
|
|
static ENGINE: OnceLock<Engine> = OnceLock::new();
|
|
static LOAD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
|
|
|
impl Engine {
|
|
/// Loads pdfium.dll from `dir` (or from the system search path when `None`). Later calls return the same engine.
|
|
pub fn load(dir: Option<&Path>) -> Result<&'static Engine, PdfError> {
|
|
if let Some(e) = ENGINE.get() {
|
|
return Ok(e);
|
|
}
|
|
let _guard = LOAD_LOCK.lock().unwrap_or_else(|p| p.into_inner());
|
|
if let Some(e) = ENGINE.get() {
|
|
return Ok(e);
|
|
}
|
|
let bindings = match dir {
|
|
Some(d) => Pdfium::bind_to_library(Pdfium::pdfium_platform_library_name_at_path(d)),
|
|
None => Pdfium::bind_to_system_library(),
|
|
}
|
|
.map_err(|e| PdfError::EngineMissing(e.to_string()))?;
|
|
let _ = ENGINE.set(Engine { pdfium: Pdfium::new(bindings) });
|
|
Ok(ENGINE.get().expect("just set"))
|
|
}
|
|
|
|
pub(crate) fn open<'a>(&'a self, bytes: &'a [u8], password: Option<&str>) -> Result<PdfDocument<'a>, PdfError> {
|
|
self.pdfium
|
|
.load_pdf_from_byte_slice(bytes, password)
|
|
.map_err(|e| PdfError::from_pdfium_open(e, password.is_some()))
|
|
}
|
|
|
|
pub(crate) fn new_document(&self) -> Result<PdfDocument<'_>, PdfError> {
|
|
self.pdfium.create_new_pdf().map_err(PdfError::from_pdfium)
|
|
}
|
|
}
|
|
|
|
/// pdfium's save (flags 0: an encrypted document would keep its security handler). Pictor only calls it on
|
|
/// unencrypted documents (the edit pipeline unlocks first) and on new ones (merge); lopdf writes encryption.
|
|
pub(crate) fn pdfium_save(doc: &PdfDocument) -> Result<Vec<u8>, PdfError> {
|
|
doc.save_to_bytes().map_err(|e| PdfError::Write(e.to_string()))
|
|
}
|