pdf-untangle 0.3.0

Untangle garbled PDF text: layout-aware extraction that reconstructs reading order, strips page furniture, and splits documents into structured, citable sections
Documentation
//! PDFium extraction backend (`backend-pdfium` feature).
//!
//! Wraps Google PDFium via the [`pdfium-render`] crate. PDFium is loaded as a
//! *dynamic library at runtime* — building with this feature adds no native
//! build step, but extraction requires `libpdfium` to be present when the
//! program runs. [`PdfiumSource::new`] searches, in order:
//!
//! 1. the `PDFIUM_DYNAMIC_LIB_PATH` environment variable (a directory
//!    containing the platform library, or a path to the library file itself),
//! 2. a `.pdfium/` directory under the current working directory,
//! 3. the system library search path.
//!
//! `scripts/fetch-pdfium.sh` downloads a prebuilt library from the
//! `bblanchon/pdfium-binaries` project into `.pdfium/` for local development.
//!
//! This is the highest-fidelity backend: per-object bounding boxes straight
//! from PDFium, effective (matrix-scaled) font sizes, font names, and
//! bold/italic derived from the font's declared weight, flags, and name.
//!
//! [`pdfium-render`]: https://crates.io/crates/pdfium-render

use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use anyhow::{Context, Result};
use pdfium_render::prelude::*;

use super::{PageRuns, TextRun, TextSource};

/// The PDFium binding is process-global (pdfium-render allows exactly one
/// initialization), so the loaded library lives in a singleton. The search
/// paths are therefore consulted only on the first successful or failed
/// attempt in a process.
static PDFIUM: OnceLock<std::result::Result<Pdfium, String>> = OnceLock::new();

/// The PDFium-backed [`TextSource`]. Borrows the process-global library
/// binding; cheap to construct once the library has loaded.
pub struct PdfiumSource {
    pdfium: &'static Pdfium,
}

impl PdfiumSource {
    /// Bind to a PDFium library, searching the locations documented at the
    /// [module level](self). Fails if no loadable library is found. The
    /// binding is process-global: only the first call performs the search,
    /// and subsequent calls reuse its outcome.
    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)",
    )
}

/// Resolve `path` to a library file: passed through if it already names a
/// file, otherwise treated as a directory holding the platform library.
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();
                    // Trust only *declared standard* weights: real-world PDFs
                    // frequently carry synthesized non-standard weights (e.g.
                    // 740 on a regular face), so `Custom(_)` values are
                    // ignored and the font name is consulted instead.
                    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)
    }
}