use super::extract::{RawPage, extract_page};
use super::fonts::{FontInfo, FontRegistry, UNKNOWN_FONT};
use super::render::{PageRenderer, PngCompression};
use crate::common::parallel;
use anyhow::{Result, anyhow};
use hayro_interpret::{InterpreterCache, InterpreterSettings};
use hayro_syntax::Pdf;
use std::collections::HashMap;
const FILE_NAME_TITLE_MARKS: [&str; 7] = [".tex", ".dvi", ".pdf", ".doc", ".docx", ".indd", "Microsoft Word - "];
pub struct PdfFile {
pdf: Pdf,
png: PngCompression,
}
impl PdfFile {
pub fn open(data: Vec<u8>) -> Result<Self> {
let head = &data[..data.len().min(1024)];
if !head.windows(5).any(|window| window == b"%PDF-") {
return Err(anyhow!("not a PDF, Word document or EPUB book"));
}
let pdf = Pdf::new(data).map_err(|err| anyhow!("cannot read PDF: {err:?}"))?;
if pdf.pages().is_empty() {
return Err(anyhow!("the PDF has no pages"));
}
Ok(Self {
pdf,
png: PngCompression::default(),
})
}
pub fn page_count(&self) -> usize {
self.pdf.pages().len()
}
pub fn renderer(&self) -> PageRenderer<'_> {
PageRenderer::new(&self.pdf).with_png_compression(self.png)
}
pub fn set_png_compression(&mut self, compression: PngCompression) {
self.png = compression;
}
pub fn extract(&self, jobs: usize) -> (Vec<RawPage>, Vec<FontInfo>) {
let pages = self.pdf.pages();
let extracted = parallel::map(
pages.len(),
jobs,
|| {
(
FontRegistry::new(),
InterpreterCache::new(),
InterpreterSettings::default(),
)
},
|(fonts, cache, settings), page_idx| {
let page = extract_page(&pages[page_idx], page_idx, fonts, cache, settings);
let used = fonts_used(&page, fonts);
(page, used)
},
);
unify_fonts(extracted)
}
pub fn info_title(&self) -> Option<String> {
let raw = self.pdf.metadata().title.as_deref()?;
let title = decode_text_string(raw).split_whitespace().collect::<Vec<_>>().join(" ");
let is_file_name = FILE_NAME_TITLE_MARKS
.iter()
.any(|mark| title.ends_with(mark) || title.starts_with(mark));
(!title.is_empty() && !is_file_name).then_some(title)
}
}
fn decode_text_string(raw: &[u8]) -> String {
let utf16 = |bytes: &[u8], big_endian: bool| {
let units: Vec<u16> = bytes
.as_chunks::<2>()
.0
.iter()
.map(|pair| {
if big_endian {
u16::from_be_bytes(*pair)
} else {
u16::from_le_bytes(*pair)
}
})
.collect();
String::from_utf16_lossy(&units)
};
match raw {
[0xFE, 0xFF, rest @ ..] => utf16(rest, true),
[0xFF, 0xFE, rest @ ..] => utf16(rest, false),
_ => {
std::str::from_utf8(raw).map_or_else(|_| raw.iter().map(|&byte| char::from(byte)).collect(), str::to_string)
}
}
}
fn fonts_used(page: &RawPage, fonts: &FontRegistry<'_>) -> Vec<(u16, FontInfo)> {
let mut used: Vec<(u16, FontInfo)> = Vec::new();
for glyph in &page.glyphs {
if !used.iter().any(|(font, _)| *font == glyph.font) {
used.push((glyph.font, fonts.infos[glyph.font as usize].clone()));
}
}
used
}
fn unify_fonts(extracted: Vec<(RawPage, Vec<(u16, FontInfo)>)>) -> (Vec<RawPage>, Vec<FontInfo>) {
let mut infos = FontRegistry::new().infos; let mut by_name: HashMap<String, u16> = HashMap::new();
let mut raw = Vec::with_capacity(extracted.len());
for (mut page, used) in extracted {
let to_global: HashMap<u16, u16> = used
.into_iter()
.map(|(local, info)| {
if local == UNKNOWN_FONT {
return (local, local);
}
let global = *by_name.entry(info.name.clone()).or_insert_with(|| {
infos.push(info);
(infos.len() - 1) as u16
});
(local, global)
})
.collect();
for glyph in &mut page.glyphs {
glyph.font = to_global[&glyph.font];
}
raw.push(page);
}
(raw, infos)
}
#[cfg(test)]
mod tests {
use super::{FontInfo, FontRegistry, PdfFile, decode_text_string, extract_page};
use hayro_interpret::{InterpreterCache, InterpreterSettings};
fn glyph_fonts(pdf: &PdfFile, pages: impl Iterator<Item = usize>) -> Vec<Vec<FontInfo>> {
let all = pdf.pdf.pages();
let (mut fonts, cache, settings) = (
FontRegistry::new(),
InterpreterCache::new(),
InterpreterSettings::default(),
);
let mut by_page = vec![Vec::new(); all.len()];
for index in pages {
let page = extract_page(&all[index], index, &mut fonts, &cache, &settings);
by_page[index] = page
.glyphs
.iter()
.map(|glyph| fonts.infos[glyph.font as usize].clone())
.collect();
}
by_page
}
#[test]
fn a_glyphs_font_does_not_depend_on_the_pages_read_before() {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/1602.03837v1.pdf")).unwrap();
let pdf = PdfFile::open(data).unwrap();
let count = pdf.page_count();
assert_eq!(glyph_fonts(&pdf, 0..count), glyph_fonts(&pdf, (0..count).rev()));
}
#[test]
fn text_strings_are_decoded() {
assert_eq!(decode_text_string(b"Plain title"), "Plain title");
assert_eq!(decode_text_string(&[0xFE, 0xFF, 0x00, 0x4D, 0x00, 0xE9]), "Mé");
assert_eq!(decode_text_string(&[0x4D, 0xE9]), "Mé");
assert_eq!(decode_text_string("Mé".as_bytes()), "Mé");
}
}