use crate::cmap::ToUnicode;
use crate::content::Content;
use crate::document::Document;
use crate::error::Result;
use crate::object::{Dictionary, Object};
use crate::page::Page;
use std::collections::BTreeMap;
const WIN_ANSI_HIGH: [char; 32] = [
'\u{20AC}', '\0', '\u{201A}', '\u{0192}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}', '\u{02C6}', '\u{2030}',
'\u{0160}', '\u{2039}', '\u{0152}', '\0', '\u{017D}', '\0', '\0', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}',
'\u{2022}', '\u{2013}', '\u{2014}', '\u{02DC}', '\u{2122}', '\u{0161}', '\u{203A}', '\u{0153}', '\0', '\u{017E}',
'\u{0178}',
];
const MAC_ROMAN_HIGH: &str = "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ\u{F8FF}ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ";
const GLYPH_NAMES: &[(&str, char)] = &[
("space", ' '), ("exclam", '!'), ("quotedbl", '"'), ("numbersign", '#'), ("dollar", '$'), ("percent", '%'),
("ampersand", '&'), ("quotesingle", '\''), ("parenleft", '('), ("parenright", ')'), ("asterisk", '*'),
("plus", '+'), ("comma", ','), ("hyphen", '-'), ("period", '.'), ("slash", '/'), ("zero", '0'), ("one", '1'),
("two", '2'), ("three", '3'), ("four", '4'), ("five", '5'), ("six", '6'), ("seven", '7'), ("eight", '8'),
("nine", '9'), ("colon", ':'), ("semicolon", ';'), ("less", '<'), ("equal", '='), ("greater", '>'),
("question", '?'), ("at", '@'), ("bracketleft", '['), ("backslash", '\\'), ("bracketright", ']'),
("asciicircum", '^'), ("underscore", '_'), ("grave", '`'), ("braceleft", '{'), ("bar", '|'),
("braceright", '}'), ("asciitilde", '~'), ("quoteright", '\u{2019}'), ("quoteleft", '\u{2018}'),
("quotedblleft", '\u{201C}'), ("quotedblright", '\u{201D}'), ("quotesinglbase", '\u{201A}'),
("quotedblbase", '\u{201E}'), ("endash", '\u{2013}'), ("emdash", '\u{2014}'), ("bullet", '\u{2022}'),
("ellipsis", '\u{2026}'), ("dagger", '\u{2020}'), ("daggerdbl", '\u{2021}'), ("trademark", '\u{2122}'),
("registered", '\u{00AE}'), ("copyright", '\u{00A9}'), ("degree", '\u{00B0}'), ("section", '\u{00A7}'),
("paragraph", '\u{00B6}'), ("fi", '\u{FB01}'), ("fl", '\u{FB02}'), ("ff", '\u{FB00}'), ("ffi", '\u{FB03}'),
("ffl", '\u{FB04}'), ("Euro", '\u{20AC}'), ("sterling", '\u{00A3}'), ("yen", '\u{00A5}'), ("cent", '\u{00A2}'),
("florin", '\u{0192}'), ("minus", '\u{2212}'), ("multiply", '\u{00D7}'), ("divide", '\u{00F7}'),
("plusminus", '\u{00B1}'), ("onehalf", '\u{00BD}'), ("onequarter", '\u{00BC}'), ("threequarters", '\u{00BE}'),
("guillemotleft", '\u{00AB}'), ("guillemotright", '\u{00BB}'), ("guilsinglleft", '\u{2039}'),
("guilsinglright", '\u{203A}'), ("exclamdown", '\u{00A1}'), ("questiondown", '\u{00BF}'),
("germandbls", '\u{00DF}'), ("ae", '\u{00E6}'), ("AE", '\u{00C6}'), ("oe", '\u{0153}'), ("OE", '\u{0152}'),
("oslash", '\u{00F8}'), ("Oslash", '\u{00D8}'), ("dotlessi", '\u{0131}'), ("lslash", '\u{0142}'),
("Lslash", '\u{0141}'), ("nbspace", '\u{00A0}'), ("periodcentered", '\u{00B7}'), ("perthousand", '\u{2030}'),
("mu", '\u{00B5}'), ("ordfeminine", '\u{00AA}'), ("ordmasculine", '\u{00BA}'), ("currency", '\u{00A4}'),
("brokenbar", '\u{00A6}'), ("dieresis", '\u{00A8}'), ("macron", '\u{00AF}'), ("acute", '\u{00B4}'),
("cedilla", '\u{00B8}'), ("logicalnot", '\u{00AC}'), ("uni00A0", '\u{00A0}'),
];
const ACCENTS: &[(&str, [char; 2])] = &[
("acute", ['\u{0301}', '\0']),
("grave", ['\u{0300}', '\0']),
("circumflex", ['\u{0302}', '\0']),
("dieresis", ['\u{0308}', '\0']),
("tilde", ['\u{0303}', '\0']),
("ring", ['\u{030A}', '\0']),
("cedilla", ['\u{0327}', '\0']),
("caron", ['\u{030C}', '\0']),
];
fn glyph_unicode(name: &[u8]) -> Option<String> {
let name = std::str::from_utf8(name).ok()?;
let name = name.split('.').next()?;
if name.len() == 1 && name.as_bytes()[0].is_ascii_alphabetic() {
return Some(name.to_owned());
}
if let Some((_, c)) = GLYPH_NAMES.iter().find(|(n, _)| *n == name) {
return Some(c.to_string());
}
let hex_run = |s: &str, width: usize| -> Option<String> {
if s.is_empty() || !s.len().is_multiple_of(width) {
return None;
}
(0..s.len())
.step_by(width)
.map(|i| u32::from_str_radix(&s[i..i + width], 16).ok().and_then(char::from_u32))
.collect()
};
if let Some(rest) = name.strip_prefix("uni") {
return hex_run(rest, 4);
}
if let Some(rest) = name.strip_prefix('u') {
if (4..=6).contains(&rest.len()) {
return u32::from_str_radix(rest, 16).ok().and_then(char::from_u32).map(String::from);
}
}
for (accent, marks) in ACCENTS {
if let Some(base) = name.strip_suffix(accent) {
if base.len() == 1 && base.as_bytes()[0].is_ascii_alphabetic() {
let decomposed: String = std::iter::once(base.chars().next()?).chain(marks.iter().copied().filter(|c| *c != '\0')).collect();
return Some(compose(&decomposed));
}
}
}
None
}
fn compose(s: &str) -> String {
const TABLE: &[(char, char, char)] = &[
('a', '\u{0301}', 'á'), ('e', '\u{0301}', 'é'), ('i', '\u{0301}', 'í'), ('o', '\u{0301}', 'ó'), ('u', '\u{0301}', 'ú'),
('y', '\u{0301}', 'ý'), ('A', '\u{0301}', 'Á'), ('E', '\u{0301}', 'É'), ('I', '\u{0301}', 'Í'), ('O', '\u{0301}', 'Ó'),
('U', '\u{0301}', 'Ú'), ('Y', '\u{0301}', 'Ý'), ('a', '\u{0300}', 'à'), ('e', '\u{0300}', 'è'), ('i', '\u{0300}', 'ì'),
('o', '\u{0300}', 'ò'), ('u', '\u{0300}', 'ù'), ('A', '\u{0300}', 'À'), ('E', '\u{0300}', 'È'), ('I', '\u{0300}', 'Ì'),
('O', '\u{0300}', 'Ò'), ('U', '\u{0300}', 'Ù'), ('a', '\u{0302}', 'â'), ('e', '\u{0302}', 'ê'), ('i', '\u{0302}', 'î'),
('o', '\u{0302}', 'ô'), ('u', '\u{0302}', 'û'), ('A', '\u{0302}', 'Â'), ('E', '\u{0302}', 'Ê'), ('I', '\u{0302}', 'Î'),
('O', '\u{0302}', 'Ô'), ('U', '\u{0302}', 'Û'), ('a', '\u{0308}', 'ä'), ('e', '\u{0308}', 'ë'), ('i', '\u{0308}', 'ï'),
('o', '\u{0308}', 'ö'), ('u', '\u{0308}', 'ü'), ('y', '\u{0308}', 'ÿ'), ('A', '\u{0308}', 'Ä'), ('E', '\u{0308}', 'Ë'),
('I', '\u{0308}', 'Ï'), ('O', '\u{0308}', 'Ö'), ('U', '\u{0308}', 'Ü'), ('Y', '\u{0308}', 'Ÿ'), ('a', '\u{0303}', 'ã'),
('n', '\u{0303}', 'ñ'), ('o', '\u{0303}', 'õ'), ('A', '\u{0303}', 'Ã'), ('N', '\u{0303}', 'Ñ'), ('O', '\u{0303}', 'Õ'),
('a', '\u{030A}', 'å'), ('A', '\u{030A}', 'Å'), ('c', '\u{0327}', 'ç'), ('C', '\u{0327}', 'Ç'), ('s', '\u{030C}', 'š'),
('S', '\u{030C}', 'Š'), ('z', '\u{030C}', 'ž'), ('Z', '\u{030C}', 'Ž'),
];
let mut chars = s.chars();
if let (Some(base), Some(mark), None) = (chars.next(), chars.next(), chars.next()) {
if let Some((_, _, c)) = TABLE.iter().find(|(b, m, _)| *b == base && *m == mark) {
return c.to_string();
}
}
s.to_owned()
}
fn base_encoding(name: &[u8], b: u8) -> Option<char> {
match name {
b"MacRomanEncoding" if b >= 0x80 => MAC_ROMAN_HIGH.chars().nth(usize::from(b - 0x80)),
b"StandardEncoding" => match b {
0x27 => Some('\u{2019}'),
0x60 => Some('\u{2018}'),
0x20..=0x7E => Some(char::from(b)),
_ => None,
},
_ => match b {
0x80..=0x9F => Some(WIN_ANSI_HIGH[usize::from(b - 0x80)]).filter(|c| *c != '\0'),
0xAD => Some('-'),
0x20..=0x7E | 0xA0..=0xFF => Some(char::from(b)),
_ => None,
},
}
}
#[derive(Debug, Clone, Default)]
struct FontText {
to_unicode: Option<ToUnicode>,
composite: bool,
base: Vec<u8>,
differences: BTreeMap<u8, String>,
}
impl FontText {
fn new(doc: &Document, font: &Dictionary) -> Self {
let mut out = Self {
composite: font.get_name(b"Subtype") == Some(b"Type0"),
base: b"WinAnsiEncoding".to_vec(),
..Self::default()
};
if let Ok(Object::Stream(s)) = doc.lookup(font, b"ToUnicode") {
if let Ok(data) = doc.decode_stream(s, 4 << 20) {
let map = ToUnicode::parse(&data);
if !map.is_empty() {
out.to_unicode = Some(map);
}
}
}
match doc.lookup(font, b"Encoding") {
Ok(Object::Name(n)) => out.base.clone_from(n),
Ok(Object::Dictionary(enc)) => {
if let Some(n) = enc.get_name(b"BaseEncoding") {
out.base = n.to_vec();
}
if let Ok(Object::Array(diffs)) = doc.lookup(enc, b"Differences") {
let mut code: Option<u8> = None;
for item in diffs {
match doc.resolve(item) {
Ok(Object::Integer(i)) => code = u8::try_from(*i).ok(),
Ok(Object::Name(name)) => {
if let Some(c) = code {
if let Some(text) = glyph_unicode(name) {
out.differences.insert(c, text);
}
code = c.checked_add(1);
}
}
_ => {}
}
}
}
}
_ => {}
}
out
}
fn decode(&self, bytes: &[u8], out: &mut String) {
if let Some(map) = &self.to_unicode {
let mut i = 0;
while i < bytes.len() {
let n = if self.composite { map.code_length(&bytes[i..]).max(2).min(bytes.len() - i) } else { 1 };
let code = bytes[i..i + n].iter().fold(0u32, |a, b| a << 8 | u32::from(*b));
if let Some(text) = map.lookup(n, code) {
out.push_str(&text);
} else if !self.composite {
self.decode_simple(bytes[i], out);
}
i += n;
}
return;
}
if self.composite {
return;
}
for b in bytes {
self.decode_simple(*b, out);
}
}
fn decode_simple(&self, b: u8, out: &mut String) {
if let Some(text) = self.differences.get(&b) {
out.push_str(text);
} else if let Some(c) = base_encoding(&self.base, b) {
out.push(c);
}
}
}
impl Page<'_> {
pub fn extract_text(&self, max: usize) -> Result<String> {
let doc = self.document();
let data = self.content(max)?;
let content = Content::parse_with(&data, doc.limits())?;
let fonts = self.resources().and_then(|r| doc.lookup_dict(r, b"Font"));
let mut cache: BTreeMap<Vec<u8>, FontText> = BTreeMap::new();
let mut current: Option<Vec<u8>> = None;
let mut out = String::new();
let newline = |out: &mut String| {
if !out.is_empty() && !out.ends_with('\n') {
out.push('\n');
}
};
for op in &content.operations {
match op.operator.as_str() {
"Tf" => {
if let Some(Object::Name(name)) = op.operands.first() {
if !cache.contains_key(name) {
let font = fonts
.and_then(|f| f.get(name))
.and_then(|f| doc.resolve(f).ok())
.and_then(|f| f.as_dict().ok());
let text = font.map(|f| FontText::new(doc, f)).unwrap_or_default();
cache.insert(name.clone(), text);
}
current = Some(name.clone());
}
}
"T*" => newline(&mut out),
"Td" | "TD" => {
let ty = op.operands.get(1).and_then(|o| o.as_f64().ok()).unwrap_or(0.0);
if ty.abs() > f64::EPSILON {
newline(&mut out);
}
}
"ET" => newline(&mut out),
"Tj" | "'" | "\"" | "TJ" => {
if matches!(op.operator.as_str(), "'" | "\"") {
newline(&mut out);
}
let font = current.as_ref().and_then(|n| cache.get(n));
let Some(font) = font else { continue };
match op.operands.last() {
Some(Object::String(s, _)) => font.decode(s, &mut out),
Some(Object::Array(items)) => {
for item in items {
match item {
Object::String(s, _) => font.decode(s, &mut out),
other => {
if other.as_f64().is_ok_and(|v| v < -250.0) && !out.ends_with(' ') {
out.push(' ');
}
}
}
}
}
_ => {}
}
}
_ => {}
}
}
while out.ends_with('\n') {
out.pop();
}
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn glyph_names() {
assert_eq!(glyph_unicode(b"A").as_deref(), Some("A"));
assert_eq!(glyph_unicode(b"eacute").as_deref(), Some("é"));
assert_eq!(glyph_unicode(b"Udieresis").as_deref(), Some("Ü"));
assert_eq!(glyph_unicode(b"uni00410042").as_deref(), Some("AB"));
assert_eq!(glyph_unicode(b"u1F600").as_deref(), Some("\u{1F600}"));
assert_eq!(glyph_unicode(b"one.oldstyle").as_deref(), Some("1"));
assert_eq!(glyph_unicode(b"fi").as_deref(), Some("\u{FB01}"));
assert_eq!(glyph_unicode(b"g123"), None);
}
#[test]
fn base_encodings() {
assert_eq!(base_encoding(b"WinAnsiEncoding", 0x93), Some('\u{201C}'));
assert_eq!(base_encoding(b"WinAnsiEncoding", 0xE9), Some('é'));
assert_eq!(base_encoding(b"MacRomanEncoding", 0x8E), Some('é'));
assert_eq!(base_encoding(b"MacRomanEncoding", 0xFF), Some('ˇ'));
assert_eq!(MAC_ROMAN_HIGH.chars().count(), 128);
assert_eq!(base_encoding(b"StandardEncoding", 0x27), Some('\u{2019}'));
}
}