use anyhow::Result;
use serde::Serialize;
#[cfg(feature = "backend-pdfium")]
pub mod pdfium;
#[cfg(feature = "backend-pure")]
pub mod pure;
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TextRun {
pub text: String,
pub bbox: (f32, f32, f32, f32),
pub font_size: f32,
pub bold: bool,
pub italic: bool,
pub font: Option<String>,
pub page: usize,
}
#[derive(Debug, Clone, Serialize)]
pub struct PageRuns {
pub width: f32,
pub height: f32,
pub runs: Vec<TextRun>,
}
pub trait TextSource {
fn pages(&self, pdf_bytes: &[u8]) -> Result<Vec<PageRuns>>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Backend {
Pdfium,
Pure,
}
impl Backend {
pub fn name(self) -> &'static str {
match self {
Backend::Pdfium => "pdfium",
Backend::Pure => "pure",
}
}
}
impl std::fmt::Display for Backend {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
pub fn runs(pdf_bytes: &[u8]) -> Result<Vec<PageRuns>> {
runs_with_backend(pdf_bytes).map(|(pages, _)| pages)
}
#[allow(unreachable_code)]
#[allow(clippy::needless_return)]
pub fn runs_with_backend(pdf_bytes: &[u8]) -> Result<(Vec<PageRuns>, Backend)> {
#[cfg(feature = "backend-pdfium")]
{
match pdfium::PdfiumSource::new() {
Ok(source) => {
log::info!("extracting with the pdfium backend");
return source.pages(pdf_bytes).map(|p| (p, Backend::Pdfium));
}
#[cfg(feature = "backend-pure")]
Err(e) => {
log::warn!("pdfium library unavailable ({e:#}); falling back to pure backend");
}
#[cfg(not(feature = "backend-pure"))]
Err(e) => {
return Err(e.context(
"pdfium library not found; set PDFIUM_DYNAMIC_LIB_PATH or run \
scripts/fetch-pdfium.sh (see README)",
));
}
}
}
#[cfg(feature = "backend-pure")]
{
log::info!("extracting with the pure backend");
return pure::PureSource
.pages(pdf_bytes)
.map(|p| (p, Backend::Pure));
}
#[cfg(not(any(feature = "backend-pdfium", feature = "backend-pure")))]
{
let _ = pdf_bytes;
anyhow::bail!(
"no extraction backend compiled in: enable the `backend-pdfium` and/or \
`backend-pure` cargo feature"
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn backend_names_are_stable() {
assert_eq!(Backend::Pdfium.name(), "pdfium");
assert_eq!(Backend::Pure.name(), "pure");
assert_eq!(Backend::Pdfium.to_string(), "pdfium");
assert_eq!(serde_json::to_string(&Backend::Pure).unwrap(), "\"pure\"");
}
#[test]
fn text_run_serializes_for_inspect_json() {
let run = TextRun {
text: "§ 2051. Definitions.".into(),
bbox: (72.0, 700.5, 210.0, 712.0),
font_size: 11.5,
bold: true,
italic: false,
font: Some("TimesNewRomanPS-BoldMT".into()),
page: 0,
};
let v: serde_json::Value = serde_json::to_value(&run).unwrap();
assert_eq!(v["text"], "§ 2051. Definitions.");
assert_eq!(v["bbox"][0], 72.0);
assert_eq!(v["bold"], true);
assert_eq!(v["font"], "TimesNewRomanPS-BoldMT");
}
#[cfg(not(any(feature = "backend-pdfium", feature = "backend-pure")))]
#[test]
fn runs_errors_without_a_backend() {
let err = runs(b"%PDF-1.7 not really").unwrap_err();
assert!(err.to_string().contains("no extraction backend"));
}
#[cfg(feature = "backend-pure")]
#[test]
fn pure_backend_rejects_garbage_bytes() {
assert!(pure::PureSource.pages(b"this is not a pdf").is_err());
}
#[cfg(feature = "backend-pure")]
fn minimal_pdf() -> Vec<u8> {
let mut pdf = Vec::new();
let mut offsets = Vec::new();
let header = b"%PDF-1.4\n";
pdf.extend_from_slice(header);
let objects: Vec<String> = vec![
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n".into(),
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n".into(),
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>\nendobj\n"
.into(),
"4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n".into(),
{
let stream = "BT /F1 12 Tf 72 720 Td (Hello Untangle) Tj ET";
format!(
"5 0 obj\n<< /Length {} >>\nstream\n{}\nendstream\nendobj\n",
stream.len(),
stream
)
},
];
for obj in &objects {
offsets.push(pdf.len());
pdf.extend_from_slice(obj.as_bytes());
}
let xref_at = pdf.len();
pdf.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
pdf.extend_from_slice(b"0000000000 65535 f \n");
for off in &offsets {
pdf.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
}
pdf.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
xref_at
)
.as_bytes(),
);
pdf
}
#[cfg(feature = "backend-pure")]
#[test]
fn pure_backend_extracts_positioned_text() {
let pages = pure::PureSource.pages(&minimal_pdf()).unwrap();
assert_eq!(pages.len(), 1);
assert_eq!(pages[0].width, 612.0);
assert_eq!(pages[0].height, 792.0);
let text: String = pages[0].runs.iter().map(|r| r.text.as_str()).collect();
assert!(text.contains("Hello Untangle"), "got: {text:?}");
let run = &pages[0].runs[0];
assert!((run.bbox.0 - 72.0).abs() < 1.0, "x0 was {}", run.bbox.0);
assert!((run.bbox.1 - 720.0).abs() < 6.0, "y0 was {}", run.bbox.1);
assert!((run.font_size - 12.0).abs() < 0.01);
assert_eq!(run.page, 0);
}
#[cfg(feature = "backend-pure")]
#[test]
fn runs_dispatches_to_a_real_backend() {
let (pages, backend) = runs_with_backend(&minimal_pdf()).unwrap();
assert_eq!(pages.len(), 1);
assert!(matches!(backend, Backend::Pdfium | Backend::Pure));
}
}