//! A lab report's PDF read for its text layer: every glyph and where it //! stands, made into lines and cells ([`super::text::assemble`]). Pure Rust //! over `lopdf`: nothing to install on a Mac, the same on an iPhone and on //! Android. A scan (no text layer) reads as pages with no lines; a locked //! PDF is refused by name. Nothing here logs a glyph. //! //! The page's content is interpreted here, as the PDF spec draws it: the //! graphics state (`q`/`Q`/`cm`), forms (`Do`) with their own matrix and //! resources, the text state (`Tf Tc Tw Tz TL Ts`), the text matrix (`BT //! Td TD Tm T*`) and the showing operators (`Tj TJ ' "`). Each code is //! decoded through the font's ToUnicode map (else its encoding) and advanced //! by its own width (`W`/`DW` of a CID font, `Widths` of a simple one, the //! standard metrics of an unembedded base font), so a glyph's position is //! where the page draws it, whatever matrices a generator stacks. Text that //! does not run left to right on the page (a rotated margin note) is left //! out: no result table is printed sideways. use std::collections::HashMap; use lopdf::{Dictionary, Document, Object, ObjectId}; use super::text::{assemble, Glyph, TextPage}; /// Why a PDF did not read. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum PdfError { #[error("the file is not a PDF that reads")] DoesNotRead, #[error("the PDF is locked with a password")] Locked, #[error("the PDF's text did not read")] TextDoesNotRead, } /// The pages of a PDF's bytes, as lines and cells. pub fn pages_of(bytes: &[u8]) -> Result, PdfError> { Ok(glyphs_of(bytes)?.into_iter().map(assemble).collect()) } /// Each page's glyphs, `y` from the page's top. pub fn glyphs_of(bytes: &[u8]) -> Result>, PdfError> { let document = match Document::load_mem(bytes) { Ok(document) => document, Err(lopdf::Error::Decryption(_)) | Err(lopdf::Error::InvalidPassword) => return Err(PdfError::Locked), Err(_) => return Err(PdfError::DoesNotRead), }; if document.is_encrypted() { return Err(PdfError::Locked); } let mut reader = Reader { document: &document, fonts: HashMap::new() }; let mut pages = Vec::new(); for (_, page_id) in document.get_pages() { pages.push(reader.page(page_id).ok_or(PdfError::TextDoesNotRead)?); } Ok(pages) } /// A 2-D affine matrix `[a b c d e f]`, row vector times matrix as the spec writes it. #[derive(Debug, Clone, Copy, PartialEq)] struct Matrix([f64; 6]); impl Matrix { const IDENTITY: Matrix = Matrix([1., 0., 0., 1., 0., 0.]); fn translate(x: f64, y: f64) -> Matrix { Matrix([1., 0., 0., 1., x, y]) } /// `self` then `then`. fn then(self, then: Matrix) -> Matrix { let [a, b, c, d, e, f] = self.0; let [a2, b2, c2, d2, e2, f2] = then.0; Matrix([a * a2 + b * c2, a * b2 + b * d2, c * a2 + d * c2, c * b2 + d * d2, e * a2 + f * c2 + e2, e * b2 + f * d2 + f2]) } fn apply(self, x: f64, y: f64) -> (f64, f64) { let [a, b, c, d, e, f] = self.0; (x * a + y * c + e, x * b + y * d + f) } fn of(operands: &[Object]) -> Option { if operands.len() < 6 { return None; } let mut m = [0.; 6]; for (at, operand) in operands.iter().take(6).enumerate() { m[at] = number(operand)?; } Some(Matrix(m)) } } fn number(object: &Object) -> Option { match object { Object::Integer(n) => Some(*n as f64), Object::Real(n) => Some(*n as f64), _ => None, } } fn numbers(operands: &[Object]) -> Option<[f64; N]> { let mut out = [0.; N]; for (at, slot) in out.iter_mut().enumerate() { *slot = number(operands.get(at)?)?; } Some(out) } /// A font as the reader needs it: how its bytes split into codes, what each code says, how wide it is. struct Font { /// Two-byte codes (a CID font). two_byte: bool, /// Code → text, from the ToUnicode map. unicode: HashMap, /// Byte → text from a simple font's encoding, where the map says nothing. table: Vec, /// Code → width in thousandths of the size (glyph space × 1000). widths: HashMap, default_width: f64, /// Glyph space to text space (0.001, or a Type 3 font's matrix). scale: f64, } impl Font { fn codes(&self, bytes: &[u8]) -> Vec { if self.two_byte { bytes.chunks(2).map(|pair| pair.iter().fold(0u32, |code, byte| code * 256 + *byte as u32)).collect() } else { bytes.iter().map(|byte| *byte as u32).collect() } } fn text(&self, code: u32) -> String { if let Some(text) = self.unicode.get(&code) { return text.clone(); } self.table.get(code as usize).cloned().unwrap_or_default() } /// The advance in text space per unit of size. fn width(&self, code: u32) -> f64 { self.widths.get(&code).copied().unwrap_or(self.default_width) * self.scale } } /// Helvetica's widths for printable ASCII (the standard metrics): an /// unembedded base font with no `Widths` is advanced by these. const HELVETICA: [u16; 95] = [ 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, ]; struct Reader<'a> { document: &'a Document, fonts: HashMap>, } /// The graphics state the text needs. #[derive(Clone)] struct State { ctm: Matrix, font: Option>, size: f64, char_spacing: f64, word_spacing: f64, scale: f64, leading: f64, rise: f64, } /// A page's drawing, being read. struct Page { glyphs: Vec, /// Page space to top-down points: the media box's origin, flipped. flip: Matrix, } const DEPTH: usize = 8; impl<'a> Reader<'a> { fn page(&mut self, page_id: ObjectId) -> Option> { let page = self.document.get_dictionary(page_id).ok()?; let media = self.inherited(page, b"MediaBox").and_then(|object| self.rect(object)).unwrap_or([0., 0., 595., 842.]); let rotate = self.inherited(page, b"Rotate").and_then(number).unwrap_or(0.0).rem_euclid(360.0) as i64; let (w, h) = (media[2] - media[0], media[3] - media[1]); // Page space → the page as seen (rotated clockwise by /Rotate), then y from the top. let to_origin = Matrix::translate(-media[0], -media[1]); let rotated = match rotate { 90 => Matrix([0., -1., 1., 0., 0., w]), 180 => Matrix([-1., 0., 0., -1., w, h]), 270 => Matrix([0., 1., -1., 0., h, 0.]), _ => Matrix::IDENTITY, }; let seen_height = if rotate == 90 || rotate == 270 { w } else { h }; let flip = to_origin.then(rotated).then(Matrix([1., 0., 0., -1., 0., seen_height])); let content = self.document.get_page_content(page_id).ok()?; let resources = self.page_resources(page_id); let mut out = Page { glyphs: Vec::new(), flip }; let state = State { ctm: Matrix::IDENTITY, font: None, size: 0.0, char_spacing: 0.0, word_spacing: 0.0, scale: 1.0, leading: 0.0, rise: 0.0 }; if !content.is_empty() { let operations = lopdf::content::Content::decode(&content).ok()?.operations; self.run(&operations, &resources, state, &mut out, 0); } Some(dedupe(out.glyphs)) } fn inherited(&self, page: &'a Dictionary, key: &[u8]) -> Option<&'a Object> { let mut node = page; for _ in 0..32 { if let Ok(object) = node.get(key) { return self.resolve(object); } node = node.get(b"Parent").ok().and_then(|parent| self.resolve(parent)).and_then(|parent| parent.as_dict().ok())?; } None } fn resolve(&self, object: &'a Object) -> Option<&'a Object> { let mut object = object; for _ in 0..16 { match object { Object::Reference(id) => object = self.document.get_object(*id).ok()?, _ => return Some(object), } } None } fn dict(&self, object: &'a Object) -> Option<&'a Dictionary> { match self.resolve(object)? { Object::Dictionary(dict) => Some(dict), Object::Stream(stream) => Some(&stream.dict), _ => None, } } fn rect(&self, object: &Object) -> Option<[f64; 4]> { let array = object.as_array().ok()?; let mut out = [0.; 4]; for (at, slot) in out.iter_mut().enumerate() { *slot = number(self.resolve(array.get(at)?)?)?; } Some([out[0].min(out[2]), out[1].min(out[3]), out[0].max(out[2]), out[1].max(out[3])]) } /// The page's resources, inherited ones merged under its own. fn page_resources(&self, page_id: ObjectId) -> Dictionary { let mut merged = Dictionary::new(); if let Ok((own, ids)) = self.document.get_page_resources(page_id) { let mut all: Vec<&Dictionary> = own.into_iter().collect(); all.extend(ids.iter().filter_map(|id| self.document.get_dictionary(*id).ok())); for dict in all { for (key, value) in dict.iter() { if !merged.has(key) { merged.set(key.clone(), value.clone()); } } } } merged } fn resource(&self, resources: &'a Dictionary, kind: &[u8], name: &[u8]) -> Option<(&'a Object, Option)> { let group = self.dict(resources.get(kind).ok()?)?; let entry = group.get(name).ok()?; let id = entry.as_reference().ok(); Some((self.resolve(entry)?, id)) } fn font(&mut self, resources: &Dictionary, name: &[u8]) -> Option> { let group = self.dict(resources.get(b"Font").ok()?)?; let entry = group.get(name).ok()?; let id = entry.as_reference().ok(); if let Some(font) = id.and_then(|id| self.fonts.get(&id)) { return Some(font.clone()); } let dict = self.dict(entry)?; let font = std::rc::Rc::new(self.read_font(dict)); if let Some(id) = id { self.fonts.insert(id, font.clone()); } Some(font) } fn read_font(&self, dict: &Dictionary) -> Font { let subtype = dict.get(b"Subtype").and_then(Object::as_name).unwrap_or(b""); let two_byte = subtype == b"Type0"; let unicode = dict .get(b"ToUnicode") .ok() .and_then(|object| self.resolve(object)) .and_then(|object| object.as_stream().ok()) .and_then(|stream| stream.decompressed_content().ok().or_else(|| stream.dict.get(b"Filter").is_err().then(|| stream.content.clone()))) .map(|bytes| to_unicode(&bytes)) .unwrap_or_default(); let mut table = Vec::new(); if !two_byte { let mut only = Dictionary::new(); only.set("Type", Object::Name(b"Font".to_vec())); let symbolic = dict.get(b"BaseFont").and_then(Object::as_name).is_ok_and(|name| name.windows(6).any(|w| w == b"Symbol") || name.windows(4).any(|w| w == b"Ding")); match dict.get(b"Encoding") { Ok(object) => only.set("Encoding", object.clone()), Err(_) if !symbolic => only.set("Encoding", Object::Name(b"WinAnsiEncoding".to_vec())), Err(_) => {} } if let Ok(encoding) = only.get_font_encoding(self.document) { table = (0..=255u8).map(|byte| encoding.bytes_to_string(&[byte]).unwrap_or_default().chars().filter(|c| *c != '\0' && *c != '\u{FFFD}').collect()).collect(); } } let mut widths = HashMap::new(); let mut default_width = 500.0; let mut scale = 0.001; if two_byte { default_width = 1000.0; if let Some(descendant) = dict.get(b"DescendantFonts").ok().and_then(|object| self.resolve(object)).and_then(|object| object.as_array().ok()).and_then(|array| array.first()).and_then(|object| self.dict(object)) { if let Some(dw) = descendant.get(b"DW").ok().and_then(|object| self.resolve(object)).and_then(number) { default_width = dw; } if let Some(w) = descendant.get(b"W").ok().and_then(|object| self.resolve(object)).and_then(|object| object.as_array().ok()) { let mut at = 0; while at < w.len() { let Some(first) = self.resolve(&w[at]).and_then(number) else { break }; match w.get(at + 1).and_then(|object| self.resolve(object)) { Some(Object::Array(list)) => { for (n, width) in list.iter().enumerate() { if let Some(width) = self.resolve(width).and_then(number) { widths.insert(first as u32 + n as u32, width); } } at += 2; } Some(last) => { let (Some(last), Some(width)) = (number(last), w.get(at + 2).and_then(|object| self.resolve(object)).and_then(number)) else { break }; for code in first as u32..=(last as u32).min(first as u32 + 65535) { widths.insert(code, width); } at += 3; } None => break, } } } } } else { if subtype == b"Type3" { if let Some(a) = dict.get(b"FontMatrix").ok().and_then(|object| self.resolve(object)).and_then(|object| object.as_array().ok()).and_then(|array| array.first()).and_then(number) { scale = a; } } let first = dict.get(b"FirstChar").ok().and_then(|object| self.resolve(object)).and_then(number).unwrap_or(0.0) as u32; let listed = dict.get(b"Widths").ok().and_then(|object| self.resolve(object)).and_then(|object| object.as_array().ok()); if let Some(list) = listed { for (n, width) in list.iter().enumerate() { if let Some(width) = self.resolve(width).and_then(number) { widths.insert(first + n as u32, width); } } if let Some(missing) = dict.get(b"FontDescriptor").ok().and_then(|object| self.dict(object)).and_then(|descriptor| descriptor.get(b"MissingWidth").ok()).and_then(|object| self.resolve(object)).and_then(number) { default_width = missing; } } else { // An unembedded base font: the standard metrics, Helvetica's for every face. for (n, width) in HELVETICA.iter().enumerate() { widths.insert(32 + n as u32, *width as f64); } default_width = 556.0; } } Font { two_byte, unicode, table, widths, default_width, scale } } fn run(&mut self, operations: &[lopdf::content::Operation], resources: &Dictionary, mut state: State, out: &mut Page, depth: usize) { let mut stack: Vec = Vec::new(); let mut tm = Matrix::IDENTITY; let mut tlm = Matrix::IDENTITY; for operation in operations { let operands = &operation.operands; match operation.operator.as_str() { "q" => stack.push(state.clone()), "Q" => { if let Some(saved) = stack.pop() { state = saved; } } "cm" => { if let Some(m) = Matrix::of(operands) { state.ctm = m.then(state.ctm); } } "BT" => { tm = Matrix::IDENTITY; tlm = Matrix::IDENTITY; } "Tf" => { if let (Some(name), Some(size)) = (operands.first().and_then(|o| o.as_name().ok()), operands.get(1).and_then(number)) { state.font = self.font(resources, name); state.size = size; } } "Tc" => state.char_spacing = operands.first().and_then(number).unwrap_or(state.char_spacing), "Tw" => state.word_spacing = operands.first().and_then(number).unwrap_or(state.word_spacing), "Tz" => state.scale = operands.first().and_then(number).map(|n| n / 100.0).unwrap_or(state.scale), "TL" => state.leading = operands.first().and_then(number).unwrap_or(state.leading), "Ts" => state.rise = operands.first().and_then(number).unwrap_or(state.rise), "Td" => { if let Some([x, y]) = numbers::<2>(operands) { tlm = Matrix::translate(x, y).then(tlm); tm = tlm; } } "TD" => { if let Some([x, y]) = numbers::<2>(operands) { state.leading = -y; tlm = Matrix::translate(x, y).then(tlm); tm = tlm; } } "Tm" => { if let Some(m) = Matrix::of(operands) { tlm = m; tm = m; } } "T*" => { tlm = Matrix::translate(0., -state.leading).then(tlm); tm = tlm; } "Tj" => { if let Some(bytes) = operands.first().and_then(|o| o.as_str().ok()) { self.show(bytes, &state, &mut tm, out); } } "'" => { tlm = Matrix::translate(0., -state.leading).then(tlm); tm = tlm; if let Some(bytes) = operands.first().and_then(|o| o.as_str().ok()) { self.show(bytes, &state, &mut tm, out); } } "\"" => { if let (Some(aw), Some(ac)) = (operands.first().and_then(number), operands.get(1).and_then(number)) { state.word_spacing = aw; state.char_spacing = ac; } tlm = Matrix::translate(0., -state.leading).then(tlm); tm = tlm; if let Some(bytes) = operands.get(2).and_then(|o| o.as_str().ok()) { self.show(bytes, &state, &mut tm, out); } } "TJ" => { if let Some(items) = operands.first().and_then(|o| o.as_array().ok()) { for item in items { match item { Object::String(bytes, _) => self.show(bytes, &state, &mut tm, out), other => { if let Some(adjust) = number(other) { let tx = -adjust / 1000.0 * state.size * state.scale; tm = Matrix::translate(tx, 0.).then(tm); } } } } } } "Do" if depth < DEPTH => { let Some(name) = operands.first().and_then(|o| o.as_name().ok()) else { continue }; let Some((Object::Stream(stream), _)) = self.resource(resources, b"XObject", name) else { continue }; if stream.dict.get(b"Subtype").and_then(Object::as_name).ok() != Some(b"Form".as_slice()) { continue; } let matrix = stream.dict.get(b"Matrix").ok().and_then(|object| self.resolve(object)).and_then(|object| object.as_array().ok()).and_then(|array| Matrix::of(array)).unwrap_or(Matrix::IDENTITY); let own = stream.dict.get(b"Resources").ok().and_then(|object| self.dict(object)).cloned(); let Ok(content) = stream.decompressed_content().or_else(|_| Ok::<_, lopdf::Error>(stream.content.clone())) else { continue }; let Ok(decoded) = lopdf::content::Content::decode(&content) else { continue }; let mut inner = state.clone(); inner.ctm = matrix.then(state.ctm); let inner_resources = own.unwrap_or_else(|| resources.clone()); self.run(&decoded.operations, &inner_resources, inner, out, depth + 1); } _ => {} } } } /// Show a string: each code a glyph where the text matrix stands, then advance. fn show(&self, bytes: &[u8], state: &State, tm: &mut Matrix, out: &mut Page) { let Some(font) = state.font.as_ref() else { return }; for code in font.codes(bytes) { let text = font.text(code); let w0 = font.width(code); // Text space → device: size and scale, rise, the text matrix, the CTM, then the page's flip. let trm = Matrix([state.size * state.scale, 0., 0., state.size, 0., state.rise]).then(*tm).then(state.ctm).then(out.flip); let [a, b, c, d, e, f] = trm.0; let advance = w0 * state.size + state.char_spacing + if !font.two_byte && code == 32 { state.word_spacing } else { 0.0 }; // Left to right on the page: the baseline runs along +x (flipped space keeps x). let horizontal = a > 0.0 && b.abs() <= a * 0.05; if horizontal && !text.is_empty() { let size = (c * c + d * d).sqrt(); let (x1, _) = Matrix::translate(w0, 0.).then(Matrix([state.size * state.scale, 0., 0., state.size, 0., state.rise])).then(*tm).then(state.ctm).then(out.flip).apply(0., 0.); let width = (x1 - e).max(0.0); if size > 0.0 && e.is_finite() && f.is_finite() { out.glyphs.push(Glyph { x: e as f32, y: f as f32, width: width as f32, size: size as f32, text }); } } *tm = Matrix::translate(advance * state.scale, 0.).then(*tm); } } } /// A glyph drawn twice in one place (a generator's fake bold) kept once. fn dedupe(glyphs: Vec) -> Vec { let mut out: Vec = Vec::with_capacity(glyphs.len()); for glyph in glyphs { let twin = out.iter().rev().take(64).any(|kept| kept.text == glyph.text && (kept.x - glyph.x).abs() < 0.5 && (kept.y - glyph.y).abs() < 0.5); if !twin { out.push(glyph); } } out } /// A ToUnicode CMap read for its `bfchar` and `bfrange` mappings, whatever /// else it says or omits (a generator's CMap rarely keeps to the letter). pub fn to_unicode(bytes: &[u8]) -> HashMap { #[derive(Debug, PartialEq)] enum Token { Hex(Vec), Open, Close, Word(String), } let mut tokens = Vec::new(); let mut at = 0; while at < bytes.len() { match bytes[at] { b'<' if bytes.get(at + 1) != Some(&b'<') => { let end = bytes[at..].iter().position(|b| *b == b'>').map(|n| at + n).unwrap_or(bytes.len()); let digits: Vec = bytes[at + 1..end].iter().copied().filter(u8::is_ascii_hexdigit).collect(); let mut hex = Vec::new(); for pair in digits.chunks(2) { let text = std::str::from_utf8(pair).unwrap_or("0"); let value = u8::from_str_radix(text, 16).unwrap_or(0); hex.push(if pair.len() == 1 { value << 4 } else { value }); } tokens.push(Token::Hex(hex)); at = end + 1; } b'[' => { tokens.push(Token::Open); at += 1; } b']' => { tokens.push(Token::Close); at += 1; } b'%' => { while at < bytes.len() && bytes[at] != b'\n' && bytes[at] != b'\r' { at += 1; } } byte if byte.is_ascii_whitespace() => at += 1, _ => { let end = bytes[at..].iter().position(|b| b.is_ascii_whitespace() || matches!(b, b'<' | b'[' | b']' | b'%')).map(|n| at + n).unwrap_or(bytes.len()); let end = end.max(at + 1); tokens.push(Token::Word(String::from_utf8_lossy(&bytes[at..end]).into_owned())); at = end; } } } let code = |hex: &[u8]| hex.iter().fold(0u32, |code, byte| code.wrapping_mul(256) | *byte as u32); let text = |hex: &[u8]| { let units: Vec = hex.chunks(2).map(|pair| if pair.len() == 2 { u16::from_be_bytes([pair[0], pair[1]]) } else { pair[0] as u16 }).collect(); char::decode_utf16(units).filter_map(Result::ok).filter(|c| *c != '\0').collect::() }; let mut map = HashMap::new(); let mut at = 0; let mut section = ""; while at < tokens.len() { match (&tokens[at], section) { (Token::Word(word), _) if word == "beginbfchar" || word == "beginbfrange" => { section = if word == "beginbfchar" { "char" } else { "range" }; at += 1; } (Token::Word(word), _) if word.starts_with("end") => { section = ""; at += 1; } (Token::Hex(source), "char") => { if let Some(Token::Hex(target)) = tokens.get(at + 1) { map.insert(code(source), text(target)); } at += 2; } (Token::Hex(low), "range") => { let (low, Some(Token::Hex(high))) = (code(low), tokens.get(at + 1)) else { at += 1; continue; }; let high = code(high).min(low.saturating_add(65535)); match tokens.get(at + 2) { Some(Token::Hex(start)) => { // The last unit counts up through the range. let mut units: Vec = start.chunks(2).map(|pair| if pair.len() == 2 { u16::from_be_bytes([pair[0], pair[1]]) } else { pair[0] as u16 }).collect(); for source in low..=high { map.insert(source, char::decode_utf16(units.iter().copied()).filter_map(Result::ok).filter(|c| *c != '\0').collect()); if let Some(last) = units.last_mut() { *last = last.wrapping_add(1); } } at += 3; } Some(Token::Open) => { let mut n = 0; at += 3; while let Some(Token::Hex(target)) = tokens.get(at) { if low + n <= high { map.insert(low + n, text(target)); } n += 1; at += 1; } at += 1; } _ => at += 2, } } _ => at += 1, } } map }