1use std::collections::{HashMap, HashSet};
17use std::sync::Arc;
18
19use lopdf::{Dictionary, Document, Object};
20
21use crate::pdfium_backend::Glyph;
22use crate::tounicode::parse_tounicode;
23
24#[derive(Default)]
33struct DocCaches {
34 fonts: HashMap<(lopdf::ObjectId, Vec<u8>), Arc<Font>>,
35 forms: HashMap<lopdf::ObjectId, Arc<lopdf::content::Content>>,
36 forms_seen: HashSet<lopdf::ObjectId>,
46}
47
48#[derive(Clone, Copy)]
50struct Mat {
51 a: f64,
52 b: f64,
53 c: f64,
54 d: f64,
55 e: f64,
56 f: f64,
57}
58
59impl Mat {
60 const ID: Mat = Mat {
61 a: 1.0,
62 b: 0.0,
63 c: 0.0,
64 d: 1.0,
65 e: 0.0,
66 f: 0.0,
67 };
68
69 fn then(self, m: Mat) -> Mat {
71 Mat {
72 a: self.a * m.a + self.b * m.c,
73 b: self.a * m.b + self.b * m.d,
74 c: self.c * m.a + self.d * m.c,
75 d: self.c * m.b + self.d * m.d,
76 e: self.e * m.a + self.f * m.c + m.e,
77 f: self.e * m.b + self.f * m.d + m.f,
78 }
79 }
80
81 fn apply(self, x: f64, y: f64) -> (f64, f64) {
82 (
83 self.a * x + self.c * y + self.e,
84 self.b * x + self.d * y + self.f,
85 )
86 }
87}
88
89struct Font {
91 two_byte: bool,
93 to_unicode: HashMap<u32, String>,
95 cid_fallback: CidFallback,
97 widths: HashMap<u32, f64>,
99 default_width: f64,
100 simple_encoding: Option<HashMap<u8, char>>,
102 fallback_names: HashMap<u8, String>,
106 blank_codes: HashSet<u32>,
110 program_encoding: HashMap<u8, char>,
114 builtin: HashMap<u8, String>,
122 diff_codes: HashSet<u8>,
124 ascent: f64,
125 descent: f64,
126 ink_y: HashMap<u32, (f64, f64)>,
134 hash: u64,
135 math: bool,
139 style: crate::font_style::FontStyle,
142}
143
144impl Font {
145 fn decode_code(&self, code: u32) -> (Option<String>, f64, bool) {
155 let w = self
156 .widths
157 .get(&code)
158 .copied()
159 .unwrap_or(self.default_width);
160 if let Some(s) = self.to_unicode.get(&code) {
161 return (Some(decompose_ligatures(s)), w, false);
162 }
163 let unmapped = |font: &Font| {
164 let blank = font.blank_codes.contains(&code);
165 (
166 Some(if blank { " " } else { "\u{FFFD}" }.to_string()),
167 w,
168 blank,
169 )
170 };
171 if !self.two_byte {
172 if let Some(name) = self.fallback_names.get(&(code as u8)) {
177 return match unknown_name_text(name) {
178 Some(text) => (Some(text), w, false),
179 None => unmapped(self),
180 };
181 }
182 if !self.diff_codes.contains(&(code as u8)) {
187 if let Some(text) = self.builtin.get(&(code as u8)) {
188 return (Some(decompose_ligatures(text)), w, false);
189 }
190 }
191 if let Some(enc) = &self.simple_encoding {
192 if let Some(&ch) = enc.get(&(code as u8)) {
193 return (Some(decompose_ligatures(&ch.to_string())), w, false);
194 }
195 }
196 if let Some(&ch) = self.program_encoding.get(&(code as u8)) {
204 return (Some(decompose_ligatures(&ch.to_string())), w, false);
205 }
206 } else {
207 match self.cid_fallback {
208 CidFallback::None => {}
209 CidFallback::UnicodeCodes { .. } => {
210 if let Some(ch) = unicode_cmap_char(code).filter(|c| !c.is_control()) {
211 return (Some(ch.to_string()), w, false);
212 }
213 }
214 CidFallback::Collection(table) => {
215 if let Some(s) = collection_text(table, code) {
216 return (Some(decompose_ligatures(&s)), w, false);
217 }
218 }
219 }
220 }
221 unmapped(self)
222 }
223}
224
225fn decompose_ligatures(s: &str) -> String {
229 if !s.chars().any(|c| ('\u{FB00}'..='\u{FB06}').contains(&c)) {
230 return s.to_string();
231 }
232 s.chars()
233 .map(|c| {
234 match c {
235 '\u{FB00}' => "ff",
236 '\u{FB01}' => "fi",
237 '\u{FB02}' => "fl",
238 '\u{FB03}' => "ffi",
239 '\u{FB04}' => "ffl",
240 '\u{FB05}' => "st",
243 '\u{FB06}' => "st",
244 _ => return c.to_string(),
245 }
246 .to_string()
247 })
248 .collect()
249}
250
251fn hash_name(name: &[u8]) -> u64 {
252 use std::hash::{Hash, Hasher};
253 let mut h = std::collections::hash_map::DefaultHasher::new();
254 name.hash(&mut h);
255 h.finish()
256}
257
258fn as_dict<'a>(doc: &'a Document, obj: &'a Object) -> Option<&'a Dictionary> {
260 match obj {
261 Object::Dictionary(d) => Some(d),
262 Object::Reference(id) => doc.get_object(*id).ok().and_then(|o| o.as_dict().ok()),
263 _ => None,
264 }
265}
266
267fn deref<'a>(doc: &'a Document, obj: &'a Object) -> Option<&'a Object> {
268 match obj {
269 Object::Reference(id) => doc.get_object(*id).ok(),
270 other => Some(other),
271 }
272}
273
274fn is_math_font_name(name: &[u8]) -> bool {
290 let lower = name.to_ascii_lowercase();
291 [
292 "cmmi", "cmsy", "cmex", "cmr", "cmbx", "msam", "msbm", "math", "symbol", "mtextra",
293 ]
294 .iter()
295 .any(|t| lower.windows(t.len()).any(|w| w == t.as_bytes()))
296}
297
298fn sanitizer_font_name(doc: &Document, fdict: &Dictionary, two_byte: bool) -> Vec<u8> {
299 let descriptor_font_name = |owner: &Dictionary| {
300 owner
301 .get(b"FontDescriptor")
302 .ok()
303 .and_then(|o| as_dict(doc, o))
304 .and_then(|fd| fd.get(b"FontName").ok())
305 .and_then(|o| deref(doc, o))
306 .and_then(|o| o.as_name().ok().map(<[u8]>::to_vec))
307 };
308 if let Some(n) = descriptor_font_name(fdict) {
309 return n;
310 }
311 if two_byte {
312 let descendant = fdict
313 .get(b"DescendantFonts")
314 .ok()
315 .and_then(|o| deref(doc, o))
316 .and_then(|o| match o {
317 Object::Array(a) => a.first(),
318 _ => None,
319 })
320 .and_then(|o| as_dict(doc, o));
321 if let Some(n) = descendant.and_then(descriptor_font_name) {
322 return n;
323 }
324 }
325 if let Some(n) = fdict
326 .get(b"Name")
327 .ok()
328 .and_then(|o| deref(doc, o))
329 .and_then(|o| o.as_name().ok())
330 {
331 return n.to_vec();
332 }
333 if let Some(n) = fdict.get(b"BaseFont").ok().and_then(|o| o.as_name().ok()) {
336 return n.to_vec();
337 }
338 b"null".to_vec()
339}
340
341fn parse_font(doc: &Document, name: &[u8], fdict: &Dictionary) -> Font {
343 let subtype: &[u8] = fdict
344 .get(b"Subtype")
345 .ok()
346 .and_then(|o| o.as_name().ok())
347 .unwrap_or(&[]);
348 let two_byte = subtype == b"Type0".as_slice();
349
350 let mut to_unicode = fdict
351 .get(b"ToUnicode")
352 .ok()
353 .and_then(|o| deref(doc, o))
354 .and_then(|o| o.as_stream().ok())
355 .and_then(|s| s.decompressed_content().ok())
356 .map(|data| parse_tounicode(&data))
357 .unwrap_or_default();
358 if !two_byte {
359 if let Some(diffs) = differences_array(doc, fdict) {
360 reconcile_stale_tounicode(&mut to_unicode, &diffs);
361 }
362 }
363 let sanitizer_name = sanitizer_font_name(doc, fdict, two_byte);
364 let raw_base = fdict.get(b"BaseFont").ok().and_then(|o| o.as_name().ok());
369 let names: Vec<&[u8]> = std::iter::once(sanitizer_name.as_slice())
370 .chain(raw_base)
371 .collect();
372 if let Some(face) = crate::symbol_fonts::symbol_face(&names) {
373 for value in to_unicode.values_mut() {
374 if let Some(ch) = crate::symbol_fonts::fold_private_use(face, value) {
375 *value = ch.to_string();
376 }
377 }
378 }
379
380 let cid_fallback = if two_byte {
381 cid_fallback(doc, fdict)
382 } else {
383 CidFallback::None
384 };
385
386 let (mut widths, mut default_width) = if two_byte {
387 cid_widths(doc, fdict)
388 } else {
389 simple_widths(doc, fdict)
390 };
391
392 let simple_encoding = if two_byte {
393 None
394 } else {
395 Some(simple_encoding_table(doc, fdict))
396 };
397
398 if !two_byte && widths.is_empty() && default_width == 0.0 {
406 if let Some(std14) = base_font_name(fdict).and_then(|n| crate::std14::widths_for(&n)) {
407 if let Some(enc) = &simple_encoding {
408 for (&code, &ch) in enc {
409 if let Some(w) = std14.width(ch) {
410 widths.insert(u32::from(code), w);
411 }
412 }
413 }
414 default_width = 500.0;
417 } else if let Some(face) = crate::symbol_fonts::symbol_face(&[base_font_name(fdict)
418 .as_deref()
419 .unwrap_or_default()])
420 {
421 for code in 0..=255u8 {
424 if let Some(w) = crate::symbol_fonts::face_width(face, code) {
425 widths.insert(u32::from(code), w);
426 }
427 }
428 default_width = 500.0;
429 } else {
430 default_width = fdict
438 .get(b"FontDescriptor")
439 .ok()
440 .and_then(|o| as_dict(doc, o))
441 .and_then(|d| d.get(b"AvgWidth").ok())
442 .and_then(num)
443 .filter(|w| *w > 0.0)
444 .unwrap_or(500.0);
445 }
446 }
447 let fallback_names = if two_byte {
448 HashMap::new()
449 } else {
450 differences_gid_names(doc, fdict)
451 };
452 let program_encoding = if two_byte {
453 HashMap::new()
454 } else {
455 type1_program_encoding(doc, fdict)
456 };
457
458 let (ascent, descent, ink_boxes) = font_ascent_descent(doc, fdict, two_byte);
459 let mut font = Font {
460 two_byte,
461 to_unicode,
462 cid_fallback,
463 widths,
464 default_width,
465 simple_encoding,
466 fallback_names,
467 blank_codes: HashSet::new(),
468 program_encoding,
469 builtin: HashMap::new(),
470 diff_codes: differences_codes(doc, fdict),
471 ascent,
472 descent,
473 ink_y: HashMap::new(),
474 hash: hash_name(&sanitizer_name),
475 math: is_math_font_name(&sanitizer_name),
476 style: crate::font_style::parse_font_style(&String::from_utf8_lossy(
477 &base_font_name(fdict).unwrap_or_else(|| name.to_vec()),
478 )),
479 };
480 font.blank_codes = blank_codes(doc, fdict, &font);
481 if !two_byte && subtype != b"Type3".as_slice() && uses_builtin_encoding(doc, fdict) {
482 font.builtin = builtin_encoding(doc, fdict, &font);
483 }
484 if ink_boxes {
485 font.ink_y = ink_extents(doc, fdict, &font);
486 }
487 font
488}
489
490fn uses_builtin_encoding(doc: &Document, fdict: &Dictionary) -> bool {
496 let symbolic = fdict
497 .get(b"FontDescriptor")
498 .ok()
499 .and_then(|o| as_dict(doc, o))
500 .and_then(|fd| fd.get(b"Flags").ok())
501 .and_then(|o| deref(doc, o))
502 .and_then(num)
503 .is_some_and(|f| (f as i64) & 4 != 0);
504 let declared_base = match fdict.get(b"Encoding").ok().and_then(|o| deref(doc, o)) {
505 Some(Object::Name(_)) => true,
506 Some(Object::Dictionary(d)) => d.get(b"BaseEncoding").is_ok(),
507 _ => false,
508 };
509 symbolic && !declared_base
510}
511
512fn differences_codes(doc: &Document, fdict: &Dictionary) -> HashSet<u8> {
514 let mut codes = HashSet::new();
515 let mut code = 0i64;
516 for el in differences_array(doc, fdict).unwrap_or_default() {
517 match el {
518 Object::Integer(i) => code = i,
519 Object::Real(r) => code = r as i64,
520 Object::Name(_) => {
521 if (0..=255).contains(&code) {
522 codes.insert(code as u8);
523 }
524 code += 1;
525 }
526 _ => {}
527 }
528 }
529 codes
530}
531
532#[cfg(feature = "render")]
536fn builtin_encoding(doc: &Document, fdict: &Dictionary, font: &Font) -> HashMap<u8, String> {
537 let mut codes: Vec<u32> = font.widths.keys().copied().collect();
538 if codes.is_empty() {
539 codes.extend(0..=255);
540 }
541 let needed = codes.iter().any(|&c| {
542 c <= 255 && !font.to_unicode.contains_key(&c) && !font.diff_codes.contains(&(c as u8))
543 });
544 if !needed {
545 return HashMap::new();
546 }
547 crate::render::font::LoadedFont::load(doc, fdict).builtin_encoding_text()
548}
549
550#[cfg(not(feature = "render"))]
553fn builtin_encoding(_doc: &Document, _fdict: &Dictionary, _font: &Font) -> HashMap<u8, String> {
554 HashMap::new()
555}
556
557#[cfg(feature = "render")]
560fn ink_extents(doc: &Document, fdict: &Dictionary, font: &Font) -> HashMap<u32, (f64, f64)> {
561 const MAX_CODES: usize = 4096;
562 let loaded = crate::render::font::LoadedFont::load(doc, fdict);
563 if !loaded.has_program() {
564 return HashMap::new();
565 }
566 let mut codes: Vec<u32> = font.widths.keys().copied().collect();
567 if !font.two_byte {
568 codes.extend(0..=255);
569 codes.sort_unstable();
570 codes.dedup();
571 }
572 codes
573 .into_iter()
574 .take(MAX_CODES)
575 .filter_map(|c| Some((c, loaded.glyph_ink_y(c)??)))
576 .collect()
577}
578
579#[cfg(not(feature = "render"))]
582fn ink_extents(_doc: &Document, _fdict: &Dictionary, _font: &Font) -> HashMap<u32, (f64, f64)> {
583 HashMap::new()
584}
585
586#[cfg(feature = "render")]
592fn blank_codes(doc: &Document, fdict: &Dictionary, font: &Font) -> HashSet<u32> {
593 const MAX_CANDIDATES: usize = 4096;
596 let unmapped: Vec<u32> = font
597 .widths
598 .keys()
599 .copied()
600 .filter(|&c| font.decode_code(c).0.as_deref() == Some("\u{FFFD}"))
601 .take(MAX_CANDIDATES + 1)
602 .collect();
603 if unmapped.is_empty() || unmapped.len() > MAX_CANDIDATES {
604 return HashSet::new();
605 }
606 let loaded = crate::render::font::LoadedFont::load(doc, fdict);
607 unmapped
608 .into_iter()
609 .filter(|&c| loaded.glyph_has_ink(c) == Some(false))
610 .collect()
611}
612
613#[cfg(not(feature = "render"))]
614fn blank_codes(_doc: &Document, _fdict: &Dictionary, _font: &Font) -> HashSet<u32> {
615 HashSet::new()
616}
617
618#[derive(Clone, Copy)]
619enum CidFallback {
620 None,
621 UnicodeCodes { utf16: bool },
622 Collection(&'static [u8]),
623}
624
625pub(crate) fn unicode_cmap_char(code: u32) -> Option<char> {
628 if code <= 0xffff {
629 char::from_u32(code)
630 } else {
631 let units = [(code >> 16) as u16, code as u16];
632 let mut chars = char::decode_utf16(units);
633 let ch = chars.next()?.ok()?;
634 chars.next().is_none().then_some(ch)
635 }
636}
637
638#[cfg(not(feature = "cid-collections"))]
639fn collection_table(_ordering: &[u8]) -> Option<&'static [u8]> {
640 None
641}
642
643#[cfg(feature = "cid-collections")]
644fn collection_table(ordering: &[u8]) -> Option<&'static [u8]> {
645 macro_rules! table {
646 ($file:literal) => {
647 include_bytes!(concat!(env!("OUT_DIR"), "/", $file))
648 };
649 }
650 Some(match ordering {
651 b"Japan1" => table!("Adobe-Japan1-UCS2"),
652 b"GB1" => table!("Adobe-GB1-UCS2"),
653 b"CNS1" => table!("Adobe-CNS1-UCS2"),
654 b"Korea1" => table!("Adobe-Korea1-UCS2"),
655 b"KR" => table!("Adobe-KR-UCS2"),
656 _ => return None,
657 })
658}
659
660pub(crate) fn collection_text(table: &[u8], cid: u32) -> Option<String> {
664 let n = u32::from_le_bytes(table.get(..4)?.try_into().ok()?) as usize;
665 let at = 4 + 3 * usize::try_from(cid).ok().filter(|&c| c < n)?;
666 let &[a, b, c] = table.get(at..at + 3)? else {
667 return None;
668 };
669 match u32::from_be_bytes([0, a, b, c]) {
670 0 => None,
671 v @ ..0x110000 => char::from_u32(v).map(String::from),
672 v => {
673 let at = 4 + 3 * n + (v - 0x110000) as usize;
674 let len = *table.get(at)? as usize;
675 std::str::from_utf8(table.get(at + 1..at + 1 + len)?)
676 .ok()
677 .map(str::to_owned)
678 }
679 }
680}
681
682fn cid_fallback(doc: &Document, fdict: &Dictionary) -> CidFallback {
683 let encoding = fdict
684 .get(b"Encoding")
685 .ok()
686 .and_then(|o| deref(doc, o))
687 .and_then(|o| o.as_name().ok())
688 .unwrap_or(&[]);
689 if encoding.starts_with(b"Uni")
690 && (encoding.windows(4).any(|w| w == b"UCS2") || encoding.windows(5).any(|w| w == b"UTF16"))
691 {
692 return CidFallback::UnicodeCodes {
693 utf16: encoding.windows(5).any(|w| w == b"UTF16"),
694 };
695 }
696 if encoding != b"Identity-H" && encoding != b"Identity-V" {
697 return CidFallback::None;
699 }
700 cid_collection(doc, fdict).map_or(CidFallback::None, CidFallback::Collection)
701}
702
703pub(crate) fn cid_collection(doc: &Document, fdict: &Dictionary) -> Option<&'static [u8]> {
705 let Object::Array(descendants) = deref(doc, fdict.get(b"DescendantFonts").ok()?)? else {
706 return None;
707 };
708 let descendant = as_dict(doc, descendants.first()?)?;
709 let info = as_dict(doc, descendant.get(b"CIDSystemInfo").ok()?)?;
710 let registry = deref(doc, info.get(b"Registry").ok()?)?.as_str().ok()?;
711 let ordering = deref(doc, info.get(b"Ordering").ok()?)?.as_str().ok()?;
712 (registry == b"Adobe").then(|| collection_table(ordering))?
713}
714
715fn differences_array(doc: &Document, fdict: &Dictionary) -> Option<Vec<Object>> {
717 let enc = fdict.get(b"Encoding").ok().and_then(|o| deref(doc, o))?;
718 let diffs = enc.as_dict().ok()?.get(b"Differences").ok()?;
719 match deref(doc, diffs)? {
720 Object::Array(a) => Some(a.clone()),
721 _ => None,
722 }
723}
724
725fn reconcile_stale_tounicode(to_unicode: &mut HashMap<u32, String>, diffs: &[Object]) {
744 let says_nothing = |value: &str| {
745 let mut chars = value.chars();
746 match (chars.next(), chars.next()) {
747 (None, _) => true,
748 (Some(c), None) => {
749 let cp = c as u32;
750 cp == 0 || cp == 0xFFFD || (0xFDD0..=0xFDEF).contains(&cp) || cp & 0xFFFE == 0xFFFE
751 }
752 _ => false,
753 }
754 };
755 let mut code = 0u8;
756 for el in diffs {
757 match el {
758 Object::Integer(i) => code = *i as u8,
759 Object::Name(name) => {
760 if let Some(ch) = glyph_name_to_char(name) {
761 let identity = (code as char).to_string();
762 let current = to_unicode.get(&u32::from(code));
763 if (ch.to_string() != identity && current == Some(&identity))
764 || current.is_some_and(|v| says_nothing(v))
765 {
766 to_unicode.insert(u32::from(code), ch.to_string());
767 }
768 }
769 code = code.wrapping_add(1);
770 }
771 _ => {}
772 }
773 }
774}
775
776fn differences_gid_names(doc: &Document, fdict: &Dictionary) -> HashMap<u8, String> {
782 let mut map = HashMap::new();
783 let Some(Object::Dictionary(enc)) = fdict.get(b"Encoding").ok().and_then(|o| deref(doc, o))
784 else {
785 return map;
786 };
787 let Some(Object::Array(diffs)) = enc.get(b"Differences").ok().and_then(|o| deref(doc, o))
788 else {
789 return map;
790 };
791 let mut code = 0u8;
792 for el in diffs {
793 match el {
794 Object::Integer(i) => code = *i as u8,
795 Object::Name(name) => {
796 if glyph_name_to_char(name).is_none() && is_gid_name(name) {
797 map.insert(code, String::from_utf8_lossy(name).into_owned());
798 }
799 code = code.wrapping_add(1);
800 }
801 _ => {}
802 }
803 }
804 map
805}
806
807fn type1_program_encoding(doc: &Document, fdict: &Dictionary) -> HashMap<u8, char> {
815 let mut map = HashMap::new();
816 let Some(desc) = fdict
817 .get(b"FontDescriptor")
818 .ok()
819 .and_then(|o| deref(doc, o))
820 .and_then(|o| o.as_dict().ok())
821 else {
822 return map;
823 };
824 let Some(data) = desc
825 .get(b"FontFile")
826 .ok()
827 .and_then(|o| deref(doc, o))
828 .and_then(|o| o.as_stream().ok())
829 .and_then(|s| s.decompressed_content().ok())
830 else {
831 return map;
832 };
833 let head_end = data
835 .windows(5)
836 .position(|w| w == b"eexec")
837 .unwrap_or(data.len());
838 let head = String::from_utf8_lossy(&data[..head_end]);
839 let toks: Vec<&str> = head.split_whitespace().collect();
841 for w in toks.windows(4) {
842 if w[0] == "dup" && w[3] == "put" {
843 if let (Ok(code), Some(name)) = (w[1].parse::<u32>(), w[2].strip_prefix('/')) {
844 if code <= 255 {
845 if let Some(ch) = glyph_name_to_char(name.as_bytes()) {
846 map.insert(code as u8, ch);
847 }
848 }
849 }
850 }
851 }
852 map
853}
854
855fn unknown_name_text(name: &str) -> Option<String> {
861 let stem = name.rsplit_once('.').map_or(name, |(s, _)| s);
862 (!is_index_name(stem)).then(|| stem.to_string())
863}
864
865fn is_index_name(name: &str) -> bool {
873 let lower = name.to_ascii_lowercase();
874 ["gid", "glyph", "g", "cid", "index"].iter().any(|p| {
875 lower
876 .strip_prefix(p)
877 .is_some_and(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_hexdigit()))
878 })
879}
880
881fn is_gid_name(name: &[u8]) -> bool {
888 let Ok(s) = std::str::from_utf8(name) else {
889 return false;
890 };
891 if s.starts_with("afii") || s.starts_with("uni") {
892 return false;
893 }
894 if is_index_name(s) {
895 return true;
896 }
897 let alpha = s.bytes().take_while(|b| b.is_ascii_alphabetic()).count();
901 let digits = s.len() - alpha;
902 (1..=3).contains(&alpha)
903 && digits >= 3
904 && s.as_bytes()[alpha..].iter().all(|b| b.is_ascii_digit())
905}
906
907fn font_ascent_descent(doc: &Document, fdict: &Dictionary, two_byte: bool) -> (f64, f64, bool) {
919 let descr_owner = if two_byte {
921 fdict
922 .get(b"DescendantFonts")
923 .ok()
924 .and_then(|o| deref(doc, o))
925 .and_then(|o| match o {
926 Object::Array(a) => a.first(),
927 _ => None,
928 })
929 .and_then(|o| as_dict(doc, o))
930 } else {
931 Some(fdict)
932 };
933 let fd = descr_owner
934 .and_then(|d| d.get(b"FontDescriptor").ok())
935 .and_then(|o| as_dict(doc, o));
936 let read = |key: &[u8]| fd.and_then(|d| d.get(key).ok()).and_then(num);
937 let plausible = |v: f64| v.is_finite() && v.abs() <= 8000.0;
938 let bbox = fd
939 .and_then(|d| d.get(b"FontBBox").ok())
940 .and_then(|o| deref(doc, o))
941 .and_then(|o| match o {
942 Object::Array(a) if a.len() == 4 => {
943 let v: Vec<f64> = a.iter().filter_map(num).collect();
944 (v.len() == 4).then(|| [v[0], v[1], v[2], v[3]])
945 }
946 _ => None,
947 });
948 let usable = |v: f64| v.abs() > 1e-3 && plausible(v);
949 let cap_scaled = |asc: f64, desc: f64| {
965 let ratio = read(b"CapHeight")
966 .filter(|&c| plausible(c))
967 .map(|c| c / asc)
968 .filter(|r| (0.05..=1.0).contains(r))
969 .unwrap_or(1.0);
970 (asc * ratio, desc * ratio)
971 };
972 let mut invalid = false;
973 let asc = match read(b"Ascent") {
974 Some(v) if plausible(v) => v,
975 Some(_) => {
976 invalid = true;
977 bbox.map(|b| b[3]).filter(|&v| usable(v)).unwrap_or(750.0)
978 }
979 None => 750.0,
980 };
981 let desc = match read(b"Descent") {
982 Some(v) if plausible(v) => v,
983 Some(_) => {
984 invalid = true;
985 bbox.map(|b| b[1]).filter(|&v| usable(v)).unwrap_or(-250.0)
986 }
987 None => -250.0,
988 };
989 if !(desc <= 0.0 && asc >= 0.0 && desc < asc) {
990 if let Some(b) = bbox.filter(|b| {
991 b[1] <= 0.0 && b[3] >= 0.0 && b[1] < b[3] && plausible(b[1]) && plausible(b[3])
992 }) {
993 let (asc, desc) = cap_scaled(b[3], b[1]);
994 return (asc, desc, true);
995 }
996 }
997 if asc - desc <= 1.0 {
1004 return (750.0, -250.0, invalid);
1005 }
1006 let (asc, desc) = cap_scaled(asc, desc);
1007 (asc, desc, invalid)
1008}
1009
1010fn base_font_name(fdict: &Dictionary) -> Option<Vec<u8>> {
1012 let name = fdict.get(b"BaseFont").ok()?.as_name().ok()?;
1013 let stripped = match name.iter().position(|&b| b == b'+') {
1014 Some(i) if i == 6 => &name[i + 1..],
1015 _ => name,
1016 };
1017 Some(stripped.to_vec())
1018}
1019
1020fn simple_widths(doc: &Document, fdict: &Dictionary) -> (HashMap<u32, f64>, f64) {
1022 let mut map = HashMap::new();
1023 let first = fdict
1024 .get(b"FirstChar")
1025 .ok()
1026 .and_then(|o| o.as_i64().ok())
1027 .unwrap_or(0) as u32;
1028 if let Some(Object::Array(arr)) = fdict.get(b"Widths").ok().and_then(|o| deref(doc, o)) {
1029 for (i, w) in arr.iter().enumerate() {
1030 if let Some(w) = num(w) {
1031 map.insert(first + i as u32, w);
1032 }
1033 }
1034 }
1035 let dw = fdict
1036 .get(b"FontDescriptor")
1037 .ok()
1038 .and_then(|o| as_dict(doc, o))
1039 .and_then(|d| d.get(b"MissingWidth").ok())
1040 .and_then(num)
1041 .unwrap_or(0.0);
1042 (map, dw)
1043}
1044
1045fn cid_widths(doc: &Document, fdict: &Dictionary) -> (HashMap<u32, f64>, f64) {
1047 let mut map = HashMap::new();
1048 let Some(desc) = fdict
1049 .get(b"DescendantFonts")
1050 .ok()
1051 .and_then(|o| deref(doc, o))
1052 .and_then(|o| match o {
1053 Object::Array(a) => a.first(),
1054 _ => None,
1055 })
1056 .and_then(|o| as_dict(doc, o))
1057 else {
1058 return (map, 1000.0);
1059 };
1060 let dw = desc.get(b"DW").ok().and_then(num).unwrap_or(1000.0);
1061 if let Some(Object::Array(w)) = desc.get(b"W").ok().and_then(|o| deref(doc, o)) {
1062 let mut i = 0;
1063 while i < w.len() {
1064 let c = w.get(i).and_then(num);
1065 match (c, w.get(i + 1)) {
1066 (Some(c), Some(Object::Array(list))) => {
1068 for (k, wv) in list.iter().enumerate() {
1069 if let Some(wv) = num(wv) {
1070 map.insert(c as u32 + k as u32, wv);
1071 }
1072 }
1073 i += 2;
1074 }
1075 (Some(c1), Some(o2)) => {
1077 if let (Some(c2), Some(wv)) = (num(o2), w.get(i + 2).and_then(num)) {
1078 for cid in c1 as u32..=c2 as u32 {
1079 map.insert(cid, wv);
1080 }
1081 }
1082 i += 3;
1083 }
1084 _ => break,
1085 }
1086 }
1087 }
1088 (map, dw)
1089}
1090
1091fn num(o: &Object) -> Option<f64> {
1092 match o {
1093 Object::Integer(i) => Some(*i as f64),
1094 Object::Real(r) => Some(real(*r)),
1095 _ => None,
1096 }
1097}
1098
1099fn real(r: f32) -> f64 {
1104 use std::fmt::Write as _;
1105 let mut buf = String::with_capacity(16);
1106 let _ = write!(buf, "{r}");
1107 buf.parse().unwrap_or(r as f64)
1108}
1109
1110fn codes(font: &Font, bytes: &[u8]) -> Vec<u32> {
1113 if font.two_byte {
1114 let mut units = bytes
1115 .chunks(2)
1116 .map(|c| {
1117 if c.len() == 2 {
1118 ((c[0] as u32) << 8) | c[1] as u32
1119 } else {
1120 c[0] as u32
1121 }
1122 })
1123 .peekable();
1124 let utf16 = matches!(font.cid_fallback, CidFallback::UnicodeCodes { utf16: true });
1125 let mut out = Vec::with_capacity(bytes.len() / 2 + 1);
1126 while let Some(mut code) = units.next() {
1127 if utf16 && (0xd800..=0xdbff).contains(&code) {
1128 if let Some(low) = units.next_if(|u| (0xdc00..=0xdfff).contains(u)) {
1129 code = (code << 16) | low;
1130 }
1131 }
1132 out.push(code);
1133 }
1134 out
1135 } else {
1136 bytes.iter().map(|&b| b as u32).collect()
1137 }
1138}
1139
1140#[derive(Debug, Clone, Copy, PartialEq)]
1155pub(crate) struct PageBox {
1156 pub l: f32,
1158 pub b: f32,
1160 pub w: f32,
1161 pub h: f32,
1162}
1163
1164impl PageBox {
1165 pub fn top(&self) -> f32 {
1167 self.b + self.h
1168 }
1169}
1170
1171fn inherited_rect(
1174 doc: &Document,
1175 page_id: lopdf::ObjectId,
1176 key: &[u8],
1177) -> Option<(f32, f32, f32, f32)> {
1178 let mut id = page_id;
1179 for _ in 0..32 {
1180 let dict = doc.get_object(id).ok()?.as_dict().ok()?;
1181 if let Some(Object::Array(a)) = dict.get(key).ok().and_then(|o| deref(doc, o)) {
1182 let v: Vec<f32> = a.iter().filter_map(|o| num(o).map(|x| x as f32)).collect();
1183 if v.len() == 4 && v.iter().all(|x| x.is_finite()) {
1184 return Some((
1185 v[0].min(v[2]),
1186 v[1].min(v[3]),
1187 v[0].max(v[2]),
1188 v[1].max(v[3]),
1189 ));
1190 }
1191 return None;
1192 }
1193 id = dict.get(b"Parent").ok()?.as_reference().ok()?;
1194 }
1195 None
1196}
1197
1198pub(crate) fn page_box(doc: &Document, page_id: lopdf::ObjectId) -> PageBox {
1199 let nonempty = |r: &(f32, f32, f32, f32)| r.2 > r.0 && r.3 > r.1;
1200 let media = inherited_rect(doc, page_id, b"MediaBox")
1201 .filter(nonempty)
1202 .unwrap_or((0.0, 0.0, 612.0, 792.0));
1203 let crop = inherited_rect(doc, page_id, b"CropBox")
1204 .map(|c| {
1205 (
1206 c.0.max(media.0),
1207 c.1.max(media.1),
1208 c.2.min(media.2),
1209 c.3.min(media.3),
1210 )
1211 })
1212 .filter(nonempty)
1213 .unwrap_or(media);
1214 PageBox {
1215 l: crop.0,
1216 b: crop.1,
1217 w: crop.2 - crop.0,
1218 h: crop.3 - crop.1,
1219 }
1220}
1221
1222pub(crate) fn content_stream_bytes(stream: &lopdf::Stream) -> Option<Vec<u8>> {
1232 let predictor = stream
1233 .dict
1234 .get(b"DecodeParms")
1235 .ok()
1236 .and_then(|o| o.as_dict().ok())
1237 .and_then(|d| d.get(b"Predictor").ok())
1238 .and_then(|o| o.as_i64().ok())
1239 .unwrap_or(1);
1240 let plain_flate = predictor <= 1
1241 && matches!(
1242 stream.filters().unwrap_or_default().as_slice(),
1243 [f] if *f == b"FlateDecode" || *f == b"Fl"
1244 );
1245 if plain_flate {
1246 let out = inflate_prefix(&stream.content);
1247 if !out.is_empty() {
1248 return Some(out);
1249 }
1250 }
1251 match stream.decompressed_content() {
1254 Ok(data) => Some(data),
1255 Err(_) if plain_flate => None,
1256 Err(_) => Some(stream.content.clone()),
1258 }
1259}
1260
1261pub(crate) fn inflate_prefix(data: &[u8]) -> Vec<u8> {
1265 let mut dec = flate2::Decompress::new(true);
1266 let mut out = Vec::new();
1267 let mut buf = vec![0u8; 1 << 16];
1268 loop {
1269 let (in_before, out_before) = (dec.total_in(), dec.total_out());
1270 let input = &data[(in_before as usize).min(data.len())..];
1271 let status = dec.decompress(input, &mut buf, flate2::FlushDecompress::None);
1272 let written = (dec.total_out() - out_before) as usize;
1273 out.extend_from_slice(&buf[..written]);
1274 match status {
1275 Ok(flate2::Status::Ok) if written > 0 || dec.total_in() > in_before => {}
1276 _ => break,
1277 }
1278 }
1279 out
1280}
1281
1282pub(crate) fn page_content(doc: &Document, page_id: lopdf::ObjectId) -> Vec<u8> {
1287 let mut content = Vec::new();
1288 for id in doc.get_page_contents(page_id) {
1289 if let Some(data) = doc
1290 .get_object(id)
1291 .and_then(Object::as_stream)
1292 .ok()
1293 .and_then(content_stream_bytes)
1294 {
1295 content.extend_from_slice(&data);
1296 content.push(b'\n');
1297 }
1298 }
1299 content
1300}
1301
1302fn page_size(doc: &Document, page_id: lopdf::ObjectId) -> (f32, f32) {
1305 let pb = page_box(doc, page_id);
1306 (pb.w, pb.h)
1307}
1308
1309pub fn content_diagnosis(bytes: &[u8]) -> String {
1315 let Some(doc) = load_document(bytes) else {
1316 return "document does not load".into();
1317 };
1318 let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
1319 pages.sort_by_key(|(n, _)| *n);
1320 let mut out = String::new();
1321 let mut caches = DocCaches::default();
1322 for (n, pid) in pages.into_iter().take(4) {
1323 let content_bytes = page_content(&doc, pid);
1324 let ops = lopdf::content::Content::decode(&content_bytes)
1325 .map(|c| c.operations.len())
1326 .ok();
1327 let res = page_res(&doc, pid);
1328 let fonts = res.map(|r| fonts_from_res(&doc, r, &mut caches).len());
1329 let glyphs = page_glyphs_cached(&doc, pid, &mut caches).len();
1330 out.push_str(&format!(
1331 "\n page {n}: content {} B, ops {}, resources {}, fonts {}, glyphs {}",
1332 content_bytes.len(),
1333 ops.map_or("UNDECODABLE".to_string(), |n| n.to_string()),
1334 if res.is_some() { "ok" } else { "MISSING" },
1335 fonts.map_or("-".to_string(), |n| n.to_string()),
1336 glyphs,
1337 ));
1338 }
1339 out
1340}
1341
1342pub fn text_layer_is_vestigial(pages: &[crate::pdfium_backend::PdfPage]) -> bool {
1355 let mut tally = TextLayerTally::default();
1356 pages.iter().for_each(|p| tally.add(p));
1357 tally.is_vestigial()
1358}
1359
1360#[derive(Debug, Default, Clone, Copy)]
1363pub struct TextLayerTally {
1364 pages: usize,
1365 lines: usize,
1366 chars: usize,
1367}
1368
1369impl TextLayerTally {
1370 pub fn add(&mut self, page: &crate::pdfium_backend::PdfPage) {
1371 self.pages += 1;
1372 self.lines += page.cells.len();
1373 self.chars += page
1374 .cells
1375 .iter()
1376 .map(|c| c.text.chars().count())
1377 .sum::<usize>();
1378 }
1379
1380 pub fn is_vestigial(&self) -> bool {
1382 self.lines == 0 || (self.lines <= self.pages && self.chars < 32)
1383 }
1384
1385 pub fn proves_text(&self, total_pages: usize) -> bool {
1389 self.lines > 0 && (self.lines > total_pages || self.chars >= 32)
1390 }
1391}
1392
1393pub fn xref_repair_status(bytes: &[u8]) -> String {
1397 if Document::load_mem(bytes).is_ok() {
1398 return "loads unaided; no repair needed".into();
1399 }
1400 match pad_short_xref_entries(bytes) {
1401 Ok(fixed) => match Document::load_mem(&fixed) {
1402 Ok(_) => "repaired: cross-reference entries padded to 20 bytes".into(),
1403 Err(e) => format!("padded the entries, but it still will not load: {e}"),
1404 },
1405 Err(why) => format!("repair declined — {why}"),
1406 }
1407}
1408
1409pub(crate) fn load_document(bytes: &[u8]) -> Option<Document> {
1424 open_document(bytes, None).ok()
1425}
1426
1427#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1429pub(crate) enum OpenError {
1430 Unreadable,
1432 Password,
1434}
1435
1436pub(crate) fn open_document(bytes: &[u8], password: Option<&str>) -> Result<Document, OpenError> {
1443 let Some(doc) = load_document_raw(bytes, password) else {
1444 if password.is_some() && load_document_raw(bytes, None).is_some_and(|d| d.is_encrypted()) {
1448 return Err(OpenError::Password);
1449 }
1450 return Err(OpenError::Unreadable);
1451 };
1452 if doc.is_encrypted() {
1453 return Err(OpenError::Password);
1454 }
1455 Ok(doc)
1456}
1457
1458fn load_options(password: Option<&str>) -> lopdf::LoadOptions {
1459 lopdf::LoadOptions {
1460 password: password.map(str::to_string),
1461 ..lopdf::LoadOptions::default()
1462 }
1463}
1464
1465fn load_document_raw(bytes: &[u8], password: Option<&str>) -> Option<Document> {
1466 let mut fallback = None;
1471 if let Some(doc) = best_effort_load(bytes, password, &mut fallback) {
1472 return Some(doc);
1473 }
1474 let xref_fixed = pad_short_xref_entries(bytes).ok();
1475 if let Some(fixed) = &xref_fixed {
1476 if let Some(doc) = best_effort_load(fixed, password, &mut fallback) {
1477 return Some(doc);
1478 }
1479 }
1480 let lengths_fixed = fix_stream_lengths(xref_fixed.as_deref().unwrap_or(bytes));
1483 if let Some(doc) = best_effort_load(&lengths_fixed, password, &mut fallback) {
1484 return Some(doc);
1485 }
1486 fallback
1487}
1488
1489fn best_effort_load(
1492 data: &[u8],
1493 password: Option<&str>,
1494 fallback: &mut Option<Document>,
1495) -> Option<Document> {
1496 match Document::load_mem_with_options(data, load_options(password)) {
1497 Ok(doc) if has_page_content(&doc) => Some(doc),
1498 Ok(doc) => {
1499 fallback.get_or_insert(doc);
1500 None
1501 }
1502 Err(_) => None,
1503 }
1504}
1505
1506fn has_page_content(doc: &Document) -> bool {
1510 doc.get_pages()
1511 .into_values()
1512 .take(4)
1513 .any(|pid| !page_content(doc, pid).is_empty())
1514}
1515
1516fn fix_stream_lengths(bytes: &[u8]) -> Vec<u8> {
1529 let mut out = bytes.to_vec();
1530 let mut i = 0;
1531 while let Some(rel) = find(&out[i..], b"stream") {
1532 let kw = i + rel;
1533 i = kw + 6;
1534 if kw >= 3 && &out[kw - 3..kw] == b"end" {
1536 continue;
1537 }
1538 let mut data = kw + 6;
1540 if out.get(data..data + 2) == Some(b"\r\n".as_slice()) {
1541 data += 2;
1542 } else if matches!(out.get(data), Some(b'\n' | b'\r')) {
1543 data += 1;
1544 }
1545 let Some(end) = find(&out[data..], b"endstream").map(|r| data + r) else {
1546 continue;
1547 };
1548 let dict_start = out[..kw].iter().rposition(|&c| c == b'<').unwrap_or(0);
1550 let Some(lrel) = find(&out[dict_start..kw], b"/Length") else {
1551 continue;
1552 };
1553 let mut d = dict_start + lrel + 7;
1554 while matches!(out.get(d), Some(b' ')) {
1555 d += 1;
1556 }
1557 let digits = out[d..].iter().take_while(|c| c.is_ascii_digit()).count();
1558 if digits == 0 {
1559 continue;
1560 }
1561 let declared: usize = match std::str::from_utf8(&out[d..d + digits])
1562 .ok()
1563 .and_then(|s| s.parse().ok())
1564 {
1565 Some(v) => v,
1566 None => continue,
1567 };
1568 let actual = end - data;
1569 let replacement = actual.to_string();
1572 if actual == declared || replacement.len() > digits {
1573 continue;
1574 }
1575 out[d..d + digits].fill(b' ');
1576 out[d..d + replacement.len()].copy_from_slice(replacement.as_bytes());
1577 }
1578 out
1579}
1580
1581fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1582 haystack.windows(needle.len()).position(|w| w == needle)
1583}
1584
1585pub(crate) fn pad_short_xref_entries(bytes: &[u8]) -> Result<Vec<u8>, &'static str> {
1588 let is_boundary = |i: usize| i == 0 || matches!(bytes[i - 1], b'\n' | b'\r');
1591 let mut starts = (0..bytes.len().saturating_sub(4))
1592 .filter(|&i| &bytes[i..i + 4] == b"xref" && is_boundary(i));
1593 let xref_at = starts
1594 .next()
1595 .ok_or("no classic `xref` section (an xref stream?)")?;
1596 if starts.next().is_some() {
1597 return Err("more than one xref section (incremental update)");
1598 }
1599 let last_obj = bytes
1600 .windows(3)
1601 .rposition(|w| w == b"obj")
1602 .ok_or("no objects found")?;
1603 if last_obj > xref_at {
1604 return Err("an object follows the xref — padding would move it");
1605 }
1606
1607 let mut out = bytes[..xref_at].to_vec();
1608 out.extend_from_slice(b"xref\n");
1609 let mut i = xref_at + 4;
1610 let skip_ws = |i: &mut usize| {
1611 while matches!(bytes.get(*i), Some(b'\r' | b'\n' | b' ')) {
1612 *i += 1;
1613 }
1614 };
1615 loop {
1616 skip_ws(&mut i);
1617 if bytes[i..].starts_with(b"trailer") {
1619 out.extend_from_slice(&bytes[i..]);
1620 return Ok(out);
1621 }
1622 let header_end = i + bytes[i..]
1623 .iter()
1624 .position(|c| matches!(c, b'\n' | b'\r'))
1625 .ok_or("subsection header runs off the end")?;
1626 let header = std::str::from_utf8(&bytes[i..header_end])
1627 .map_err(|_| "subsection header is not text")?
1628 .trim();
1629 let mut parts = header.split_whitespace();
1630 let count: usize = parts
1631 .nth(1)
1632 .and_then(|c| c.parse().ok())
1633 .ok_or("unparseable subsection header")?;
1634 if parts.next().is_some() || count == 0 {
1635 return Err("unexpected subsection header shape");
1636 }
1637 out.extend_from_slice(header.as_bytes());
1638 out.push(b'\n');
1639 i = header_end;
1640 for _ in 0..count {
1641 skip_ws(&mut i);
1642 let entry = bytes.get(i..i + 18).ok_or("xref entry runs off the end")?;
1644 let well_formed = entry[..10].iter().all(u8::is_ascii_digit)
1645 && entry[10] == b' '
1646 && entry[11..16].iter().all(u8::is_ascii_digit)
1647 && entry[16] == b' '
1648 && matches!(entry[17], b'n' | b'f');
1649 if !well_formed {
1650 return Err("xref entry is not `nnnnnnnnnn ggggg n`");
1651 }
1652 out.extend_from_slice(entry);
1653 out.extend_from_slice(b" \n"); i += 18;
1655 }
1656 }
1657}
1658
1659pub fn debug_glyphs(bytes: &[u8], index: usize) -> Vec<(char, f32, f32, f32, f32)> {
1662 let Some(doc) = load_document(bytes) else {
1663 return Vec::new();
1664 };
1665 let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
1666 pages.sort_by_key(|(n, _)| *n);
1667 let Some((_, pid)) = pages.get(index) else {
1668 return Vec::new();
1669 };
1670 page_glyphs(&doc, *pid)
1671 .into_iter()
1672 .map(|g| (g.ch, g.ll, g.lr, g.lb, g.lt))
1673 .collect()
1674}
1675
1676pub fn pdf_textlines(bytes: &[u8]) -> Vec<(f32, f32, Vec<crate::pdfium_backend::TextCell>)> {
1680 let Some(doc) = load_document(bytes) else {
1681 return Vec::new();
1682 };
1683 let mut caches = DocCaches::default();
1684 let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
1685 pages.sort_by_key(|(n, _)| *n);
1686 pages
1687 .into_iter()
1688 .map(|(_, pid)| {
1689 let (w, h) = page_size(&doc, pid);
1690 let glyphs = page_glyphs_cached(&doc, pid, &mut caches);
1691 let cells = crate::dp_lines::line_cells(&glyphs, h, true);
1692 (w, h, cells)
1693 })
1694 .collect()
1695}
1696
1697pub fn pdf_words(bytes: &[u8]) -> Vec<(f32, f32, Vec<crate::pdfium_backend::TextCell>)> {
1702 let Some(doc) = load_document(bytes) else {
1703 return Vec::new();
1704 };
1705 let mut caches = DocCaches::default();
1706 let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
1707 pages.sort_by_key(|(n, _)| *n);
1708 pages
1709 .into_iter()
1710 .map(|(_, pid)| {
1711 let (w, h) = page_size(&doc, pid);
1712 let glyphs = page_glyphs_cached(&doc, pid, &mut caches);
1713 let cells = crate::dp_lines::word_cells(&glyphs, h, true);
1714 (w, h, cells)
1715 })
1716 .collect()
1717}
1718
1719#[derive(Default)]
1723pub struct PageParserCells {
1724 pub prose: Vec<crate::pdfium_backend::TextCell>,
1725 pub words: Vec<crate::pdfium_backend::TextCell>,
1726 pub code: Vec<crate::pdfium_backend::TextCell>,
1727 pub checkboxes: Vec<crate::checkbox::CheckBox>,
1729 pub bitmaps: Vec<[f32; 4]>,
1732 pub shapes: PageShapes,
1734}
1735
1736pub struct PageTextParser {
1749 doc: Document,
1750 caches: DocCaches,
1751 pages: Vec<lopdf::ObjectId>,
1753 word_gap: crate::dp_lines::WordGap,
1756 keep_typography: bool,
1760}
1761
1762impl PageTextParser {
1763 pub fn open(bytes: &[u8]) -> Option<Self> {
1765 Self::open_with_password(bytes, None)
1766 }
1767
1768 pub fn open_with_password(bytes: &[u8], password: Option<&str>) -> Option<Self> {
1772 let doc = open_document(bytes, password).ok()?;
1773 let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
1774 pages.sort_by_key(|(n, _)| *n);
1775 Some(Self {
1776 doc,
1777 caches: DocCaches::default(),
1778 pages: pages.into_iter().map(|(_, pid)| pid).collect(),
1779 word_gap: crate::dp_lines::WordGap::from_env(),
1780 keep_typography: crate::assemble::keep_typography_from_env(),
1781 })
1782 }
1783
1784 pub fn set_word_gap(&mut self, gap: Option<crate::dp_lines::WordGap>) {
1788 if let Some(g) = gap {
1789 self.word_gap = g;
1790 }
1791 }
1792
1793 pub fn set_keep_typography(&mut self, keep: Option<bool>) {
1797 if let Some(k) = keep {
1798 self.keep_typography = k;
1799 }
1800 }
1801
1802 pub(crate) fn glyph_styles(
1810 &mut self,
1811 index: usize,
1812 ) -> Vec<crate::heading_hierarchy::GlyphStyle> {
1813 let Some(&pid) = self.pages.get(index) else {
1814 return Vec::new();
1815 };
1816 let (_w, h) = page_size(&self.doc, pid);
1817 let glyphs = page_glyphs_cached(&self.doc, pid, &mut self.caches);
1818 let styles: HashMap<u64, crate::font_style::FontStyle> = self
1821 .caches
1822 .fonts
1823 .values()
1824 .map(|f| (f.hash, f.style))
1825 .collect();
1826 glyphs
1827 .iter()
1828 .filter(|g| !g.ch.is_whitespace() && g.ll.is_finite())
1829 .map(|g| {
1830 let st = styles.get(&g.font).copied().unwrap_or_default();
1831 crate::heading_hierarchy::GlyphStyle {
1832 l: g.ll,
1833 t: h - g.lt,
1834 r: g.lr,
1835 b: h - g.lb,
1836 height: g.height(),
1837 weight_cls: crate::font_style::weight_class(st.weight),
1838 italic: st.italic,
1839 styled: st.known,
1840 }
1841 })
1842 .collect()
1843 }
1844
1845 pub(crate) fn script_chars(
1854 &mut self,
1855 index: usize,
1856 ) -> Vec<(crate::script_position::ScriptChar, [f32; 4])> {
1857 let Some(&pid) = self.pages.get(index) else {
1858 return Vec::new();
1859 };
1860 let (w, h) = page_size(&self.doc, pid);
1861 let rotation = page_rotation(&self.doc, pid);
1862 page_glyphs_cached(&self.doc, pid, &mut self.caches)
1863 .iter()
1864 .filter(|g| !g.invisible && !g.ch.is_whitespace() && g.ll.is_finite())
1865 .filter_map(|g| {
1866 let [_, y, size] = g.pen?;
1867 let c = crate::script_position::ScriptChar {
1868 text: g.ch,
1869 left: g.ll,
1870 bottom: g.lb,
1871 right: g.lr,
1872 top: g.lt,
1873 baseline: y,
1874 size,
1875 horizontal: g.quad.is_none(),
1876 };
1877 let (l, t, r, b) = crate::pdfium_backend::to_display_frame(
1878 (g.ll, h - g.lt, g.lr, h - g.lb),
1879 rotation,
1880 w,
1881 h,
1882 );
1883 Some((c, [l, t, r, b]))
1884 })
1885 .collect()
1886 }
1887
1888 pub fn cells(&mut self, index: usize) -> PageParserCells {
1892 let Some(&pid) = self.pages.get(index) else {
1893 return PageParserCells::default();
1894 };
1895 let (_w, h) = page_size(&self.doc, pid);
1896 let (glyphs, inks, bitmaps, shapes) =
1897 page_glyphs_and_inks(&self.doc, pid, &mut self.caches);
1898 let (prose, words) =
1899 crate::dp_lines::line_and_word_cells_with(&glyphs, h, true, self.word_gap);
1900 PageParserCells {
1901 prose,
1902 words,
1903 code: crate::pdfium_backend::code_cells_from_glyphs(&glyphs, h),
1904 checkboxes: crate::checkbox::find(&inks, h),
1905 bitmaps,
1906 shapes,
1907 }
1908 }
1909
1910 pub fn page_count(&self) -> usize {
1912 self.pages.len()
1913 }
1914
1915 pub fn text_page(&mut self, index: usize) -> crate::pdfium_backend::PdfPage {
1921 let (w, h, (glyphs, inks, _, shapes)) = match self.pages.get(index) {
1922 Some(&pid) => {
1923 let (w, h) = page_size(&self.doc, pid);
1924 (w, h, page_glyphs_and_inks(&self.doc, pid, &mut self.caches))
1925 }
1926 None => (0.0, 0.0, Default::default()),
1927 };
1928 let (mut prose, mut words) =
1929 crate::dp_lines::line_and_word_cells_with(&glyphs, h, true, self.word_gap);
1930 drop_overpainted_cells(&mut prose);
1931 drop_overpainted_cells(&mut words);
1932 crate::pdfium_backend::PdfPage {
1933 #[cfg(feature = "ocr-prep")]
1934 image_layout: None,
1935 width: w,
1936 height: h,
1937 scale: 1.0,
1939 cells: prose,
1940 code_cells: crate::pdfium_backend::code_cells_from_glyphs(&glyphs, h),
1941 word_cells: words,
1942 checkboxes: crate::checkbox::find(&inks, h),
1943 bitmaps: Vec::new(),
1944 shapes,
1945 #[cfg(feature = "ocr-prep")]
1946 image: image::RgbImage::new(1, 1),
1947 links: Vec::new(),
1948 rotation: 0,
1949 keep_typography: self.keep_typography,
1950 #[cfg(feature = "render")]
1951 embedded_images: Vec::new(),
1952 #[cfg(feature = "render")]
1953 pending_image: None,
1954 }
1955 }
1956}
1957
1958pub fn pdf_all_cells(bytes: &[u8]) -> Vec<PageParserCells> {
1963 let Some(mut parser) = PageTextParser::open(bytes) else {
1964 return Vec::new();
1965 };
1966 (0..parser.pages.len()).map(|i| parser.cells(i)).collect()
1967}
1968
1969pub fn pdf_text_pages(bytes: &[u8]) -> Vec<crate::pdfium_backend::PdfPage> {
1976 let Some(mut parser) = PageTextParser::open(bytes) else {
1977 return Vec::new();
1978 };
1979 (0..parser.page_count())
1980 .map(|i| parser.text_page(i))
1981 .collect()
1982}
1983
1984fn drop_overpainted_cells(cells: &mut Vec<crate::pdfium_backend::TextCell>) {
2003 let mut paint = vec![false; cells.len()];
2004 for i in 0..cells.len() {
2005 for j in 0..cells.len() {
2006 if i == j || cells[i].text == cells[j].text {
2007 continue;
2008 }
2009 let (a, b) = (&cells[i], &cells[j]);
2010 let vo = (a.b.min(b.b) - a.t.max(b.t)).max(0.0);
2012 if vo < 0.6 * (a.b - a.t).min(b.b - b.t) {
2013 continue;
2014 }
2015 let shift = ((a.t + a.b) - (b.t + b.b)).abs() / 2.0;
2028 if shift > 0.5 * a.mean_advance().min(b.mean_advance()) {
2029 continue;
2030 }
2031 let ho = (a.r.min(b.r) - a.l.max(b.l)).max(0.0);
2033 if ho >= 0.8 * (a.r - a.l) && (a.r - a.l) <= (b.r - b.l) {
2034 paint[i] = true;
2035 paint[j] = true;
2036 }
2037 }
2038 }
2039 let mut keep = paint.iter().map(|p| !p);
2040 cells.retain(|_| keep.next().unwrap());
2041}
2042
2043#[derive(Clone, Copy)]
2047struct TextState {
2048 tc: f64,
2049 tw: f64,
2050 th: f64,
2051 tl: f64,
2052 trise: f64,
2053 fsize: f64,
2054 tr: i64,
2056}
2057
2058impl TextState {
2059 const INIT: TextState = TextState {
2060 tc: 0.0,
2061 tw: 0.0,
2062 th: 1.0,
2063 tl: 0.0,
2064 trise: 0.0,
2065 fsize: 0.0,
2066 tr: 0,
2067 };
2068}
2069
2070fn page_rotation(doc: &Document, pid: lopdf::ObjectId) -> u16 {
2073 let mut id = pid;
2074 for _ in 0..32 {
2075 let Ok(dict) = doc.get_dictionary(id) else {
2076 return 0;
2077 };
2078 if let Some(obj) = dict.get(b"Rotate").ok().and_then(|o| deref(doc, o)) {
2079 let quarter = (num(obj).unwrap_or(0.0) as i64 / 90).rem_euclid(4);
2080 return (quarter * 90) as u16;
2081 }
2082 match dict.get(b"Parent").ok().and_then(|o| o.as_reference().ok()) {
2083 Some(parent) => id = parent,
2084 None => return 0,
2085 }
2086 }
2087 0
2088}
2089
2090pub(crate) fn page_res(doc: &Document, page_id: lopdf::ObjectId) -> Option<&Dictionary> {
2101 let mut id = page_id;
2102 for _ in 0..32 {
2104 let dict = doc.get_object(id).ok()?.as_dict().ok()?;
2105 if let Some(res) = dict.get(b"Resources").ok().and_then(|o| as_dict(doc, o)) {
2106 return Some(res);
2107 }
2108 id = dict.get(b"Parent").ok()?.as_reference().ok()?;
2109 }
2110 None
2111}
2112
2113fn fonts_from_res(
2117 doc: &Document,
2118 res: &Dictionary,
2119 caches: &mut DocCaches,
2120) -> HashMap<Vec<u8>, Arc<Font>> {
2121 let mut map = HashMap::new();
2122 let font_dict = res
2123 .get(b"Font")
2124 .ok()
2125 .and_then(|o| deref(doc, o))
2126 .and_then(|o| o.as_dict().ok());
2127 if let Some(fd) = font_dict {
2128 for (name, value) in fd.iter() {
2129 let font = match value {
2130 Object::Reference(id) => {
2131 let key = (*id, name.clone());
2132 if let Some(f) = caches.fonts.get(&key) {
2133 Arc::clone(f)
2134 } else if let Some(fdict) = deref(doc, value).and_then(|o| o.as_dict().ok()) {
2135 let f = Arc::new(parse_font(doc, name, fdict));
2136 caches.fonts.insert(key, Arc::clone(&f));
2137 f
2138 } else {
2139 continue;
2140 }
2141 }
2142 _ => {
2143 if let Some(fdict) = deref(doc, value).and_then(|o| o.as_dict().ok()) {
2144 Arc::new(parse_font(doc, name, fdict))
2145 } else {
2146 continue;
2147 }
2148 }
2149 };
2150 map.insert(name.clone(), font);
2151 }
2152 }
2153 map
2154}
2155
2156pub(crate) fn glyph_styles(
2162 bytes: &[u8],
2163 pages: &[usize],
2164) -> HashMap<usize, Vec<crate::heading_hierarchy::GlyphStyle>> {
2165 let mut out = HashMap::new();
2166 let Some(mut parser) = PageTextParser::open(bytes) else {
2167 return out;
2168 };
2169 for &page_no in pages {
2170 if page_no == 0 {
2171 continue;
2172 }
2173 let styles = parser.glyph_styles(page_no - 1);
2174 if !styles.is_empty() {
2175 out.insert(page_no, styles);
2176 }
2177 }
2178 out
2179}
2180
2181pub(crate) fn page_glyphs(doc: &Document, page_id: lopdf::ObjectId) -> Vec<Glyph> {
2182 page_glyphs_cached(doc, page_id, &mut DocCaches::default())
2183}
2184
2185fn page_glyphs_cached(
2188 doc: &Document,
2189 page_id: lopdf::ObjectId,
2190 caches: &mut DocCaches,
2191) -> Vec<Glyph> {
2192 page_glyphs_and_inks(doc, page_id, caches).0
2193}
2194
2195fn page_glyphs_and_inks(
2201 doc: &Document,
2202 page_id: lopdf::ObjectId,
2203 caches: &mut DocCaches,
2204) -> (
2205 Vec<Glyph>,
2206 Vec<crate::checkbox::Ink>,
2207 Vec<[f32; 4]>,
2208 PageShapes,
2209) {
2210 let mut out = Vec::new();
2211 let mut inks = Vec::new();
2212 let content_bytes = page_content(doc, page_id);
2215 let Ok(content) = lopdf::content::Content::decode(&content_bytes) else {
2216 return (out, inks, Vec::new(), PageShapes::default());
2217 };
2218 let mut bitmaps = Vec::new();
2219 let mut page_shapes = PageShapes::default();
2220 if let Some(res) = page_res(doc, page_id) {
2221 let pb = page_box(doc, page_id);
2224 let base = Mat {
2225 e: -(pb.l as f64),
2226 f: -(pb.b as f64),
2227 ..Mat::ID
2228 };
2229 let mut shapes = Shapes::default();
2230 run_content(
2231 doc,
2232 res,
2233 &content,
2234 base,
2235 TextState::INIT,
2236 0,
2237 caches,
2238 &mut out,
2239 &mut inks,
2240 ShapeGs::INIT,
2241 &mut shapes,
2242 );
2243 out.retain(|g| on_page(g, pb.w, pb.h));
2244 drop_overprinted_spaces(&mut out);
2245 drop_letter_spacing_spaces(&mut out);
2246 drop_shadow_runs(&mut out);
2247 let (w, h) = (f64::from(pb.w), f64::from(pb.h));
2248 inks.retain(|ink| match *ink {
2249 crate::checkbox::Ink::Bitmap { l, b, r, t } => {
2250 let (l, r, b, t) = (l.max(0.0), r.min(w), b.max(0.0), t.min(h));
2251 if r > l && t > b {
2252 bitmaps.push([l as f32, (h - t) as f32, r as f32, (h - b) as f32]);
2253 }
2254 false
2255 }
2256 _ => true,
2257 });
2258 let top_left =
2259 |[l, b, r, t]: [f64; 4]| [l as f32, (h - t) as f32, r as f32, (h - b) as f32];
2260 page_shapes.lines = shapes.lines.into_iter().map(top_left).collect();
2261 if shapes.boxes.len() <= MAX_SHAPE_BOXES {
2262 page_shapes.boxes = connected_boxes(&shapes.boxes)
2263 .into_iter()
2264 .map(top_left)
2265 .collect();
2266 } else {
2267 docling_core::debug_log!(
2268 "textparse: {} painted paths on the page; their boxes are not merged",
2269 shapes.boxes.len()
2270 );
2271 }
2272 }
2273 (out, inks, bitmaps, page_shapes)
2274}
2275
2276#[derive(Default, Clone, Debug, PartialEq)]
2280pub struct PageShapes {
2281 pub lines: Vec<[f32; 4]>,
2282 pub boxes: Vec<[f32; 4]>,
2283}
2284
2285fn drop_shadow_runs(glyphs: &mut Vec<Glyph>) {
2311 const LOOKBACK: usize = 1024;
2313 const NEAR_EM: f32 = 0.15;
2315 const SAME_EM: f32 = 0.01;
2317 let pen = |g: &Glyph| if g.quad.is_none() { g.pen } else { None };
2318 let n = glyphs.len();
2319 let mut keep = vec![true; n];
2320 let mut earlier: HashMap<(char, u64), Vec<usize>> = HashMap::new();
2326 let mut j = 0;
2327 while j < n {
2328 let b = &glyphs[j];
2329 let continues = j > 0
2336 && match (pen(b), pen(&glyphs[j - 1])) {
2337 (Some([xb, yb, sb]), Some([xp, yp, _])) => {
2338 (yb - yp).abs() <= NEAR_EM * sb && xb > xp && xb - xp <= sb
2339 }
2340 _ => false,
2341 };
2342 let start = pen(b).filter(|p| p[2] > 0.0 && !b.ch.is_whitespace() && !continues);
2343 let mut copy = 0;
2344 if let Some([xj, yj, sj]) = start {
2345 let lo = j.saturating_sub(LOOKBACK);
2346 let candidates = earlier.entry((b.ch, b.font)).or_default();
2347 for &i in candidates.iter().rev().take_while(|&&i| i >= lo) {
2348 let Some([xi, yi, si]) = pen(&glyphs[i]) else {
2349 continue;
2350 };
2351 if (si - sj).abs() > SAME_EM * sj {
2352 continue;
2353 }
2354 let (dx, dy) = (xj - xi, yj - yi);
2355 if dx.abs() > NEAR_EM * sj || dy.abs() > NEAR_EM * sj {
2356 continue;
2357 }
2358 if dx.abs() + dy.abs() <= SAME_EM * sj {
2362 continue;
2363 }
2364 if let Some([xn, yn, _]) = glyphs.get(i + 1).and_then(pen) {
2369 let step = (xn - xi).abs().max((yn - yi).abs());
2370 if step > SAME_EM * sj && dx.abs().max(dy.abs()) >= step {
2371 continue;
2372 }
2373 }
2374 let mut m = 1;
2378 while j + m < n && i + m < j {
2379 let (a, b) = (&glyphs[i + m], &glyphs[j + m]);
2380 let (Some([xa, ya, sa]), Some([xb, yb, sb])) = (pen(a), pen(b)) else {
2381 break;
2382 };
2383 if a.ch != b.ch
2384 || a.font != b.font
2385 || (sa - sb).abs() > SAME_EM * sj
2386 || ((xb - xa) - dx).abs() > SAME_EM * sj
2387 || ((yb - ya) - dy).abs() > SAME_EM * sj
2388 {
2389 break;
2390 }
2391 m += 1;
2392 }
2393 if m >= 2 {
2394 copy = m;
2395 break;
2396 }
2397 }
2398 if copy == 0 {
2399 candidates.push(j);
2400 }
2401 }
2402 if copy > 0 {
2403 keep[j..j + copy].iter_mut().for_each(|k| *k = false);
2404 j += copy;
2405 } else {
2406 j += 1;
2407 }
2408 }
2409 let mut it = keep.into_iter();
2410 glyphs.retain(|_| it.next().unwrap_or(true));
2411}
2412
2413const MAX_ACTUAL_TEXT_DEPTH: usize = 64;
2416
2417fn apply_actual_text(out: &mut Vec<Glyph>, begin: usize, text: &str) {
2441 let begin = begin.min(out.len());
2442 let mut cells: Vec<std::ops::Range<usize>> = Vec::new();
2443 for i in begin..out.len() {
2444 match cells.last_mut() {
2445 Some(cell) if out[i].pen.is_some() && out[i].pen == out[cell.end - 1].pen => {
2446 cell.end = i + 1;
2447 }
2448 _ => cells.push(i..i + 1),
2449 }
2450 }
2451 if cells.is_empty() {
2452 return;
2453 }
2454 let chars: Vec<char> = text.chars().collect();
2455 if chars.len() > (4 * cells.len()).max(8) {
2456 return;
2457 }
2458 if chars.is_empty() {
2459 out.truncate(begin);
2460 return;
2461 }
2462 if chars.len() == cells.len() {
2463 for (w, (cell, &ch)) in cells.iter().zip(&chars).enumerate() {
2466 out[begin + w] = Glyph {
2467 ch,
2468 ..out[cell.start]
2469 };
2470 }
2471 out.truncate(begin + cells.len());
2472 return;
2473 }
2474 let quad_of = |g: &Glyph| {
2478 g.quad
2479 .unwrap_or([g.ll, g.lb, g.lr, g.lb, g.lr, g.lt, g.ll, g.lt])
2480 };
2481 let mut merged = Glyph { ..out[begin] };
2482 let mut quad = quad_of(&merged);
2483 let dir = (quad[2] - quad[0], quad[3] - quad[1]);
2484 let along = |q: &[f32; 8]| q[2] * dir.0 + q[3] * dir.1;
2485 let mut reach = along(&quad);
2486 for g in &out[begin + 1..] {
2487 merged.l = merged.l.min(g.l);
2488 merged.b = merged.b.min(g.b);
2489 merged.r = merged.r.max(g.r);
2490 merged.t = merged.t.max(g.t);
2491 merged.ll = merged.ll.min(g.ll);
2492 merged.lb = merged.lb.min(g.lb);
2493 merged.lr = merged.lr.max(g.lr);
2494 merged.lt = merged.lt.max(g.lt);
2495 let q = quad_of(g);
2496 if along(&q) > reach {
2497 reach = along(&q);
2498 quad[2..6].copy_from_slice(&q[2..6]);
2499 }
2500 }
2501 if merged.quad.is_some() {
2502 merged.quad = Some(quad);
2503 }
2504 out.truncate(begin);
2505 out.extend(chars.iter().map(|&ch| Glyph { ch, ..merged }));
2507}
2508
2509fn drop_overprinted_spaces(glyphs: &mut Vec<Glyph>) {
2527 if glyphs.len() < 2 {
2528 return;
2529 }
2530 let overprinted = |sp: &Glyph, next: &Glyph| {
2531 if sp.ch != ' ' || next.ch == ' ' {
2532 return false;
2533 }
2534 if sp.quad.is_some() || next.quad.is_some() {
2540 return false;
2541 }
2542 let width = sp.lr - sp.ll;
2543 if !width.is_finite() || width <= 0.0 || !next.ll.is_finite() {
2544 return false;
2545 }
2546 let same_line = next.lb < sp.lt && next.lt > sp.lb;
2549 same_line && next.ll >= sp.ll - 0.1 * width && next.ll <= sp.ll + 0.3 * width
2550 };
2551 let mut keep = vec![true; glyphs.len()];
2552 for i in 0..glyphs.len() - 1 {
2553 if overprinted(&glyphs[i], &glyphs[i + 1]) {
2554 keep[i] = false;
2555 }
2556 }
2557 let mut it = keep.into_iter();
2558 glyphs.retain(|_| it.next().unwrap_or(true));
2559}
2560
2561const TAKEN_BACK_SPACE: f32 = 0.95;
2565
2566const WORD_OVER_LETTER_SPACING: f32 = 1.5;
2569
2570fn letter_spacing_tolerance(gap: f32) -> f32 {
2574 (0.08 * gap).max(0.25)
2575}
2576
2577fn drop_letter_spacing_spaces(glyphs: &mut Vec<Glyph>) {
2609 let boxed =
2610 |g: &Glyph| g.quad.is_none() && [g.ll, g.lb, g.lr, g.lt].iter().all(|v| v.is_finite());
2611 let same_line = |a: &Glyph, b: &Glyph| b.lb < a.lt && b.lt > a.lb;
2612 let link = |i: usize| -> bool {
2615 let (Some(a), Some(sp), Some(b)) = (glyphs.get(i), glyphs.get(i + 1), glyphs.get(i + 2))
2616 else {
2617 return false;
2618 };
2619 a.ch != ' '
2620 && sp.ch == ' '
2621 && b.ch != ' '
2622 && boxed(a)
2623 && boxed(sp)
2624 && boxed(b)
2625 && sp.lr > sp.ll
2626 && same_line(a, sp)
2627 && same_line(a, b)
2628 && b.ll >= a.lr
2629 };
2630 let in_word_before = |i: usize| {
2633 i > 0
2634 && glyphs[i - 1].ch != ' '
2635 && boxed(&glyphs[i - 1])
2636 && same_line(&glyphs[i - 1], &glyphs[i])
2637 };
2638 let in_word_after = |i: usize| {
2639 glyphs
2640 .get(i + 1)
2641 .is_some_and(|n| n.ch != ' ' && boxed(n) && same_line(n, &glyphs[i]))
2642 };
2643
2644 let mut dropped: Vec<usize> = Vec::new();
2646 let mut i = 0;
2647 while i < glyphs.len() {
2648 if !link(i) {
2649 i += 1;
2650 continue;
2651 }
2652 let first = i;
2654 let mut last = i;
2655 while link(last) {
2656 last += 2;
2657 }
2658 i = last + 1;
2659 let spaces = (last - first) / 2;
2661 let gap = |k: usize| glyphs[first + 2 * k + 2].ll - glyphs[first + 2 * k].lr;
2662 let taken_back = |k: usize| {
2663 let sp = &glyphs[first + 2 * k + 1];
2664 glyphs[first + 2 * k + 2].ll - sp.ll <= TAKEN_BACK_SPACE * (sp.lr - sp.ll)
2665 };
2666 let (lo_k, hi_k) = (
2669 usize::from(in_word_before(first)),
2670 spaces - usize::from(in_word_after(last)),
2671 );
2672 if hi_k < lo_k + 3 {
2673 continue;
2674 }
2675 let letter = |k: usize| glyphs[first + 2 * k].ch.is_alphabetic();
2676
2677 let mut spacings: Vec<(f32, f32)> = Vec::new();
2680 let mut k = lo_k;
2681 while k < hi_k {
2682 if !(taken_back(k) && letter(k) && letter(k + 1)) {
2683 k += 1;
2684 continue;
2685 }
2686 let (mut lo, mut hi) = (gap(k), gap(k));
2687 let mut end = k + 1;
2688 while end < hi_k
2689 && taken_back(end)
2690 && letter(end + 1)
2691 && hi.max(gap(end)) - lo.min(gap(end)) <= letter_spacing_tolerance(lo)
2692 {
2693 lo = lo.min(gap(end));
2694 hi = hi.max(gap(end));
2695 end += 1;
2696 }
2697 let one_char = (k..=end).all(|j| glyphs[first + 2 * j].ch == glyphs[first + 2 * k].ch);
2698 if end - k >= 3 && !one_char {
2699 spacings.push((lo, hi));
2700 }
2701 k = end.max(k + 1);
2702 }
2703 if spacings.is_empty() {
2704 continue;
2705 }
2706 let spaced = |k: usize| {
2707 (lo_k..hi_k).contains(&k)
2708 && taken_back(k)
2709 && spacings.iter().any(|&(lo, hi)| {
2710 let tol = letter_spacing_tolerance(lo);
2711 gap(k) >= lo - tol && gap(k) <= hi + tol
2712 })
2713 };
2714 let widest = spacings.iter().map(|s| s.1).fold(0.0, f32::max);
2719 if (0..spaces).any(|k| !spaced(k) && gap(k) < WORD_OVER_LETTER_SPACING * widest) {
2720 continue;
2721 }
2722 dropped.extend(
2723 (lo_k..hi_k)
2724 .filter(|&k| spaced(k))
2725 .map(|k| first + 2 * k + 1),
2726 );
2727 }
2728 if dropped.is_empty() {
2729 return;
2730 }
2731 let mut keep = vec![true; glyphs.len()];
2732 for at in dropped {
2733 keep[at] = false;
2734 glyphs[at + 1].spaced = true;
2739 }
2740 let mut it = keep.into_iter();
2741 glyphs.retain(|_| it.next().unwrap_or(true));
2742}
2743
2744fn on_page(g: &Glyph, w: f32, h: f32) -> bool {
2759 const EPS: f32 = 1e-3;
2761 let (l, b, r, t) = if [g.ll, g.lb, g.lr, g.lt].iter().all(|v| v.is_finite()) {
2762 (g.ll, g.lb, g.lr, g.lt)
2763 } else {
2764 (g.l, g.b, g.r, g.t)
2765 };
2766 if ![l, b, r, t].iter().all(|v| v.is_finite()) {
2767 return true;
2768 }
2769 l >= -EPS && b >= -EPS && r <= w + EPS && t <= h + EPS
2770}
2771
2772#[allow(clippy::too_many_arguments)]
2777fn run_content(
2778 doc: &Document,
2779 res: &Dictionary,
2780 content: &lopdf::content::Content,
2781 base_ctm: Mat,
2782 init: TextState,
2783 depth: u32,
2784 caches: &mut DocCaches,
2785 out: &mut Vec<Glyph>,
2786 inks: &mut Vec<crate::checkbox::Ink>,
2787 shape_init: ShapeGs,
2788 shapes: &mut Shapes,
2789) {
2790 let fonts = fonts_from_res(doc, res, caches);
2791 let xobjects = res
2792 .get(b"XObject")
2793 .ok()
2794 .and_then(|o| deref(doc, o))
2795 .and_then(|o| o.as_dict().ok());
2796
2797 #[allow(clippy::type_complexity)]
2802 let mut gstate_stack: Vec<(Mat, f64, f64, f64, f64, f64, f64, i64, Option<&Arc<Font>>)> =
2803 Vec::new();
2804 let mut ctm = base_ctm;
2805 let mut tm = Mat::ID;
2806 let mut tlm = Mat::ID;
2807 let mut font: Option<&Arc<Font>> = None;
2808 let mut fsize = init.fsize;
2809 let mut tc = init.tc; let mut tw = init.tw; let mut th = init.th; let mut tl = init.tl; let mut trise = init.trise;
2814 let mut tr = init.tr; let op_f = |operands: &[Object], i: usize| operands.get(i).and_then(num).unwrap_or(0.0);
2817 let mut path: Vec<PathPiece> = Vec::new();
2821 let (mut cur, mut start) = ((0.0, 0.0), (0.0, 0.0));
2822 let mut fill_light = false;
2826 let mut fill_stack: Vec<bool> = Vec::new();
2827 let mut marked: Vec<(usize, Option<String>)> = Vec::new();
2830 let mut shape_gs = shape_init;
2833 let mut shape_stack: Vec<ShapeGs> = Vec::new();
2834 let mut shape_path: Vec<ShapeSub> = Vec::new();
2835 let mut clip_pending = false;
2836 let ext_gstates = res
2837 .get(b"ExtGState")
2838 .ok()
2839 .and_then(|o| deref(doc, o))
2840 .and_then(|o| o.as_dict().ok());
2841 let colorspaces = res
2842 .get(b"ColorSpace")
2843 .ok()
2844 .and_then(|o| deref(doc, o))
2845 .and_then(|o| o.as_dict().ok());
2846
2847 for op in &content.operations {
2848 let operands = &op.operands;
2849 let shown = out.len();
2850 match op.operator.as_str() {
2851 "q" => {
2852 gstate_stack.push((ctm, tc, tw, th, tl, trise, fsize, tr, font));
2853 fill_stack.push(fill_light);
2854 shape_stack.push(shape_gs.clone());
2855 }
2856 "BMC" => marked.push((out.len(), None)),
2857 "BDC" => {
2860 let actual = operands
2861 .get(1)
2862 .filter(|_| marked.len() < MAX_ACTUAL_TEXT_DEPTH)
2863 .and_then(|o| o.as_dict().ok())
2864 .and_then(|d| d.get(b"ActualText").ok())
2865 .and_then(|o| match o {
2866 Object::String(bytes, _) => Some(crate::info::decode_text(bytes)),
2867 _ => None,
2868 });
2869 marked.push((out.len(), actual));
2870 }
2871 "EMC" => {
2872 if let Some((begin, Some(text))) = marked.pop() {
2873 apply_actual_text(out, begin, &text);
2874 }
2875 continue;
2878 }
2879 "Q" => {
2880 fill_light = fill_stack.pop().unwrap_or(false);
2881 if let Some(gs) = shape_stack.pop() {
2882 shape_gs = gs;
2883 }
2884 if let Some((c, a, b, h, l, r, fs, mode, f)) = gstate_stack.pop() {
2885 ctm = c;
2886 tc = a;
2887 tw = b;
2888 th = h;
2889 tl = l;
2890 trise = r;
2891 fsize = fs;
2892 tr = mode;
2893 font = f;
2894 }
2895 }
2896 "cm" => {
2897 let m = Mat {
2898 a: op_f(operands, 0),
2899 b: op_f(operands, 1),
2900 c: op_f(operands, 2),
2901 d: op_f(operands, 3),
2902 e: op_f(operands, 4),
2903 f: op_f(operands, 5),
2904 };
2905 ctm = m.then(ctm);
2906 }
2907 "BT" => {
2908 tm = Mat::ID;
2909 tlm = Mat::ID;
2910 }
2911 "ET" => {}
2912 "Tf" => {
2913 if let Some(Object::Name(n)) = operands.first() {
2914 font = fonts.get(n.as_slice());
2915 }
2916 fsize = op_f(operands, 1);
2917 }
2918 "Td" => {
2919 tlm = Mat {
2920 a: 1.0,
2921 b: 0.0,
2922 c: 0.0,
2923 d: 1.0,
2924 e: op_f(operands, 0),
2925 f: op_f(operands, 1),
2926 }
2927 .then(tlm);
2928 tm = tlm;
2929 }
2930 "TD" => {
2931 tl = -op_f(operands, 1);
2932 tlm = Mat {
2933 a: 1.0,
2934 b: 0.0,
2935 c: 0.0,
2936 d: 1.0,
2937 e: op_f(operands, 0),
2938 f: op_f(operands, 1),
2939 }
2940 .then(tlm);
2941 tm = tlm;
2942 }
2943 "Tm" => {
2944 tlm = Mat {
2945 a: op_f(operands, 0),
2946 b: op_f(operands, 1),
2947 c: op_f(operands, 2),
2948 d: op_f(operands, 3),
2949 e: op_f(operands, 4),
2950 f: op_f(operands, 5),
2951 };
2952 tm = tlm;
2953 }
2954 "T*" => {
2955 tlm = Mat {
2956 a: 1.0,
2957 b: 0.0,
2958 c: 0.0,
2959 d: 1.0,
2960 e: 0.0,
2961 f: -tl,
2962 }
2963 .then(tlm);
2964 tm = tlm;
2965 }
2966 "Tc" => tc = op_f(operands, 0),
2967 "Tw" => tw = op_f(operands, 0),
2968 "Tz" => th = op_f(operands, 0) / 100.0,
2969 "TL" => tl = op_f(operands, 0),
2970 "Ts" => trise = op_f(operands, 0),
2971 "Tr" => tr = op_f(operands, 0) as i64,
2972 "Tj" | "'" | "\"" => {
2973 if op.operator == "'" || op.operator == "\"" {
2974 tlm = Mat {
2976 a: 1.0,
2977 b: 0.0,
2978 c: 0.0,
2979 d: 1.0,
2980 e: 0.0,
2981 f: -tl,
2982 }
2983 .then(tlm);
2984 tm = tlm;
2985 }
2986 if op.operator == "\"" {
2987 tw = op_f(operands, 0);
2990 tc = op_f(operands, 1);
2991 }
2992 if let (Some(f), Some(Object::String(s, _))) = (font, operands.last()) {
2993 let first = out.len();
2994 show_text(f, s, fsize, tc, tw, th, trise, &mut tm, ctm, out);
2995 stamp_clip(&mut out[first..], shape_gs.clip_box);
2996 }
2997 }
2998 "TJ" => {
2999 if let (Some(f), Some(Object::Array(arr))) = (font, operands.first()) {
3000 let first = out.len();
3001 for el in arr {
3002 match el {
3003 Object::String(s, _) => {
3004 show_text(f, s, fsize, tc, tw, th, trise, &mut tm, ctm, out)
3005 }
3006 other => {
3007 if let Some(adj) = num(other) {
3008 let tx = -adj / 1000.0 * fsize * th;
3010 tm = Mat {
3011 a: 1.0,
3012 b: 0.0,
3013 c: 0.0,
3014 d: 1.0,
3015 e: tx,
3016 f: 0.0,
3017 }
3018 .then(tm);
3019 }
3020 }
3021 }
3022 }
3023 stamp_clip(&mut out[first..], shape_gs.clip_box);
3024 }
3025 }
3026 "m" => {
3027 cur = ctm.apply(op_f(operands, 0), op_f(operands, 1));
3028 start = cur;
3029 shape_path.push(ShapeSub::at(cur));
3030 }
3031 "l" => {
3032 let p = ctm.apply(op_f(operands, 0), op_f(operands, 1));
3033 path.push(PathPiece::Line(cur, p));
3034 cur = p;
3035 if let Some(sub) = shape_path.last_mut() {
3036 sub.lines.push((sub.cur, p));
3037 sub.pts.push(p);
3038 sub.cur = p;
3039 }
3040 }
3041 "c" | "v" | "y" => {
3042 let pts: Vec<(f64, f64)> = (0..operands.len() / 2)
3043 .map(|k| ctm.apply(op_f(operands, 2 * k), op_f(operands, 2 * k + 1)))
3044 .collect();
3045 if let Some(&end) = pts.last() {
3046 path.push(PathPiece::Curve(
3047 std::iter::once(cur).chain(pts.iter().copied()).collect(),
3048 ));
3049 cur = end;
3050 if let Some(sub) = shape_path.last_mut() {
3051 sub.pts.extend(pts.iter().copied());
3052 sub.cur = end;
3053 }
3054 }
3055 }
3056 "h" => {
3057 if cur != start {
3058 path.push(PathPiece::Line(cur, start));
3059 }
3060 cur = start;
3061 if let Some(sub) = shape_path.last_mut() {
3064 sub.closed = true;
3065 sub.pts.push(sub.start);
3066 let at = sub.start;
3067 shape_path.push(ShapeSub::at(at));
3068 }
3069 }
3070 "re" => {
3071 let (x, y, w, h) = (
3072 op_f(operands, 0),
3073 op_f(operands, 1),
3074 op_f(operands, 2),
3075 op_f(operands, 3),
3076 );
3077 path.push(PathPiece::Rect([
3078 ctm.apply(x, y),
3079 ctm.apply(x + w, y),
3080 ctm.apply(x + w, y + h),
3081 ctm.apply(x, y + h),
3082 ]));
3083 cur = ctm.apply(x, y);
3084 start = cur;
3085 let c = [
3087 ctm.apply(x, y),
3088 ctm.apply(x + w, y),
3089 ctm.apply(x + w, y + h),
3090 ctm.apply(x, y + h),
3091 ];
3092 shape_path.push(ShapeSub {
3093 start: c[0],
3094 cur: c[3],
3095 pts: vec![c[0], c[1], c[2], c[3], c[0]],
3096 lines: vec![(c[0], c[1]), (c[1], c[2]), (c[2], c[3])],
3097 closed: true,
3098 });
3099 shape_path.push(ShapeSub::at(c[0]));
3100 }
3101 "S" | "s" | "f" | "F" | "f*" | "B" | "B*" | "b" | "b*" => {
3102 let op = op.operator.as_str();
3103 if matches!(op, "s" | "b" | "b*") && cur != start {
3104 path.push(PathPiece::Line(cur, start));
3105 }
3106 let stroke = matches!(op, "S" | "s" | "B" | "B*" | "b" | "b*");
3107 let fill = !matches!(op, "S" | "s");
3108 paint_path(&path, stroke, fill, fill_light, inks);
3109 path.clear();
3110 if !matches!(op, "S" | "B" | "B*") {
3112 if let Some(sub) = shape_path.last_mut() {
3113 sub.closed = true;
3114 }
3115 }
3116 let scale = (ctm.a * ctm.d - ctm.b * ctm.c).abs().sqrt();
3117 record_shape(
3118 &shape_path,
3119 stroke,
3120 fill,
3121 &shape_gs,
3122 if scale > 0.0 { scale } else { 1.0 },
3123 shapes,
3124 );
3125 if std::mem::take(&mut clip_pending) {
3127 capture_clip(&shape_path, &mut shape_gs);
3128 }
3129 shape_path.clear();
3130 }
3131 "n" => {
3132 path.clear();
3133 if std::mem::take(&mut clip_pending) {
3134 capture_clip(&shape_path, &mut shape_gs);
3135 }
3136 shape_path.clear();
3137 }
3138 "W" | "W*" => clip_pending = true,
3139 "w" => shape_gs.line_width = op_f(operands, 0),
3140 "gs" => {
3141 let params = operands
3142 .first()
3143 .and_then(|o| o.as_name().ok())
3144 .and_then(|n| ext_gstates?.get(n).ok())
3145 .and_then(|o| deref(doc, o))
3146 .and_then(|o| o.as_dict().ok());
3147 if let Some(params) = params {
3148 let get = |k: &[u8]| params.get(k).ok().and_then(num);
3149 if let Some(lw) = get(b"LW") {
3150 shape_gs.line_width = lw;
3151 }
3152 if let Some(a) = get(b"CA") {
3153 shape_gs.stroke_alpha = a;
3154 }
3155 if let Some(a) = get(b"ca") {
3156 shape_gs.fill_alpha = a;
3157 }
3158 }
3159 }
3160 "g" | "rg" | "k" | "sc" | "scn" => {
3163 if matches!(op.operator.as_str(), "scn")
3166 && matches!(operands.last(), Some(Object::Name(_)))
3167 {
3168 shape_gs.fill_pattern = true;
3169 } else if !operands.is_empty() {
3170 shape_gs.fill_pattern = false;
3171 }
3172 let v: Vec<f64> = operands
3173 .iter()
3174 .map(num)
3175 .collect::<Option<_>>()
3176 .unwrap_or_default();
3177 fill_light = match v.as_slice() {
3178 [g] => *g >= 0.9,
3179 [r, g, b] => r.min(*g).min(*b) >= 0.9,
3180 [c, m, y, k] => c.max(*m).max(*y).max(*k) <= 0.1,
3181 _ => false,
3182 };
3183 }
3184 "cs" => {
3185 fill_light = false;
3186 let pattern = match operands.first() {
3188 Some(Object::Name(n)) if n.as_slice() == b"Pattern" => true,
3189 Some(Object::Name(n)) => colorspaces
3190 .and_then(|cs| cs.get(n).ok())
3191 .and_then(|o| deref(doc, o))
3192 .is_some_and(|o| match o {
3193 Object::Name(f) => f.as_slice() == b"Pattern",
3194 Object::Array(a) => a
3195 .first()
3196 .and_then(|f| f.as_name().ok())
3197 .is_some_and(|f| f == b"Pattern"),
3198 _ => false,
3199 }),
3200 _ => false,
3201 };
3202 if pattern {
3203 shape_gs.fill_pattern = true;
3204 }
3205 }
3206 "BI" => inks.push(image_ink(ctm)),
3208 "Do" => {
3209 if depth >= 8 {
3213 continue;
3214 }
3215 let Some(Object::Name(n)) = operands.first() else {
3216 continue;
3217 };
3218 let obj = xobjects.and_then(|d| d.get(n.as_slice()).ok());
3219 let form_id = match obj {
3220 Some(Object::Reference(id)) => Some(*id),
3221 _ => None,
3222 };
3223 let stream = obj
3224 .and_then(|o| deref(doc, o))
3225 .and_then(|o| o.as_stream().ok());
3226 let Some(stream) = stream else { continue };
3227 let is_form = stream
3228 .dict
3229 .get(b"Subtype")
3230 .ok()
3231 .and_then(|o| o.as_name().ok())
3232 == Some(b"Form".as_slice());
3233 if !is_form {
3234 let is_image = stream
3235 .dict
3236 .get(b"Subtype")
3237 .ok()
3238 .and_then(|o| o.as_name().ok())
3239 == Some(b"Image".as_slice());
3240 if is_image {
3241 inks.push(image_ink(ctm));
3242 }
3243 continue;
3244 }
3245 let cached = form_id.and_then(|id| caches.forms.get(&id).cloned());
3249 let form_content = match cached {
3250 Some(c) => c,
3251 None => {
3252 let Some(data) = content_stream_bytes(stream) else {
3253 continue;
3254 };
3255 let Ok(c) = lopdf::content::Content::decode(&data) else {
3256 continue;
3257 };
3258 let c = Arc::new(c);
3259 if let Some(id) = form_id {
3260 if !caches.forms_seen.insert(id) {
3261 caches.forms.insert(id, Arc::clone(&c));
3262 }
3263 }
3264 c
3265 }
3266 };
3267 let form_mat = match stream.dict.get(b"Matrix").ok() {
3269 Some(Object::Array(a)) if a.len() == 6 => {
3270 let v: Vec<f64> = a.iter().filter_map(num).collect();
3271 if v.len() == 6 {
3272 Mat {
3273 a: v[0],
3274 b: v[1],
3275 c: v[2],
3276 d: v[3],
3277 e: v[4],
3278 f: v[5],
3279 }
3280 } else {
3281 Mat::ID
3282 }
3283 }
3284 _ => Mat::ID,
3285 };
3286 let form_res = stream
3288 .dict
3289 .get(b"Resources")
3290 .ok()
3291 .and_then(|o| deref(doc, o))
3292 .and_then(|o| o.as_dict().ok())
3293 .unwrap_or(res);
3294 let state = TextState {
3295 tc,
3296 tw,
3297 th,
3298 tl,
3299 trise,
3300 fsize,
3301 tr,
3302 };
3303 run_content(
3304 doc,
3305 form_res,
3306 &form_content,
3307 form_mat.then(ctm),
3308 state,
3309 depth + 1,
3310 caches,
3311 out,
3312 inks,
3313 shape_gs.clone(),
3314 shapes,
3315 );
3316 }
3317 _ => {}
3318 }
3319 if matches!(tr, 3 | 7) {
3322 for g in &mut out[shown..] {
3323 g.invisible = true;
3324 }
3325 }
3326 }
3327}
3328
3329fn image_ink(ctm: Mat) -> crate::checkbox::Ink {
3332 let pts = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)].map(|(x, y)| ctm.apply(x, y));
3333 let (mut l, mut b, mut r, mut t) = (
3334 f64::INFINITY,
3335 f64::INFINITY,
3336 f64::NEG_INFINITY,
3337 f64::NEG_INFINITY,
3338 );
3339 for (x, y) in pts {
3340 (l, b, r, t) = (l.min(x), b.min(y), r.max(x), t.max(y));
3341 }
3342 crate::checkbox::Ink::Bitmap { l, b, r, t }
3343}
3344
3345#[derive(Default, Clone, Debug, PartialEq)]
3353pub(crate) struct Shapes {
3354 pub lines: Vec<[f64; 4]>,
3355 pub boxes: Vec<[f64; 4]>,
3356}
3357
3358const MAX_SHAPE_BOXES: usize = 10_000;
3363
3364struct ShapeSub {
3367 start: (f64, f64),
3368 cur: (f64, f64),
3369 pts: Vec<(f64, f64)>,
3372 lines: Vec<((f64, f64), (f64, f64))>,
3374 closed: bool,
3375}
3376
3377impl ShapeSub {
3378 fn at(p: (f64, f64)) -> Self {
3379 ShapeSub {
3380 start: p,
3381 cur: p,
3382 pts: vec![p],
3383 lines: Vec::new(),
3384 closed: false,
3385 }
3386 }
3387
3388 fn kept(&self) -> bool {
3391 let Some((l, b, r, t)) = bbox_of(&self.pts) else {
3392 return false;
3393 };
3394 self.pts.len() >= 2 && (r - l).powi(2) + (t - b).powi(2) >= 1e-3
3395 }
3396}
3397
3398fn bbox_of(pts: &[(f64, f64)]) -> Option<(f64, f64, f64, f64)> {
3399 let (&first, rest) = pts.split_first()?;
3400 Some(rest.iter().fold(
3401 (first.0, first.1, first.0, first.1),
3402 |(l, b, r, t), &(x, y)| (l.min(x), b.min(y), r.max(x), t.max(y)),
3403 ))
3404}
3405
3406#[derive(Clone)]
3411struct ShapeGs {
3412 line_width: f64,
3413 stroke_alpha: f64,
3414 fill_alpha: f64,
3415 fill_pattern: bool,
3416 clips: Vec<[f64; 4]>,
3417 clip_box: Option<[f64; 4]>,
3422}
3423
3424impl ShapeGs {
3425 const INIT: ShapeGs = ShapeGs {
3426 line_width: 1.0,
3427 stroke_alpha: 1.0,
3428 fill_alpha: 1.0,
3429 fill_pattern: false,
3430 clips: Vec::new(),
3431 clip_box: None,
3432 };
3433}
3434
3435fn stamp_clip(glyphs: &mut [Glyph], clip: Option<[f64; 4]>) {
3437 let clip = clip.map(|c| c.map(|v| v as f32));
3438 for g in glyphs {
3439 g.clip = clip;
3440 }
3441}
3442
3443fn boxes_intersect(a: [f64; 4], b: [f64; 4]) -> bool {
3446 a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1]
3447}
3448
3449fn clipped(mut bbox: [f64; 4], clips: &[[f64; 4]]) -> Option<[f64; 4]> {
3452 for c in clips {
3453 if !boxes_intersect(bbox, *c) {
3454 return None;
3455 }
3456 bbox = [
3457 bbox[0].max(c[0]),
3458 bbox[1].max(c[1]),
3459 bbox[2].min(c[2]),
3460 bbox[3].min(c[3]),
3461 ];
3462 }
3463 Some(bbox)
3464}
3465
3466fn shape_line(a: (f64, f64), z: (f64, f64), clips: &[[f64; 4]], out: &mut Vec<[f64; 4]>) {
3471 const TOL: f64 = 1e-3;
3472 let horizontal = (z.1 - a.1).abs() <= TOL;
3473 let vertical = (z.0 - a.0).abs() <= TOL;
3474 if horizontal == vertical {
3475 return;
3476 }
3477 let mut bbox = [a.0.min(z.0), a.1.min(z.1), a.0.max(z.0), a.1.max(z.1)];
3478 for c in clips {
3479 if horizontal {
3480 if a.1 < c[1] - TOL || a.1 > c[3] + TOL {
3481 return;
3482 }
3483 bbox[0] = bbox[0].max(c[0]);
3484 bbox[2] = bbox[2].min(c[2]);
3485 if bbox[0] > bbox[2] + TOL {
3486 return;
3487 }
3488 } else {
3489 if a.0 < c[0] - TOL || a.0 > c[2] + TOL {
3490 return;
3491 }
3492 bbox[1] = bbox[1].max(c[1]);
3493 bbox[3] = bbox[3].min(c[3]);
3494 if bbox[1] > bbox[3] + TOL {
3495 return;
3496 }
3497 }
3498 }
3499 out.push(bbox);
3500}
3501
3502fn capture_clip(subs: &[ShapeSub], gs: &mut ShapeGs) {
3510 let mut group: Option<[f64; 4]> = None;
3511 for sub in subs.iter().filter(|s| s.pts.len() >= 2) {
3512 if let Some((l, b, r, t)) = bbox_of(&sub.pts) {
3513 gs.clips.push([l, b, r, t]);
3514 group = Some(match group {
3515 None => [l, b, r, t],
3516 Some(g) => [g[0].min(l), g[1].min(b), g[2].max(r), g[3].max(t)],
3517 });
3518 }
3519 }
3520 if let Some(g) = group {
3521 gs.clip_box = Some(match gs.clip_box {
3522 None => g,
3523 Some(c) => {
3524 let (x0, y0) = (c[0].max(g[0]), c[1].max(g[1]));
3525 [x0, y0, c[2].min(g[2]).max(x0), c[3].min(g[3]).max(y0)]
3527 }
3528 });
3529 }
3530}
3531
3532fn record_shape(
3539 subs: &[ShapeSub],
3540 stroke: bool,
3541 fill: bool,
3542 gs: &ShapeGs,
3543 scale: f64,
3544 shapes: &mut Shapes,
3545) {
3546 let kept: Vec<&ShapeSub> = subs.iter().filter(|s| s.kept()).collect();
3547 if kept.is_empty() {
3548 return;
3549 }
3550 let fill = fill && !gs.fill_pattern;
3551 if gs.fill_pattern && !stroke {
3552 return;
3553 }
3554 let strokes_visible = stroke && gs.stroke_alpha > 0.0;
3555 let visible = strokes_visible || (fill && gs.fill_alpha > 0.0);
3556 if strokes_visible {
3557 for sub in &kept {
3558 for &(a, z) in &sub.lines {
3559 shape_line(a, z, &gs.clips, &mut shapes.lines);
3560 }
3561 if sub.closed {
3562 shape_line(sub.cur, sub.start, &gs.clips, &mut shapes.lines);
3563 }
3564 }
3565 }
3566 if visible {
3567 let pts: Vec<(f64, f64)> = kept.iter().flat_map(|s| s.pts.iter().copied()).collect();
3568 if let Some((l, b, r, t)) = bbox_of(&pts) {
3569 let pad = if strokes_visible {
3570 (gs.line_width * scale).max(0.0) * 0.5
3571 } else {
3572 0.0
3573 };
3574 if let Some(bbox) = clipped([l - pad, b - pad, r + pad, t + pad], &gs.clips) {
3575 shapes.boxes.push(bbox);
3576 }
3577 }
3578 }
3579}
3580
3581fn connected_boxes(boxes: &[[f64; 4]]) -> Vec<[f64; 4]> {
3588 let touches =
3589 |a: [f64; 4], b: [f64; 4]| a[0] <= b[2] && a[2] >= b[0] && a[1] <= b[3] && a[3] >= b[1];
3590 let mut taken = vec![false; boxes.len()];
3591 let mut out = Vec::new();
3592 for i in 0..boxes.len() {
3593 if taken[i] {
3594 continue;
3595 }
3596 taken[i] = true;
3597 let mut component = boxes[i];
3598 let mut changed = true;
3599 while changed {
3600 changed = false;
3601 for j in 0..boxes.len() {
3602 if !taken[j] && touches(component, boxes[j]) {
3603 let b = boxes[j];
3604 component = [
3605 component[0].min(b[0]),
3606 component[1].min(b[1]),
3607 component[2].max(b[2]),
3608 component[3].max(b[3]),
3609 ];
3610 taken[j] = true;
3611 changed = true;
3612 }
3613 }
3614 }
3615 out.push(component);
3616 }
3617 out
3618}
3619
3620enum PathPiece {
3622 Line((f64, f64), (f64, f64)),
3623 Rect([(f64, f64); 4]),
3625 Curve(Vec<(f64, f64)>),
3627}
3628
3629fn paint_path(
3637 path: &[PathPiece],
3638 stroke: bool,
3639 fill: bool,
3640 fill_light: bool,
3641 inks: &mut Vec<crate::checkbox::Ink>,
3642) {
3643 use crate::checkbox::Ink;
3644 let bbox = |pts: &mut dyn Iterator<Item = (f64, f64)>| {
3645 pts.fold(
3646 (
3647 f64::INFINITY,
3648 f64::INFINITY,
3649 f64::NEG_INFINITY,
3650 f64::NEG_INFINITY,
3651 ),
3652 |(l, b, r, t), (x, y)| (l.min(x), b.min(y), r.max(x), t.max(y)),
3653 )
3654 };
3655 let mut keep = |ink: Ink| {
3656 if ink.worth_keeping() {
3657 inks.push(ink);
3658 }
3659 };
3660 if fill && !fill_light {
3661 let (l, b, r, t) = bbox(&mut path.iter().flat_map(|p| match p {
3665 PathPiece::Line(a, z) => vec![*a, *z],
3666 PathPiece::Rect(c) => c.to_vec(),
3667 PathPiece::Curve(c) => c.clone(),
3668 }));
3669 if l.is_finite() {
3670 keep(Ink::Blot { l, b, r, t });
3671 }
3672 return;
3673 }
3674 if !stroke {
3675 return;
3676 }
3677 for piece in path {
3678 match piece {
3679 PathPiece::Line(a, z) => keep(Ink::Seg {
3680 x0: a.0,
3681 y0: a.1,
3682 x1: z.0,
3683 y1: z.1,
3684 }),
3685 PathPiece::Rect(c) => {
3686 let axis = ((c[0].1 - c[1].1).abs() < 1e-6 && (c[1].0 - c[2].0).abs() < 1e-6)
3687 || ((c[0].0 - c[1].0).abs() < 1e-6 && (c[1].1 - c[2].1).abs() < 1e-6);
3688 if axis {
3689 let (l, b, r, t) = bbox(&mut c.iter().copied());
3690 keep(Ink::Rect { l, b, r, t });
3691 } else {
3692 for k in 0..4 {
3693 let (a, z) = (c[k], c[(k + 1) % 4]);
3694 keep(Ink::Seg {
3695 x0: a.0,
3696 y0: a.1,
3697 x1: z.0,
3698 y1: z.1,
3699 });
3700 }
3701 }
3702 }
3703 PathPiece::Curve(c) => {
3704 let (l, b, r, t) = bbox(&mut c.iter().copied());
3705 keep(Ink::Blot { l, b, r, t });
3706 }
3707 }
3708 }
3709}
3710
3711#[allow(clippy::too_many_arguments)]
3712fn show_text(
3713 font: &Font,
3714 bytes: &[u8],
3715 fsize: f64,
3716 tc: f64,
3717 tw: f64,
3718 th: f64,
3719 trise: f64,
3720 tm: &mut Mat,
3721 ctm: Mat,
3722 out: &mut Vec<Glyph>,
3723) {
3724 for code in codes(font, bytes) {
3725 let (text, w, blank) = font.decode_code(code);
3726 let w0 = w / 1000.0; let scale = Mat {
3729 a: fsize * th,
3730 b: 0.0,
3731 c: 0.0,
3732 d: fsize,
3733 e: 0.0,
3734 f: trise,
3735 };
3736 let trm = scale.then(*tm).then(ctm);
3737 let (desc, asc) = if blank {
3741 (0.0, 0.0)
3742 } else if let Some(&(lo, hi)) = font.ink_y.get(&code) {
3743 (lo / 1000.0, hi / 1000.0)
3744 } else {
3745 (font.descent / 1000.0, font.ascent / 1000.0)
3746 };
3747 let (x0, y0) = trm.apply(0.0, desc);
3748 let (x1, y1) = trm.apply(w0, desc);
3749 let (x2, y2) = trm.apply(w0, asc);
3750 let (x3, y3) = trm.apply(0.0, asc);
3751 let exact = {
3752 use std::hash::{Hash, Hasher};
3753 let mut h = std::collections::hash_map::DefaultHasher::new();
3754 [x0, y0, x1, y1, x2, y2, x3, y3]
3755 .map(f64::to_bits)
3756 .hash(&mut h);
3757 h.finish()
3758 };
3759 let upright = trm.a > 0.0 && trm.b.abs() <= 1e-6 * trm.a;
3767 let (left, bot, right, top, quad) = if upright {
3768 (x0.min(x1), y0.min(y3), x0.max(x1), y0.max(y3), None)
3769 } else {
3770 let (xs, ys) = ([x0, x1, x2, x3], [y0, y1, y2, y3]);
3771 let fold = |v: [f64; 4], f: fn(f64, f64) -> f64| v.into_iter().reduce(f).unwrap();
3772 let q = [x0, y0, x1, y1, x2, y2, x3, y3].map(|v| v as f32);
3773 (
3774 fold(xs, f64::min),
3775 fold(ys, f64::min),
3776 fold(xs, f64::max),
3777 fold(ys, f64::max),
3778 Some(q),
3779 )
3780 };
3781 let (ox, oy) = trm.apply(0.0, 0.0);
3785 let (sx, sy) = trm.apply(0.0, 1.0);
3786 let pen = Some([ox as f32, oy as f32, (sx - ox).hypot(sy - oy) as f32]);
3787 if let Some(s) = text {
3788 for ch in s.chars() {
3790 let ch = if ch == '\u{0}' { '\u{FFFD}' } else { ch };
3793 out.push(Glyph {
3794 ch,
3795 l: left as f32,
3796 b: bot as f32,
3797 r: right as f32,
3798 t: top as f32,
3799 ll: left as f32,
3800 lb: bot as f32,
3801 lr: right as f32,
3802 lt: top as f32,
3803 font: font.hash,
3804 quad,
3805 pen,
3806 math_font: font.math,
3807 invisible: false,
3808 spaced: false,
3809 clip: None,
3810 exact,
3811 });
3812 }
3813 }
3814 let is_space = !font.two_byte && code == 32;
3816 let tx = (w0 * fsize + tc + if is_space { tw } else { 0.0 }) * th;
3817 *tm = Mat {
3818 a: 1.0,
3819 b: 0.0,
3820 c: 0.0,
3821 d: 1.0,
3822 e: tx,
3823 f: 0.0,
3824 }
3825 .then(*tm);
3826 }
3827}
3828
3829fn simple_encoding_table(doc: &Document, fdict: &Dictionary) -> HashMap<u8, char> {
3834 let enc = fdict.get(b"Encoding").ok().and_then(|o| deref(doc, o));
3835 let base_name = match enc {
3836 Some(Object::Name(n)) => n.clone(),
3837 Some(Object::Dictionary(d)) => d
3838 .get(b"BaseEncoding")
3839 .ok()
3840 .and_then(|o| o.as_name().ok())
3841 .map(|n| n.to_vec())
3842 .unwrap_or_default(),
3843 _ => Vec::new(),
3844 };
3845 let face = || {
3846 let font_name = sanitizer_font_name(doc, fdict, false);
3847 let base = fdict.get(b"BaseFont").ok().and_then(|o| o.as_name().ok());
3848 let names: Vec<&[u8]> = std::iter::once(font_name.as_slice()).chain(base).collect();
3849 crate::symbol_fonts::symbol_face(&names)
3850 };
3851 let mut m = if base_name == b"MacRomanEncoding" {
3852 macroman_table()
3853 } else if base_name == b"StandardEncoding" || base_name == b"MacExpertEncoding" {
3854 named_table(crate::encodings::by_name(&base_name).unwrap_or_default())
3857 } else if let Some(face) = base_name.is_empty().then(face).flatten() {
3858 crate::symbol_fonts::face_table(face)
3864 } else if base_name.is_empty() {
3865 tex_math_builtin(fdict).unwrap_or_else(|| {
3877 if implied_standard_encoding(doc, fdict) {
3878 named_table(crate::encodings::STANDARD)
3879 } else {
3880 winansi_table()
3881 }
3882 })
3883 } else if base_name == b"WinAnsiEncoding" {
3884 let mut m = winansi_table();
3885 for b in [0x7Fu8, 0x81, 0x8D, 0x8F, 0x90, 0x9D] {
3893 m.insert(b, '\u{2022}');
3894 }
3895 m
3896 } else {
3897 winansi_table()
3898 };
3899 if let Some(latin) = crate::encodings::by_name(&base_name) {
3906 if let Some(face) = face() {
3907 let face_glyphs = match face {
3908 crate::symbol_fonts::SymbolFace::Symbol => crate::encodings::SYMBOL,
3909 crate::symbol_fonts::SymbolFace::ZapfDingbats => crate::encodings::ZAPF_DINGBATS,
3910 };
3911 let has = |n: &str| face_glyphs.iter().any(|&(_, g)| g == n);
3912 for code in 0..=255u8 {
3913 if crate::encodings::lookup(latin, code).is_some_and(has) {
3914 continue;
3915 }
3916 if let Some(ch) = crate::symbol_fonts::face_text(face, code) {
3917 m.insert(code, ch);
3918 }
3919 }
3920 }
3921 }
3922 if let Some(Object::Dictionary(d)) = enc {
3924 if let Some(Object::Array(diffs)) = d.get(b"Differences").ok().and_then(|o| deref(doc, o)) {
3925 let mut code = 0u8;
3926 for el in diffs {
3927 match el {
3928 Object::Integer(i) => code = *i as u8,
3929 Object::Name(name) => {
3930 if let Some(ch) = glyph_name_to_char(name) {
3931 m.insert(code, ch);
3932 }
3933 code = code.wrapping_add(1);
3934 }
3935 _ => {}
3936 }
3937 }
3938 }
3939 }
3940 m
3941}
3942
3943fn named_table(table: &[(u8, &str)]) -> HashMap<u8, char> {
3945 table
3946 .iter()
3947 .filter_map(|&(c, n)| glyph_name_to_char(n.as_bytes()).map(|ch| (c, ch)))
3948 .collect()
3949}
3950
3951fn implied_standard_encoding(doc: &Document, fdict: &Dictionary) -> bool {
3954 let type1 = matches!(
3955 fdict.get(b"Subtype").ok().and_then(|o| o.as_name().ok()),
3956 Some(b"Type1" | b"MMType1")
3957 );
3958 let symbolic = fdict
3959 .get(b"FontDescriptor")
3960 .ok()
3961 .and_then(|o| as_dict(doc, o))
3962 .and_then(|fd| fd.get(b"Flags").ok())
3963 .and_then(|o| deref(doc, o))
3964 .and_then(num)
3965 .is_some_and(|f| (f as i64) & 4 != 0);
3966 type1 && !symbolic
3967}
3968
3969fn tex_math_builtin(fdict: &Dictionary) -> Option<HashMap<u8, char>> {
3975 const CMSY: [char; 128] = [
3976 '−', '·', '×', '∗', '÷', '⋄', '±', '∓', '⊕', '⊖', '⊗', '⊘', '⊙', '◯', '∘', '•', '≍', '≡',
3977 '⊆', '⊇', '≤', '≥', '≼', '≽', '∼', '≈', '⊂', '⊃', '≪', '≫', '≺', '≻', '←', '→', '↑', '↓',
3978 '↔', '↗', '↘', '≃', '⇐', '⇒', '⇑', '⇓', '⇔', '↖', '↙', '∝', '′', '∞', '∈', '∋', '△', '▽',
3979 '\u{338}', '↦', '∀', '∃', '¬', '∅', 'ℜ', 'ℑ', '⊤', '⊥', 'ℵ', 'A', 'B', 'C', 'D', 'E', 'F',
3980 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
3981 'Y', 'Z', '∪', '∩', '⊎', '∧', '∨', '⊢', '⊣', '⌊', '⌋', '⌈', '⌉', '{', '}', '⟨', '⟩', '|',
3982 '∥', '↕', '⇕', '\\', '≀', '√', '∐', '∇', '∫', '⊔', '⊓', '⊑', '⊒', '§', '†', '‡', '¶', '♣',
3983 '♢', '♡', '♠',
3984 ];
3985 const CMMI: [char; 128] = [
3986 'Γ', 'Δ', 'Θ', 'Λ', 'Ξ', 'Π', 'Σ', 'Υ', 'Φ', 'Ψ', 'Ω', 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η',
3987 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'π', 'ρ', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω', 'ϵ', 'ϑ',
3988 'ϖ', 'ϱ', 'ς', 'ϕ', '↼', '↽', '⇀', '⇁', '↩', '↪', '▷', '◁', '0', '1', '2', '3', '4', '5',
3989 '6', '7', '8', '9', '.', ',', '<', '/', '>', '⋆', '∂', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
3990 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
3991 'Z', '♭', '♮', '♯', '⌣', '⌢', 'ℓ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
3992 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'ı', 'ȷ', '℘',
3993 '\u{20d7}', '⁀',
3994 ];
3995 let name = base_font_name(fdict)?;
3996 let up = name.to_ascii_uppercase();
3997 let table: &[char; 128] = if up.starts_with(b"CMSY") || up.starts_with(b"CMBSY") {
3998 &CMSY
3999 } else if up.starts_with(b"CMMI") {
4000 &CMMI
4001 } else {
4002 return None;
4003 };
4004 Some(
4005 table
4006 .iter()
4007 .enumerate()
4008 .map(|(i, &c)| (i as u8, c))
4009 .collect(),
4010 )
4011}
4012
4013const AGL_LATIN: &[(&str, char)] = &[
4021 ("AE", '\u{00C6}'),
4022 ("Aacute", '\u{00C1}'),
4023 ("Abreve", '\u{0102}'),
4024 ("Acircumflex", '\u{00C2}'),
4025 ("Adieresis", '\u{00C4}'),
4026 ("Agrave", '\u{00C0}'),
4027 ("Amacron", '\u{0100}'),
4028 ("Aogonek", '\u{0104}'),
4029 ("Aring", '\u{00C5}'),
4030 ("Atilde", '\u{00C3}'),
4031 ("Cacute", '\u{0106}'),
4032 ("Ccaron", '\u{010C}'),
4033 ("Ccedilla", '\u{00C7}'),
4034 ("Ccircumflex", '\u{0108}'),
4035 ("Cdotaccent", '\u{010A}'),
4036 ("Dcaron", '\u{010E}'),
4037 ("Dcroat", '\u{0110}'),
4038 ("Eacute", '\u{00C9}'),
4039 ("Ebreve", '\u{0114}'),
4040 ("Ecaron", '\u{011A}'),
4041 ("Ecircumflex", '\u{00CA}'),
4042 ("Edieresis", '\u{00CB}'),
4043 ("Edotaccent", '\u{0116}'),
4044 ("Egrave", '\u{00C8}'),
4045 ("Emacron", '\u{0112}'),
4046 ("Eng", '\u{014A}'),
4047 ("Eogonek", '\u{0118}'),
4048 ("Eth", '\u{00D0}'),
4049 ("Euro", '\u{20AC}'),
4050 ("Gbreve", '\u{011E}'),
4051 ("Gcircumflex", '\u{011C}'),
4052 ("Gcommaaccent", '\u{0122}'),
4053 ("Gdotaccent", '\u{0120}'),
4054 ("Hbar", '\u{0126}'),
4055 ("Hcircumflex", '\u{0124}'),
4056 ("IJ", '\u{0132}'),
4057 ("Iacute", '\u{00CD}'),
4058 ("Ibreve", '\u{012C}'),
4059 ("Icircumflex", '\u{00CE}'),
4060 ("Idieresis", '\u{00CF}'),
4061 ("Idotaccent", '\u{0130}'),
4062 ("Igrave", '\u{00CC}'),
4063 ("Imacron", '\u{012A}'),
4064 ("Iogonek", '\u{012E}'),
4065 ("Itilde", '\u{0128}'),
4066 ("Jcircumflex", '\u{0134}'),
4067 ("Kcommaaccent", '\u{0136}'),
4068 ("Lacute", '\u{0139}'),
4069 ("Lcaron", '\u{013D}'),
4070 ("Lcommaaccent", '\u{013B}'),
4071 ("Ldot", '\u{013F}'),
4072 ("Lslash", '\u{0141}'),
4073 ("Nacute", '\u{0143}'),
4074 ("Ncaron", '\u{0147}'),
4075 ("Ncommaaccent", '\u{0145}'),
4076 ("Ntilde", '\u{00D1}'),
4077 ("OE", '\u{0152}'),
4078 ("Oacute", '\u{00D3}'),
4079 ("Obreve", '\u{014E}'),
4080 ("Ocircumflex", '\u{00D4}'),
4081 ("Odieresis", '\u{00D6}'),
4082 ("Ograve", '\u{00D2}'),
4083 ("Ohungarumlaut", '\u{0150}'),
4084 ("Omacron", '\u{014C}'),
4085 ("Oslash", '\u{00D8}'),
4086 ("Otilde", '\u{00D5}'),
4087 ("Racute", '\u{0154}'),
4088 ("Rcaron", '\u{0158}'),
4089 ("Rcommaaccent", '\u{0156}'),
4090 ("Sacute", '\u{015A}'),
4091 ("Scaron", '\u{0160}'),
4092 ("Scedilla", '\u{015E}'),
4093 ("Scircumflex", '\u{015C}'),
4094 ("Scommaaccent", '\u{0218}'),
4095 ("Tbar", '\u{0166}'),
4096 ("Tcaron", '\u{0164}'),
4097 ("Tcommaaccent", '\u{0162}'),
4098 ("Thorn", '\u{00DE}'),
4099 ("Uacute", '\u{00DA}'),
4100 ("Ubreve", '\u{016C}'),
4101 ("Ucircumflex", '\u{00DB}'),
4102 ("Udieresis", '\u{00DC}'),
4103 ("Ugrave", '\u{00D9}'),
4104 ("Uhungarumlaut", '\u{0170}'),
4105 ("Umacron", '\u{016A}'),
4106 ("Uogonek", '\u{0172}'),
4107 ("Uring", '\u{016E}'),
4108 ("Utilde", '\u{0168}'),
4109 ("Wcircumflex", '\u{0174}'),
4110 ("Yacute", '\u{00DD}'),
4111 ("Ycircumflex", '\u{0176}'),
4112 ("Ydieresis", '\u{0178}'),
4113 ("Zacute", '\u{0179}'),
4114 ("Zcaron", '\u{017D}'),
4115 ("Zdotaccent", '\u{017B}'),
4116 ("aacute", '\u{00E1}'),
4117 ("abreve", '\u{0103}'),
4118 ("acircumflex", '\u{00E2}'),
4119 ("acute", '\u{00B4}'),
4120 ("adieresis", '\u{00E4}'),
4121 ("ae", '\u{00E6}'),
4122 ("agrave", '\u{00E0}'),
4123 ("amacron", '\u{0101}'),
4124 ("aogonek", '\u{0105}'),
4125 ("aring", '\u{00E5}'),
4126 ("atilde", '\u{00E3}'),
4127 ("brokenbar", '\u{00A6}'),
4128 ("cacute", '\u{0107}'),
4129 ("ccaron", '\u{010D}'),
4130 ("ccedilla", '\u{00E7}'),
4131 ("ccircumflex", '\u{0109}'),
4132 ("cdotaccent", '\u{010B}'),
4133 ("cedilla", '\u{00B8}'),
4134 ("cent", '\u{00A2}'),
4135 ("currency", '\u{00A4}'),
4136 ("dcaron", '\u{010F}'),
4137 ("dcroat", '\u{0111}'),
4138 ("dieresis", '\u{00A8}'),
4139 ("dotlessi", '\u{0131}'),
4140 ("eacute", '\u{00E9}'),
4141 ("ebreve", '\u{0115}'),
4142 ("ecaron", '\u{011B}'),
4143 ("ecircumflex", '\u{00EA}'),
4144 ("edieresis", '\u{00EB}'),
4145 ("edotaccent", '\u{0117}'),
4146 ("egrave", '\u{00E8}'),
4147 ("emacron", '\u{0113}'),
4148 ("eng", '\u{014B}'),
4149 ("eogonek", '\u{0119}'),
4150 ("eth", '\u{00F0}'),
4151 ("exclamdown", '\u{00A1}'),
4152 ("florin", '\u{0192}'),
4153 ("gbreve", '\u{011F}'),
4154 ("gcircumflex", '\u{011D}'),
4155 ("gcommaaccent", '\u{0123}'),
4156 ("gdotaccent", '\u{0121}'),
4157 ("germandbls", '\u{00DF}'),
4158 ("guillemotleft", '\u{00AB}'),
4159 ("guillemotright", '\u{00BB}'),
4160 ("hbar", '\u{0127}'),
4161 ("hcircumflex", '\u{0125}'),
4162 ("iacute", '\u{00ED}'),
4163 ("ibreve", '\u{012D}'),
4164 ("icircumflex", '\u{00EE}'),
4165 ("idieresis", '\u{00EF}'),
4166 ("igrave", '\u{00EC}'),
4167 ("ij", '\u{0133}'),
4168 ("imacron", '\u{012B}'),
4169 ("iogonek", '\u{012F}'),
4170 ("itilde", '\u{0129}'),
4171 ("jcircumflex", '\u{0135}'),
4172 ("kcommaaccent", '\u{0137}'),
4173 ("kgreenlandic", '\u{0138}'),
4174 ("lacute", '\u{013A}'),
4175 ("lcaron", '\u{013E}'),
4176 ("lcommaaccent", '\u{013C}'),
4177 ("ldot", '\u{0140}'),
4178 ("logicalnot", '\u{00AC}'),
4179 ("longs", '\u{017F}'),
4180 ("lslash", '\u{0142}'),
4181 ("macron", '\u{00AF}'),
4182 ("nacute", '\u{0144}'),
4183 ("napostrophe", '\u{0149}'),
4184 ("ncaron", '\u{0148}'),
4185 ("ncommaaccent", '\u{0146}'),
4186 ("ntilde", '\u{00F1}'),
4187 ("oacute", '\u{00F3}'),
4188 ("obreve", '\u{014F}'),
4189 ("ocircumflex", '\u{00F4}'),
4190 ("odieresis", '\u{00F6}'),
4191 ("oe", '\u{0153}'),
4192 ("ograve", '\u{00F2}'),
4193 ("ohungarumlaut", '\u{0151}'),
4194 ("omacron", '\u{014D}'),
4195 ("onehalf", '\u{00BD}'),
4196 ("onequarter", '\u{00BC}'),
4197 ("onesuperior", '\u{00B9}'),
4198 ("ordfeminine", '\u{00AA}'),
4199 ("ordmasculine", '\u{00BA}'),
4200 ("oslash", '\u{00F8}'),
4201 ("otilde", '\u{00F5}'),
4202 ("paragraph", '\u{00B6}'),
4203 ("questiondown", '\u{00BF}'),
4204 ("racute", '\u{0155}'),
4205 ("rcaron", '\u{0159}'),
4206 ("rcommaaccent", '\u{0157}'),
4207 ("sacute", '\u{015B}'),
4208 ("scaron", '\u{0161}'),
4209 ("scedilla", '\u{015F}'),
4210 ("scircumflex", '\u{015D}'),
4211 ("scommaaccent", '\u{0219}'),
4212 ("section", '\u{00A7}'),
4213 ("sfthyphen", '\u{00AD}'),
4214 ("sterling", '\u{00A3}'),
4215 ("tbar", '\u{0167}'),
4216 ("tcaron", '\u{0165}'),
4217 ("tcommaaccent", '\u{0163}'),
4218 ("thorn", '\u{00FE}'),
4219 ("threequarters", '\u{00BE}'),
4220 ("threesuperior", '\u{00B3}'),
4221 ("twosuperior", '\u{00B2}'),
4222 ("uacute", '\u{00FA}'),
4223 ("ubreve", '\u{016D}'),
4224 ("ucircumflex", '\u{00FB}'),
4225 ("udieresis", '\u{00FC}'),
4226 ("ugrave", '\u{00F9}'),
4227 ("uhungarumlaut", '\u{0171}'),
4228 ("umacron", '\u{016B}'),
4229 ("uogonek", '\u{0173}'),
4230 ("uring", '\u{016F}'),
4231 ("utilde", '\u{0169}'),
4232 ("wcircumflex", '\u{0175}'),
4233 ("yacute", '\u{00FD}'),
4234 ("ycircumflex", '\u{0177}'),
4235 ("ydieresis", '\u{00FF}'),
4236 ("yen", '\u{00A5}'),
4237 ("zacute", '\u{017A}'),
4238 ("zcaron", '\u{017E}'),
4239 ("zdotaccent", '\u{017C}'),
4240];
4241
4242pub(crate) fn builtin_glyph_text(name: &str) -> Option<String> {
4249 if name.is_empty() || name == ".notdef" {
4250 return None;
4251 }
4252 let name = match name.find('.') {
4253 Some(dot) if dot > 0 => &name[..dot],
4254 _ => name,
4255 };
4256 let lower = name.to_ascii_lowercase();
4257 let index_name = ["gid", "glyph", "g", "cid", "index"].iter().any(|p| {
4258 lower
4259 .strip_prefix(p)
4260 .is_some_and(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
4261 });
4262 if index_name {
4263 return None;
4264 }
4265 if let Some(c) = crate::symbol_fonts::symbol_glyph_char(name) {
4266 return Some(c.to_string());
4267 }
4268 let hex_points = |hex: &str, width: usize| -> Option<String> {
4269 (!hex.is_empty()
4270 && hex.len().is_multiple_of(width)
4271 && hex.bytes().all(|b| b.is_ascii_hexdigit()))
4272 .then(|| {
4273 (0..hex.len())
4274 .step_by(width)
4275 .map(|i| {
4276 u32::from_str_radix(&hex[i..i + width], 16)
4277 .ok()
4278 .and_then(char::from_u32)
4279 })
4280 .collect::<Option<String>>()
4281 })
4282 .flatten()
4283 };
4284 if let Some(hex) = name.strip_prefix("uni") {
4285 if let Some(t) = hex_points(hex, 4) {
4286 return Some(t);
4287 }
4288 }
4289 if let Some(hex) = name.strip_prefix('u') {
4290 if (4..=6).contains(&hex.len()) {
4291 if let Some(t) = hex_points(hex, hex.len()) {
4292 return Some(t);
4293 }
4294 }
4295 }
4296 glyph_name_to_char(name.as_bytes()).map(String::from)
4297}
4298
4299pub(crate) fn glyph_name_to_char(name: &[u8]) -> Option<char> {
4304 let s = std::str::from_utf8(name).ok()?;
4305 if let Some(cp) = s
4308 .strip_prefix("uni")
4309 .and_then(|hex| hex.get(0..4))
4310 .and_then(|hex| u32::from_str_radix(hex, 16).ok())
4311 {
4312 return char::from_u32(cp);
4313 }
4314 if s.len() == 1 {
4316 let b = s.as_bytes()[0];
4317 if b.is_ascii_alphabetic() {
4318 return Some(b as char);
4319 }
4320 }
4321 let resolved = match s {
4322 "space" => ' ',
4323 "exclam" => '!',
4324 "quotedbl" => '"',
4325 "numbersign" => '#',
4326 "dollar" => '$',
4327 "percent" => '%',
4328 "ampersand" => '&',
4329 "quotesingle" => '\'',
4330 "parenleft" => '(',
4331 "parenright" => ')',
4332 "asterisk" => '*',
4333 "plus" => '+',
4334 "comma" => ',',
4335 "hyphen" => '-',
4336 "period" => '.',
4337 "slash" => '/',
4338 "zero" => '0',
4339 "one" => '1',
4340 "two" => '2',
4341 "three" => '3',
4342 "four" => '4',
4343 "five" => '5',
4344 "six" => '6',
4345 "seven" => '7',
4346 "eight" => '8',
4347 "nine" => '9',
4348 "colon" => ':',
4349 "semicolon" => ';',
4350 "less" => '<',
4351 "equal" => '=',
4352 "greater" => '>',
4353 "question" => '?',
4354 "at" => '@',
4355 "bracketleft" => '[',
4356 "backslash" => '\\',
4357 "bracketright" => ']',
4358 "asciicircum" => '^',
4359 "underscore" => '_',
4360 "grave" => '`',
4361 "braceleft" => '{',
4362 "bar" => '|',
4363 "braceright" => '}',
4364 "asciitilde" => '~',
4365 "bullet" => '\u{2022}',
4366 "periodcentered" => '\u{00B7}',
4367 "endash" => '\u{2013}',
4368 "emdash" => '\u{2014}',
4369 "quoteright" => '\u{2019}',
4370 "quoteleft" => '\u{2018}',
4371 "quotedblleft" => '\u{201C}',
4372 "quotedblright" => '\u{201D}',
4373 "quotedblbase" => '\u{201E}',
4374 "quotesinglbase" => '\u{201A}',
4375 "ff" => '\u{FB00}',
4380 "fi" => '\u{FB01}',
4381 "fl" => '\u{FB02}',
4382 "ffi" => '\u{FB03}',
4383 "ffl" => '\u{FB04}',
4384 "ft" => '\u{FB05}',
4385 "st" => '\u{FB06}',
4386 "degree" => '\u{00B0}',
4387 "trademark" => '\u{2122}',
4388 "registered" => '\u{00AE}',
4389 "copyright" => '\u{00A9}',
4390 "ellipsis" => '\u{2026}',
4391 "minus" => '\u{2212}',
4392 "fraction" => '\u{2044}',
4393 "nbspace" => '\u{00A0}',
4394 "alpha" => '\u{03B1}',
4399 "beta" => '\u{03B2}',
4400 "gamma" => '\u{03B3}',
4401 "delta" => '\u{03B4}',
4402 "epsilon" | "epsilon1" => '\u{03B5}',
4403 "zeta" => '\u{03B6}',
4404 "eta" => '\u{03B7}',
4405 "theta" | "theta1" => '\u{03B8}',
4406 "iota" => '\u{03B9}',
4407 "kappa" => '\u{03BA}',
4408 "lambda" => '\u{03BB}',
4409 "mu" => '\u{03BC}',
4410 "nu" => '\u{03BD}',
4411 "xi" => '\u{03BE}',
4412 "omicron" => '\u{03BF}',
4413 "pi" | "pi1" => '\u{03C0}',
4414 "rho" | "rho1" => '\u{03C1}',
4415 "sigma" => '\u{03C3}',
4416 "sigma1" => '\u{03C2}',
4417 "tau" => '\u{03C4}',
4418 "upsilon" => '\u{03C5}',
4419 "phi" | "phi1" => '\u{03C6}',
4420 "chi" => '\u{03C7}',
4421 "psi" => '\u{03C8}',
4422 "omega" | "omega1" => '\u{03C9}',
4423 "Gamma" => '\u{0393}',
4424 "Delta" => '\u{0394}',
4425 "Theta" => '\u{0398}',
4426 "Lambda" => '\u{039B}',
4427 "Xi" => '\u{039E}',
4428 "Pi" => '\u{03A0}',
4429 "Sigma" => '\u{03A3}',
4430 "Upsilon" => '\u{03A5}',
4431 "Phi" => '\u{03A6}',
4432 "Psi" => '\u{03A8}',
4433 "Omega" => '\u{03A9}',
4434 "lessequal" => '\u{2264}',
4435 "greaterequal" => '\u{2265}',
4436 "notequal" => '\u{2260}',
4437 "approxequal" => '\u{2248}',
4438 "equivalence" => '\u{2261}',
4439 "element" => '\u{2208}',
4440 "plusminus" => '\u{00B1}',
4441 "multiply" => '\u{00D7}',
4442 "divide" => '\u{00F7}',
4443 "infinity" => '\u{221E}',
4444 "partialdiff" => '\u{2202}',
4445 "gradient" => '\u{2207}',
4446 "summation" => '\u{2211}',
4447 "product" => '\u{220F}',
4448 "integral" => '\u{222B}',
4449 "radical" => '\u{221A}',
4450 "proportional" => '\u{221D}',
4451 "arrowright" => '\u{2192}',
4452 "arrowleft" => '\u{2190}',
4453 "arrowup" => '\u{2191}',
4454 "arrowdown" => '\u{2193}',
4455 "arrowboth" => '\u{2194}',
4456 "arrowdblright" => '\u{21D2}',
4457 "logicaland" => '\u{2227}',
4458 "logicalor" => '\u{2228}',
4459 "intersection" => '\u{2229}',
4460 "union" => '\u{222A}',
4461 "similar" => '\u{223C}',
4462 "congruent" => '\u{2245}',
4463 "dotmath" => '\u{22C5}',
4464 "asteriskmath" => '\u{2217}',
4465 _ => {
4466 if let Ok(i) = AGL_LATIN.binary_search_by_key(&s, |(n, _)| n) {
4467 return Some(AGL_LATIN[i].1);
4468 }
4469 if let Some(ch) = crate::glyph_names::lookup(s)
4480 .or_else(|| crate::symbol_fonts::symbol_glyph_char(s))
4481 .or_else(|| crate::adobe_glyph_list::lookup(s))
4482 {
4483 return Some(ch);
4484 }
4485 if let Some((base, _)) = s.split_once('.') {
4487 if !base.is_empty() {
4488 return glyph_name_to_char(base.as_bytes());
4489 }
4490 }
4491 if s.contains('_') {
4495 let joined: String = s.chars().filter(|&c| c != '_').collect();
4496 if !joined.is_empty() && joined.len() < s.len() {
4497 return glyph_name_to_char(joined.as_bytes());
4498 }
4499 }
4500 return None;
4501 }
4502 };
4503 Some(resolved)
4504}
4505
4506fn winansi_table() -> HashMap<u8, char> {
4508 let mut m = HashMap::new();
4509 for b in 0x20u8..=0x7e {
4510 m.insert(b, b as char);
4511 }
4512 let extra: &[(u8, char)] = &[
4514 (0x91, '\u{2018}'),
4515 (0x92, '\u{2019}'),
4516 (0x93, '\u{201C}'),
4517 (0x94, '\u{201D}'),
4518 (0x95, '\u{2022}'),
4519 (0x96, '\u{2013}'),
4520 (0x97, '\u{2014}'),
4521 (0x85, '\u{2026}'),
4522 (0xA0, '\u{00A0}'),
4523 (0x80, '\u{20AC}'),
4530 (0x82, '\u{201A}'),
4531 (0x83, '\u{0192}'),
4532 (0x84, '\u{201E}'),
4533 (0x86, '\u{2020}'),
4534 (0x87, '\u{2021}'),
4535 (0x88, '\u{02C6}'),
4536 (0x89, '\u{2030}'),
4537 (0x8A, '\u{0160}'),
4538 (0x8B, '\u{2039}'),
4539 (0x8C, '\u{0152}'),
4540 (0x8E, '\u{017D}'),
4541 (0x98, '\u{02DC}'),
4542 (0x99, '\u{2122}'),
4543 (0x9A, '\u{0161}'),
4544 (0x9B, '\u{203A}'),
4545 (0x9C, '\u{0153}'),
4546 (0x9E, '\u{017E}'),
4547 (0x9F, '\u{0178}'),
4548 ];
4549 for &(b, c) in extra {
4550 m.insert(b, c);
4551 }
4552 for b in 0xA1u8..=0xFF {
4553 m.entry(b).or_insert(b as char);
4554 }
4555 m
4556}
4557
4558fn macroman_table() -> HashMap<u8, char> {
4565 #[rustfmt::skip]
4566 const HIGH: [char; 128] = [
4567 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', '†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{00A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '¤', '‹', '›', 'fi', 'fl', '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', '\0', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ', ];
4584 let mut m = HashMap::new();
4585 for b in 0x20u8..=0x7e {
4586 m.insert(b, b as char);
4587 }
4588 for (b, &c) in (0x80u8..=0xFF).zip(HIGH.iter()) {
4589 if c != '\0' {
4590 m.insert(b, c);
4591 }
4592 }
4593 m
4594}
4595
4596#[cfg(test)]
4597mod glyph_names {
4598 #[test]
4602 fn latin_glyph_names_resolve() {
4603 for w in super::AGL_LATIN.windows(2) {
4604 assert!(
4605 w[0].0 < w[1].0,
4606 "AGL_LATIN not sorted at {:?} / {:?}",
4607 w[0].0,
4608 w[1].0
4609 );
4610 }
4611 for (name, ch) in [
4612 ("Lslash", 'Ł'),
4613 ("lslash", 'ł'),
4614 ("Aacute", 'Á'),
4615 ("aacute", 'á'),
4616 ("Scaron", 'Š'),
4617 ("germandbls", 'ß'),
4618 ("oe", 'œ'),
4619 ("Ydieresis", 'Ÿ'),
4620 ("Euro", '€'),
4621 ("Lslash.sc", 'Ł'),
4622 ("fi", '\u{FB01}'),
4623 ("Omega", '\u{03A9}'),
4624 ] {
4625 assert_eq!(
4626 super::glyph_name_to_char(name.as_bytes()),
4627 Some(ch),
4628 "{name}"
4629 );
4630 }
4631 assert_eq!(super::glyph_name_to_char(b"g123"), None);
4632 assert_eq!(super::glyph_name_to_char(b"f_f_i"), Some('\u{FB03}'));
4634 assert_eq!(super::glyph_name_to_char(b"f_l"), Some('\u{FB02}'));
4635 assert_eq!(super::glyph_name_to_char(b"a_b"), None);
4636 }
4637
4638 #[test]
4642 fn a_stale_tounicode_yields_to_differences() {
4643 use lopdf::Object;
4644 use std::collections::HashMap;
4645 let mut tu: HashMap<u32, String> = HashMap::new();
4646 tu.insert(33, "!".into()); tu.insert(34, "x".into()); let diffs = vec![
4649 Object::Integer(33),
4650 Object::Name(b"f_f_i".to_vec()),
4651 Object::Name(b"f_i".to_vec()),
4652 Object::Name(b"f_f".to_vec()),
4653 Object::Integer(65),
4654 Object::Name(b"A".to_vec()), ];
4656 super::reconcile_stale_tounicode(&mut tu, &diffs);
4657 assert_eq!(tu.get(&33).map(String::as_str), Some("\u{FB03}"));
4658 assert_eq!(tu.get(&34).map(String::as_str), Some("x"));
4659 assert_eq!(tu.get(&35), None);
4660 assert_eq!(tu.get(&65), None);
4661 }
4662
4663 #[test]
4669 fn a_tounicode_value_that_says_nothing_yields_to_differences() {
4670 use lopdf::Object;
4671 use std::collections::HashMap;
4672 let name = |n: &str| Object::Name(n.as_bytes().to_vec());
4673 let mut tu: HashMap<u32, String> = HashMap::new();
4674 tu.insert(33, "\u{0}".into());
4675 tu.insert(34, "\u{FFFD}".into());
4676 tu.insert(35, "\u{FFFF}".into());
4677 tu.insert(36, String::new());
4678 tu.insert(37, "\u{0}".into()); tu.insert(38, "\u{0}\u{0}".into()); tu.insert(39, "−".into()); let diffs = vec![
4682 Object::Integer(33),
4683 name("minus"),
4684 name("Delta"),
4685 name("radicalbig"),
4686 name("parenleftbig"),
4687 name("nosuchglyphname"),
4688 name("plus"),
4689 name("hyphen"),
4690 ];
4691 super::reconcile_stale_tounicode(&mut tu, &diffs);
4692 let got = |c: u32| tu.get(&c).map(String::as_str);
4693 assert_eq!(got(33), Some("−"));
4694 assert_eq!(got(34), Some("Δ"));
4695 assert_eq!(got(35), Some("√"));
4696 assert_eq!(got(36), Some("("));
4697 assert_eq!(got(37), Some("\u{0}"));
4698 assert_eq!(got(38), Some("\u{0}\u{0}"));
4699 assert_eq!(got(39), Some("−"));
4700 }
4701
4702 #[test]
4707 fn tex_glyph_names_resolve() {
4708 let c = |n: &str| super::glyph_name_to_char(n.as_bytes());
4709 assert_eq!(c("parenleftbig"), Some('('));
4710 assert_eq!(c("parenrightBigg"), Some(')'));
4711 assert_eq!(c("integraldisplay"), Some('∫'));
4712 assert_eq!(c("trianglerightsld"), Some('▶'));
4713 assert_eq!(c("prime"), Some('′'));
4714 assert_eq!(c("universal"), Some('∀'));
4715 assert_eq!(c("existential"), Some('∃'));
4716 assert_eq!(c("arrowup"), Some('↑'));
4717 assert_eq!(c("union"), Some('∪'));
4718 assert_eq!(c("uni2212"), Some('−'));
4719 assert_eq!(c("minus"), Some('−'));
4720 assert_eq!(c("Delta"), Some('Δ'), "the Greek letter, not the list's ∆");
4721 assert_eq!(c("angbracketleft"), Some('⟨'));
4722 assert_eq!(c("nosuchglyphname"), None);
4723 }
4724}
4725
4726#[cfg(test)]
4727mod page_box_frame {
4728 use super::*;
4729 use lopdf::dictionary;
4730
4731 fn pdf(boxes: &str, x: f32, y: f32) -> Vec<u8> {
4734 pdf_content(
4735 boxes,
4736 &format!("BT /F1 12 Tf {x} {y} Td (First printing) Tj ET\n"),
4737 )
4738 }
4739
4740 fn pdf_content(boxes: &str, content: &str) -> Vec<u8> {
4743 let objs: Vec<String> = vec![
4744 "<</Type/Catalog/Pages 2 0 R>>".into(),
4745 format!("<</Type/Pages/Kids[3 0 R]/Count 1{boxes}>>"),
4746 "<</Type/Page/Parent 2 0 R/Contents 4 0 R/Resources<</Font<</F1 5 0 R>>>>>>".into(),
4747 format!("<</Length {}>>stream\n{content}endstream", content.len()),
4748 "<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>".into(),
4749 ];
4750 let mut out = b"%PDF-1.4\n".to_vec();
4751 let mut offsets = Vec::new();
4752 for (i, body) in objs.iter().enumerate() {
4753 offsets.push(out.len());
4754 out.extend_from_slice(format!("{} 0 obj{body}endobj\n", i + 1).as_bytes());
4755 }
4756 let xref_at = out.len();
4757 out.extend_from_slice(
4758 format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes(),
4759 );
4760 for off in &offsets {
4761 out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
4762 }
4763 out.extend_from_slice(
4764 format!(
4765 "trailer<</Size {}/Root 1 0 R>>\nstartxref\n{xref_at}\n%%EOF\n",
4766 objs.len() + 1
4767 )
4768 .as_bytes(),
4769 );
4770 out
4771 }
4772
4773 fn pdf_content_streams(contents: &[&[u8]]) -> Vec<u8> {
4775 pdf_with_streams(
4776 contents
4777 .iter()
4778 .map(|content| lopdf::Stream::new(Dictionary::new(), content.to_vec()))
4779 .collect(),
4780 )
4781 }
4782
4783 fn pdf_with_streams(contents: Vec<lopdf::Stream>) -> Vec<u8> {
4785 let mut doc = Document::with_version("1.5");
4786 let streams = contents
4787 .into_iter()
4788 .map(|stream| Object::Reference(doc.add_object(stream)))
4789 .collect::<Vec<_>>();
4790 let font_id = doc.add_object(dictionary! {
4791 "Type" => "Font",
4792 "Subtype" => "Type1",
4793 "BaseFont" => "Helvetica",
4794 });
4795 let resources_id = doc.add_object(dictionary! {
4796 "Font" => dictionary! { "F1" => Object::Reference(font_id) },
4797 });
4798 let pages_id = doc.new_object_id();
4799 let page_id = doc.add_object(dictionary! {
4800 "Type" => "Page",
4801 "Parent" => Object::Reference(pages_id),
4802 "MediaBox" => vec![0.into(), 0.into(), 300.into(), 400.into()],
4803 "Contents" => streams,
4804 "Resources" => Object::Reference(resources_id),
4805 });
4806 doc.objects.insert(
4807 pages_id,
4808 Object::Dictionary(dictionary! {
4809 "Type" => "Pages",
4810 "Kids" => vec![Object::Reference(page_id)],
4811 "Count" => 1,
4812 }),
4813 );
4814 let catalog_id = doc.add_object(dictionary! {
4815 "Type" => "Catalog",
4816 "Pages" => Object::Reference(pages_id),
4817 });
4818 doc.trailer.set("Root", Object::Reference(catalog_id));
4819 let mut out = Vec::new();
4820 doc.save_to(&mut out).expect("save synthetic PDF");
4821 out
4822 }
4823
4824 fn only_page(bytes: &[u8]) -> (PageBox, Vec<Glyph>) {
4825 let doc = load_document(bytes).expect("loads");
4826 let pid = *doc.get_pages().values().next().expect("one page");
4827 (page_box(&doc, pid), page_glyphs(&doc, pid))
4828 }
4829
4830 #[test]
4835 fn glyphs_count_from_the_cropbox_corner_like_pdfium() {
4836 let (pb, shifted) = only_page(&pdf(
4837 "/MediaBox[-56.505 -58.25 576.303 723.31]/CropBox[1.095 -0.65 518.703 665.71]",
4838 37.0 + 1.095,
4839 58.0 - 0.65,
4840 ));
4841 assert!((pb.l - 1.095).abs() < 1e-3 && (pb.b + 0.65).abs() < 1e-3);
4842 assert!(
4843 (pb.w - 517.608).abs() < 1e-3 && (pb.h - 666.36).abs() < 1e-3,
4844 "{pb:?}"
4845 );
4846 let (pb0, plain) = only_page(&pdf("/MediaBox[0 0 517.608 666.36]", 37.0, 58.0));
4847 assert!((pb0.w - pb.w).abs() < 1e-3 && (pb0.h - pb.h).abs() < 1e-3);
4848 assert_eq!(shifted.len(), plain.len());
4849 assert!(!plain.is_empty());
4850 for (a, b) in shifted.iter().zip(&plain) {
4851 assert!(
4852 (a.l - b.l).abs() < 1e-3 && (a.b - b.b).abs() < 1e-3,
4853 "{:?} vs {:?}",
4854 (a.l, a.b),
4855 (b.l, b.b)
4856 );
4857 }
4858 assert!((plain[0].l - 37.0).abs() < 1e-3, "{}", plain[0].l);
4859 }
4860
4861 fn text(glyphs: &[Glyph]) -> String {
4862 glyphs.iter().map(|g| g.ch).collect()
4863 }
4864
4865 #[test]
4870 fn glyphs_outside_the_display_box_are_dropped() {
4871 let (_, g) = only_page(&pdf_content(
4872 "/MediaBox[0 0 400 400]/CropBox[100 100 400 400]",
4873 "BT /F1 14 Tf 120 300 Td (Visible.) Tj ET\nBT /F1 8 Tf 5 40 Td (Slug) Tj ET\n",
4874 ));
4875 assert_eq!(text(&g), "Visible.");
4876 let (_, g) = only_page(&pdf_content(
4877 "/MediaBox[0 0 300 400]",
4878 "BT /F1 14 Tf 40 300 Td (On page) Tj ET\nBT /F1 14 Tf 400 250 Td (Beyond) Tj ET\n",
4879 ));
4880 assert_eq!(text(&g), "On page");
4881 let (_, g) = only_page(&pdf_content(
4883 "/MediaBox[0 0 300 400]",
4884 "BT /F1 14 Tf 200 250 Td (Crossing the right edge) Tj ET\n",
4885 ));
4886 assert_eq!(text(&g), "Crossing the rig");
4887 }
4888
4889 #[test]
4890 fn leading_comment_content_stream_does_not_hide_later_text() {
4891 let (_, glyphs) = only_page(&pdf_content_streams(&[
4894 b"% CANON_PFINF_TYPE2_TEXTOFF\n",
4895 b"BT /F1 14 Tf 40 300 Td (Second stream text) Tj ET",
4896 ]));
4897 assert_eq!(text(&glyphs), "Second stream text");
4898 }
4899
4900 #[test]
4907 fn a_damaged_flate_stream_keeps_its_inflated_prefix() {
4908 use std::io::Write as _;
4909 let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
4913 z.write_all(b"BT /F1 14 Tf 40 200 Td (Partial) Tj ET\n")
4914 .expect("deflate");
4915 z.flush().expect("sync flush");
4916 let mut data = z.get_ref().clone();
4917 data.extend_from_slice(b"\x07garbage\n");
4918 let damaged =
4919 || lopdf::Stream::new(dictionary! { "Filter" => "FlateDecode" }, data.clone());
4920 let plain = |s: &[u8]| lopdf::Stream::new(Dictionary::new(), s.to_vec());
4921
4922 let (_, alone) = only_page(&pdf_with_streams(vec![damaged()]));
4923 assert!(text(&alone).starts_with("Partial"), "{:?}", text(&alone));
4924
4925 let (_, glyphs) = only_page(&pdf_with_streams(vec![
4926 plain(b"BT /F1 14 Tf 40 300 Td (Before) Tj ET"),
4927 damaged(),
4928 plain(b"BT /F1 14 Tf 40 100 Td (After) Tj ET"),
4929 ]));
4930 let t = text(&glyphs);
4931 assert!(t.starts_with("Before") && t.ends_with("After"), "{t:?}");
4932 assert!(t.contains("Partial"), "{t:?}");
4933 }
4934
4935 #[test]
4940 fn a_glyph_on_the_edge_stays_one_over_it_goes() {
4941 let w_at = |x: f32, y: f32| {
4942 let (_, g) = only_page(&pdf_content(
4943 "/MediaBox[0 0 300 400]",
4944 &format!("BT /F1 50 Tf {x} {y} Td (W) Tj ET\n"),
4945 ));
4946 text(&g)
4947 };
4948 assert_eq!(w_at(252.8, 200.0), "W");
4949 assert_eq!(w_at(252.81, 200.0), "");
4950 assert_eq!(w_at(0.0, 200.0), "W");
4951 assert_eq!(w_at(-0.01, 200.0), "");
4952 assert_eq!(w_at(100.0, 20.0), "W");
4955 assert_eq!(w_at(100.0, 0.0), "");
4956 assert_eq!(w_at(100.0, 380.0), "");
4957 }
4958
4959 #[test]
4962 fn page_box_follows_pdfium_fallbacks() {
4963 let (pb, _) = only_page(&pdf("", 10.0, 10.0));
4964 assert_eq!((pb.l, pb.b, pb.w, pb.h), (0.0, 0.0, 612.0, 792.0));
4965 let (pb, _) = only_page(&pdf(
4966 "/MediaBox[0 0 500 700]/CropBox[-100 100 600 900]",
4967 10.0,
4968 10.0,
4969 ));
4970 assert_eq!((pb.l, pb.b, pb.w, pb.h), (0.0, 100.0, 500.0, 600.0));
4971 let (pb, _) = only_page(&pdf(
4972 "/MediaBox[0 0 500 700]/CropBox[800 800 900 900]",
4973 10.0,
4974 10.0,
4975 ));
4976 assert_eq!((pb.l, pb.b, pb.w, pb.h), (0.0, 0.0, 500.0, 700.0));
4977 let (pb, _) = only_page(&pdf("/MediaBox[500 700 0 0]", 10.0, 10.0));
4979 assert_eq!((pb.l, pb.b, pb.w, pb.h), (0.0, 0.0, 500.0, 700.0));
4980 }
4981}
4982
4983#[cfg(test)]
4990mod inherited_resources {
4991 use super::*;
4992 use lopdf::dictionary;
4993
4994 fn pdf(root_res: Object, mid_res: Option<Object>, page_res: Option<Object>) -> Vec<u8> {
4998 let mut doc = Document::with_version("1.3");
4999 let content = doc.add_object(lopdf::Stream::new(
5000 Dictionary::new(),
5001 b"BT /F1 12 Tf 72 700 Td (Inherited resources) Tj ET".to_vec(),
5002 ));
5003 let root_id = doc.new_object_id();
5004 let mid_id = doc.new_object_id();
5005 let mut page = dictionary! {
5006 "Type" => "Page",
5007 "Parent" => Object::Reference(mid_id),
5008 "Contents" => vec![Object::Reference(content)],
5009 };
5010 if let Some(r) = page_res {
5011 page.set("Resources", r);
5012 }
5013 let page_id = doc.add_object(page);
5014 let mut mid = dictionary! {
5015 "Type" => "Pages",
5016 "Parent" => Object::Reference(root_id),
5017 "Kids" => vec![Object::Reference(page_id)],
5018 "Count" => 1,
5019 };
5020 if let Some(r) = mid_res {
5021 mid.set("Resources", r);
5022 }
5023 doc.objects.insert(mid_id, Object::Dictionary(mid));
5024 doc.objects.insert(
5025 root_id,
5026 Object::Dictionary(dictionary! {
5027 "Type" => "Pages",
5028 "Kids" => vec![Object::Reference(mid_id)],
5029 "Count" => 1,
5030 "Resources" => root_res,
5031 "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
5032 }),
5033 );
5034 let catalog = doc.add_object(dictionary! {
5035 "Type" => "Catalog",
5036 "Pages" => Object::Reference(root_id),
5037 });
5038 doc.trailer.set("Root", Object::Reference(catalog));
5039 let mut out = Vec::new();
5040 doc.save_to(&mut out).expect("save synthetic PDF");
5041 out
5042 }
5043
5044 fn fonts(base: &str) -> Object {
5045 Object::Dictionary(dictionary! {
5046 "Font" => dictionary! { "F1" => dictionary! {
5047 "Type" => "Font", "Subtype" => "Type1", "BaseFont" => base,
5048 }},
5049 })
5050 }
5051
5052 fn page_text(bytes: &[u8]) -> String {
5053 let pages = pdf_text_pages(bytes);
5054 assert_eq!(pages.len(), 1);
5055 pages[0]
5056 .cells
5057 .iter()
5058 .map(|c| c.text.as_str())
5059 .collect::<Vec<_>>()
5060 .join(" ")
5061 }
5062
5063 #[test]
5064 fn inline_resources_on_an_ancestor_pages_node_are_inherited() {
5065 let bytes = pdf(fonts("Helvetica"), None, None);
5066 assert_eq!(page_text(&bytes), "Inherited resources");
5067 }
5068
5069 #[test]
5073 fn the_nearest_resources_dictionary_wins() {
5074 let doc_of = |b: &[u8]| load_document(b).expect("load");
5075 let font_of = |bytes: &[u8]| {
5076 let doc = doc_of(bytes);
5077 let pid = *doc.get_pages().values().next().unwrap();
5078 let res = page_res(&doc, pid).expect("resources");
5079 let f1 = res
5080 .get(b"Font")
5081 .ok()
5082 .and_then(|o| o.as_dict().ok())
5083 .and_then(|f| f.get(b"F1").ok())
5084 .and_then(|o| o.as_dict().ok())
5085 .and_then(|f| f.get(b"BaseFont").ok())
5086 .and_then(|o| o.as_name().ok())
5087 .map(|n| String::from_utf8_lossy(n).into_owned());
5088 f1.unwrap_or_default()
5089 };
5090 assert_eq!(font_of(&pdf(fonts("Root"), None, None)), "Root");
5091 assert_eq!(
5092 font_of(&pdf(fonts("Root"), Some(fonts("Mid")), None)),
5093 "Mid"
5094 );
5095 assert_eq!(
5096 font_of(&pdf(fonts("Root"), Some(fonts("Mid")), Some(fonts("Page")))),
5097 "Page"
5098 );
5099 assert_eq!(
5100 font_of(&pdf(fonts("Root"), Some(Object::Null), None)),
5101 "Root"
5102 );
5103 }
5104}
5105
5106#[cfg(test)]
5107mod xref_repair {
5108 fn pdf_with_xref(two_byte_eol: bool) -> Vec<u8> {
5112 let content = b"BT /F1 12 Tf 72 700 Td (Invoice 922769430725) Tj ET\n";
5113 let stream = format!("<</Length {}>>stream\n", content.len()).into_bytes();
5114 let objs: Vec<Vec<u8>> = vec![
5115 b"<</Type/Catalog/Pages 2 0 R>>".to_vec(),
5116 b"<</Type/Pages/Kids[3 0 R]/Count 1>>".to_vec(),
5117 b"<</Type/Page/Parent 2 0 R/MediaBox[0 0 595 842]/Contents 4 0 R\
5118 /Resources<</Font<</F1 5 0 R>>>>>>"
5119 .to_vec(),
5120 [stream.as_slice(), content.as_slice(), b"endstream"].concat(),
5121 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>".to_vec(),
5122 ];
5123
5124 let mut out = b"%PDF-1.4\n".to_vec();
5125 let mut offsets = Vec::new();
5126 for (i, body) in objs.iter().enumerate() {
5127 offsets.push(out.len());
5128 out.extend_from_slice(format!("{} 0 obj", i + 1).as_bytes());
5129 out.extend_from_slice(body);
5130 out.extend_from_slice(b"endobj\n");
5131 }
5132 let xref_at = out.len();
5133 let eol: &[u8] = if two_byte_eol { b" \n" } else { b"\n" };
5134 out.extend_from_slice(format!("xref\n0 {}\n", objs.len() + 1).as_bytes());
5135 out.extend_from_slice(b"0000000000 65535 f");
5136 out.extend_from_slice(eol);
5137 for off in &offsets {
5138 out.extend_from_slice(format!("{off:010} 00000 n").as_bytes());
5139 out.extend_from_slice(eol);
5140 }
5141 out.extend_from_slice(
5142 format!("trailer<</Size {}/Root 1 0 R>>\n", objs.len() + 1).as_bytes(),
5143 );
5144 out.extend_from_slice(format!("startxref\n{xref_at}\n%%EOF\n").as_bytes());
5145 out
5146 }
5147
5148 #[test]
5153 fn short_xref_entries_are_padded_for_fallback() {
5154 let good = pdf_with_xref(true);
5155 let broken = pdf_with_xref(false);
5156 assert!(
5157 broken.len() < good.len(),
5158 "the broken file is the shorter one"
5159 );
5160 assert!(
5161 lopdf::Document::load_mem(&good).is_ok(),
5162 "the control file must load unaided"
5163 );
5164 assert!(
5165 lopdf::Document::load_mem(&broken).is_ok(),
5166 "lopdf 0.45 should accept 19-byte entries"
5167 );
5168
5169 let repaired = super::pad_short_xref_entries(&broken).expect("repair short entries");
5170 assert_eq!(repaired, good, "repair should recreate the valid xref");
5171 assert!(
5172 lopdf::Document::load_mem(&repaired).is_ok(),
5173 "the bytes produced for lopdf 0.44 must load"
5174 );
5175
5176 let cells = |b: &[u8]| -> Vec<String> {
5177 super::pdf_textlines(b)
5178 .into_iter()
5179 .flat_map(|(_, _, c)| c.into_iter().map(|c| c.text))
5180 .collect()
5181 };
5182 let from_good = cells(&good);
5183 assert!(
5184 from_good.iter().any(|t| t.contains("922769430725")),
5185 "control text: {from_good:?}"
5186 );
5187 assert_eq!(
5188 cells(&repaired),
5189 from_good,
5190 "repair must match the good parse"
5191 );
5192 }
5193
5194 #[test]
5198 fn overstated_stream_length_is_fixed_for_fallback() {
5199 let good = pdf_with_xref(true);
5200 let broken = {
5203 let at = good
5204 .windows(8)
5205 .position(|w| w == b"/Length ")
5206 .expect("a /Length")
5207 + 8;
5208 let digits = good[at..].iter().take_while(|c| c.is_ascii_digit()).count();
5209 let n: usize = std::str::from_utf8(&good[at..at + digits])
5210 .unwrap()
5211 .parse()
5212 .unwrap();
5213 let inflated = (n + 1).to_string();
5214 assert_eq!(inflated.len(), digits, "keep the digit count");
5215 let mut b = good.clone();
5216 b[at..at + digits].copy_from_slice(inflated.as_bytes());
5217 b
5218 };
5219 assert_eq!(broken.len(), good.len(), "the defect must not move bytes");
5220 let raw = lopdf::Document::load_mem(&broken).expect("still loads");
5222 assert!(
5223 raw.get_pages()
5224 .into_values()
5225 .any(|p| !raw.get_page_content(p).is_empty()),
5226 "lopdf 0.45 should recover content at endstream"
5227 );
5228
5229 let repaired = super::fix_stream_lengths(&broken);
5230 assert_eq!(repaired.len(), broken.len(), "repair must preserve offsets");
5231 assert_eq!(repaired, good, "repair should restore the true length");
5232 let repaired_doc = lopdf::Document::load_mem(&repaired).expect("repaired PDF loads");
5233 assert!(
5234 repaired_doc
5235 .get_pages()
5236 .into_values()
5237 .any(|p| !repaired_doc.get_page_content(p).is_empty()),
5238 "the bytes produced for lopdf 0.44 must retain page content"
5239 );
5240
5241 let text = |b: &[u8]| -> Vec<String> {
5243 super::pdf_textlines(b)
5244 .into_iter()
5245 .flat_map(|(_, _, c)| c.into_iter().map(|c| c.text))
5246 .collect()
5247 };
5248 let expected = text(&good);
5249 assert!(!expected.is_empty(), "control must produce text");
5250 assert_eq!(text(&repaired), expected);
5251 }
5252
5253 #[test]
5257 fn repair_declines_when_padding_would_move_objects() {
5258 let mut incremental = pdf_with_xref(false);
5259 incremental.extend_from_slice(b"6 0 obj<</Type/Whatever>>endobj\n");
5260 let declined = super::pad_short_xref_entries(&incremental).unwrap_err();
5261 assert!(
5262 declined.contains("object follows the xref"),
5263 "reason: {declined}"
5264 );
5265 }
5266}
5267
5268#[cfg(test)]
5274mod base14_fonts {
5275 fn pdf_with_font(fontdict: &[u8], text: &[u8]) -> Vec<u8> {
5277 let content = [b"BT /F1 12 Tf 72 700 Td (".as_slice(), text, b") Tj ET\n"].concat();
5278 pdf_with_content(fontdict, &content)
5279 }
5280
5281 pub(super) fn pdf_with_content(fontdict: &[u8], content: &[u8]) -> Vec<u8> {
5283 pdf_with_fonts(&[fontdict], content)
5284 }
5285
5286 fn pdf_with_fonts(fontdicts: &[&[u8]], content: &[u8]) -> Vec<u8> {
5289 let stream = format!("<</Length {}>>stream\n", content.len()).into_bytes();
5290 let font_res: String = fontdicts
5291 .iter()
5292 .enumerate()
5293 .map(|(i, _)| format!("/F{} {} 0 R", i + 1, i + 5))
5294 .collect();
5295 let mut objs: Vec<Vec<u8>> = vec![
5296 b"<</Type/Catalog/Pages 2 0 R>>".to_vec(),
5297 b"<</Type/Pages/Kids[3 0 R]/Count 1>>".to_vec(),
5298 format!(
5299 "<</Type/Page/Parent 2 0 R/MediaBox[0 0 595 842]/Contents 4 0 R\
5300 /Resources<</Font<<{font_res}>>>>>>"
5301 )
5302 .into_bytes(),
5303 [stream.as_slice(), content, b"endstream"].concat(),
5304 ];
5305 objs.extend(fontdicts.iter().map(|d| d.to_vec()));
5306 let mut out = b"%PDF-1.4\n".to_vec();
5307 let mut offsets = Vec::new();
5308 for (i, body) in objs.iter().enumerate() {
5309 offsets.push(out.len());
5310 out.extend_from_slice(format!("{} 0 obj", i + 1).as_bytes());
5311 out.extend_from_slice(body);
5312 out.extend_from_slice(b"endobj\n");
5313 }
5314 let xref_at = out.len();
5315 out.extend_from_slice(format!("xref\n0 {}\n", objs.len() + 1).as_bytes());
5316 out.extend_from_slice(b"0000000000 65535 f \n");
5317 for off in &offsets {
5318 out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
5319 }
5320 out.extend_from_slice(
5321 format!("trailer<</Size {}/Root 1 0 R>>\n", objs.len() + 1).as_bytes(),
5322 );
5323 out.extend_from_slice(format!("startxref\n{xref_at}\n%%EOF\n").as_bytes());
5324 out
5325 }
5326
5327 pub(super) fn cells(pdf: &[u8]) -> Vec<crate::pdfium_backend::TextCell> {
5329 super::pdf_textlines(pdf)
5330 .into_iter()
5331 .flat_map(|(_, _, c)| c)
5332 .collect()
5333 }
5334
5335 #[test]
5342 fn rotated_text_matrix_reads_in_order() {
5343 const HELV: &[u8] = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>";
5344 const TEXT: &str = "Upright text on a rotated page.";
5345 for (tm, [l, b, r, t]) in [
5346 ("0 14 -14 0 200 100", [189.9, 100.0, 202.9, 289.1]), ("-14 0 0 -14 350 300", [160.9, 289.9, 350.0, 302.9]), ("0 -14 14 0 200 500", [197.1, 310.9, 210.1, 500.0]), (
5350 "9.8995 9.8995 -9.8995 9.8995 100 100",
5351 [92.9, 98.0, 235.8, 240.8],
5352 ), ] {
5354 let content = format!("BT /F1 1 Tf {tm} Tm ({TEXT}) Tj ET\n");
5355 let pdf = pdf_with_content(HELV, content.as_bytes());
5356 let cs = cells(&pdf);
5357 assert_eq!(cs.len(), 1, "{tm}: {cs:?}");
5358 let c = &cs[0];
5359 assert_eq!(c.text, TEXT, "{tm}");
5360 let got = [c.l, 842.0 - c.b, c.r, 842.0 - c.t];
5365 for (g, w) in got.iter().zip([l, b, r, t]) {
5366 assert!(
5367 (g - w).abs() < 1.0,
5368 "{tm}: box {got:?} vs docling-parse {:?}",
5369 [l, b, r, t]
5370 );
5371 }
5372 let words: Vec<String> = super::pdf_words(&pdf)
5373 .into_iter()
5374 .flat_map(|(_, _, c)| c)
5375 .map(|c| c.text)
5376 .collect();
5377 assert_eq!(words, TEXT.split(' ').collect::<Vec<_>>(), "{tm}");
5378 }
5379 }
5380
5381 #[test]
5386 fn rotated_text_off_the_page_is_dropped() {
5387 const HELV: &[u8] = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>";
5388 let off = pdf_with_content(
5389 HELV,
5390 b"BT /F1 1 Tf 0 14 -14 0 -4 200 Tm (Spine title) Tj ET\n",
5391 );
5392 assert!(cells(&off).is_empty(), "{:?}", cells(&off));
5393 let on = pdf_with_content(
5394 HELV,
5395 b"BT /F1 1 Tf 0 14 -14 0 30 200 Tm (Margin note) Tj ET\n",
5396 );
5397 assert_eq!(cells(&on).len(), 1);
5398 }
5399
5400 #[test]
5403 fn upright_glyphs_carry_no_quad() {
5404 let only_page = |pdf: &[u8]| {
5405 let doc = super::load_document(pdf).expect("loads");
5406 let pid = *doc.get_pages().values().next().expect("one page");
5407 super::page_glyphs(&doc, pid)
5408 };
5409 let pdf = pdf_with_font(b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>", b"Plain");
5410 let glyphs = only_page(&pdf);
5411 assert!(!glyphs.is_empty());
5412 assert!(glyphs.iter().all(|g| g.quad.is_none() && g.lr > g.ll));
5413 let pdf = pdf_with_content(
5415 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>",
5416 b"BT /F1 1 Tf 0 14 -14 0 200 100 Tm (W) Tj ET\n",
5417 );
5418 let glyphs = only_page(&pdf);
5419 let g = &glyphs[0];
5420 assert!(g.quad.is_some());
5421 assert!((g.height() - 14.0).abs() < 0.05, "{}", g.height());
5423 }
5424
5425 #[test]
5430 fn ticks_stacked_by_cm_are_separate_line_cells() {
5431 let mut content = String::new();
5432 for (k, tick) in "345678".chars().enumerate() {
5433 let y = 300.0 + 25.92 * k as f64;
5434 content.push_str(&format!(
5435 "q 1 0 0 1 125 {y} cm BT /F1 10 Tf 1 0 0 1 -5 -4 Tm ({tick}) Tj ET Q\n"
5436 ));
5437 }
5438 let pdf = pdf_with_content(
5439 b"<</Type/Font/Subtype/Type1/BaseFont/Times-Roman>>",
5440 content.as_bytes(),
5441 );
5442 let cells = cells(&pdf);
5443 let texts: Vec<&str> = cells.iter().map(|c| c.text.as_str()).collect();
5444 assert_eq!(texts, ["3", "4", "5", "6", "7", "8"]);
5445 for (k, c) in cells.iter().enumerate() {
5446 let base = 842.0 - (300.0 + 25.92 * k as f32 - 4.0);
5448 assert!((c.l - 120.0).abs() < 0.1, "{k}: l {}", c.l);
5449 assert!(
5450 c.t < base && base - c.t < 10.0,
5451 "{k}: t {} base {base}",
5452 c.t
5453 );
5454 }
5455 }
5456
5457 #[test]
5463 fn drawn_checkbox_squares_are_found() {
5464 let content = b"q 1 0 0 1 119.52 449.04 cm \
5465 n 0 12.96 m 12.96 12.96 l S n 0 0 m 12.96 0 l S \
5466 n 0 0 m 0 12.96 l S n 12.96 0 m 12.96 12.96 l S Q\n\
5467 200 400 10 10 re S 202 405 m 204.5 402 l 208.5 408.5 l S\n\
5468 300 400 12 12 re f 50 50 100 100 re S\n\
5469 q 0.2 0.4 0.8 rg 400 400 12 12 re B Q q 1 g 500 400 12 12 re B Q\n";
5470 let pdf = pdf_with_content(b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>", content);
5471 let mut parser = super::PageTextParser::open(&pdf).expect("parses");
5472 let mut boxes = parser.cells(0).checkboxes;
5473 boxes.sort_by(|a, b| a.l.total_cmp(&b.l));
5474 let got: Vec<([i32; 4], bool)> = boxes
5475 .iter()
5476 .map(|c| {
5477 let r = |v: f32| (v * 100.0).round() as i32;
5478 ([r(c.l), r(c.t), r(c.r), r(c.b)], c.checked)
5479 })
5480 .collect();
5481 assert_eq!(
5483 got,
5484 [
5485 ([11952, 38000, 13248, 39296], false),
5486 ([20000, 43200, 21000, 44200], true),
5487 ([50000, 43000, 51200, 44200], false),
5488 ]
5489 );
5490 }
5491
5492 #[test]
5494 fn standard14_faces_get_builtin_widths() {
5495 for fontdict in [
5496 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>".as_slice(),
5498 b"<</Type/Font/Subtype/Type1/BaseFont/Times-BoldItalic>>",
5500 b"<</Type/Font/Subtype/TrueType/BaseFont/Arial,Bold>>",
5502 b"<</Type/Font/Subtype/Type1/BaseFont/ABCDEF+Courier-Oblique>>",
5503 ] {
5504 let pdf = pdf_with_font(fontdict, b"Words have width now");
5505 let cs = cells(&pdf);
5506 let text: String = cs
5507 .iter()
5508 .map(|c| c.text.as_str())
5509 .collect::<Vec<_>>()
5510 .join(" ");
5511 assert!(
5512 text.contains("Words have width now"),
5513 "{}: text lost: {text:?}",
5514 String::from_utf8_lossy(fontdict)
5515 );
5516 assert!(
5517 cs.iter().all(|c| c.r > c.l),
5518 "{}: zero-width cells: {cs:?}",
5519 String::from_utf8_lossy(fontdict)
5520 );
5521 }
5522 }
5523
5524 #[test]
5529 fn macroman_fonts_keep_accented_letters() {
5530 let sentence = b"Bl\x8cb\xbergr\xbfd p\x8c \xbfen \xd0 caf\x8e M\x9fller, Stra\xa7e \xa4 3";
5531 for (fontdict, want) in [
5532 (
5533 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/MacRomanEncoding>>"
5534 .as_slice(),
5535 "Blåbærgrød på øen – café Müller, Straße § 3",
5536 ),
5537 (
5538 b"<</Type/Font/Subtype/TrueType/BaseFont/ABCDEF+Arial\
5539 /Encoding<</Type/Encoding/BaseEncoding/MacRomanEncoding/Differences[51/four]>>>>",
5540 "Blåbærgrød på øen – café Müller, Straße § 4",
5541 ),
5542 ] {
5543 let text: String = cells(&pdf_with_font(fontdict, sentence))
5544 .iter()
5545 .map(|c| c.text.as_str())
5546 .collect::<Vec<_>>()
5547 .join(" ");
5548 assert_eq!(text, want, "{}", String::from_utf8_lossy(fontdict));
5549 }
5550
5551 let table = super::macroman_table();
5553 assert_eq!(
5554 (0x80u8..=0xFF).filter(|b| table.contains_key(b)).count(),
5555 127
5556 );
5557 assert_eq!(table.get(&0xF0), None);
5558 assert_eq!(table[&0xDB], '¤');
5559 assert_eq!(
5560 [0x80, 0x8C, 0xAE, 0xAF, 0xBE, 0xBF, 0xFF].map(|b| table[&b]),
5561 ['Ä', 'å', 'Æ', 'Ø', 'æ', 'ø', 'ˇ']
5562 );
5563 }
5564
5565 #[test]
5570 fn winansi_unused_codes_are_bullets() {
5571 let read = |fontdict: &[u8], text: &[u8]| -> String {
5572 cells(&pdf_with_font(fontdict, text))
5573 .iter()
5574 .map(|c| c.text.as_str())
5575 .collect::<Vec<_>>()
5576 .join(" ")
5577 };
5578 let winansi = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
5579 assert_eq!(read(winansi, b"\\177 Cut costs"), "\u{2022} Cut costs");
5580 for code in [0x7Fu8, 0x81, 0x8D, 0x8F, 0x90, 0x9D] {
5581 assert_eq!(
5582 read(winansi, &[b'x', code, b'x']),
5583 "x\u{2022}x",
5584 "{code:#x}"
5585 );
5586 }
5587 let dict = b"<</Type/Font/Subtype/TrueType/BaseFont/Arial\
5588 /Encoding<</Type/Encoding/BaseEncoding/WinAnsiEncoding>>>>";
5589 assert_eq!(read(dict, b"\\177 Cut costs"), "\u{2022} Cut costs");
5590 let bare = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>";
5591 assert!(!read(bare, b"x\\177x").contains('\u{2022}'));
5592 }
5593
5594 #[test]
5600 fn unmapped_glyphs_read_as_the_replacement_char() {
5601 let cmap = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap\n\
5602 1 begincodespacerange <00> <FF> endcodespacerange\n\
5603 1 beginbfchar <7e> <0000> endbfchar\n\
5604 endcmap CMapName currentdict /CMap defineresource pop end end";
5605 let stream = [
5606 format!("<</Length {}>>stream\n", cmap.len()).as_bytes(),
5607 cmap.as_slice(),
5608 b"\nendstream",
5609 ]
5610 .concat();
5611 let pdf = pdf_with_fonts(
5612 &[
5613 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/ToUnicode 6 0 R\
5614 /Encoding<</Type/Encoding/Differences[1/g115 2/SM590000]>>>>",
5615 &stream,
5616 ],
5617 b"BT /F1 12 Tf 72 700 Td (mg.mL ~ 1 \x01 x \x02 y) Tj ET\n",
5618 );
5619 let text: String = cells(&pdf)
5620 .iter()
5621 .map(|c| c.text.as_str())
5622 .collect::<Vec<_>>()
5623 .join(" ");
5624 assert_eq!(text, "mg.mL \u{FFFD} 1 \u{FFFD} x SM590000 y");
5625 }
5626
5627 #[cfg(feature = "render")]
5631 #[test]
5632 fn a_blank_glyph_program_is_a_space() {
5633 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5634 .join("../../tests/data/pdf/sources/redp5110_sampled.pdf");
5635 let Ok(bytes) = std::fs::read(path) else {
5636 return;
5637 };
5638 let lines: Vec<String> = super::pdf_textlines(&bytes)
5639 .into_iter()
5640 .flat_map(|(_, _, c)| c)
5641 .map(|c| c.text)
5642 .collect();
5643 let want = "\u{FFFD} \u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD} \
5644 \u{FFFD}\u{FFFD}\u{FFFD} ";
5645 assert!(
5646 lines.iter().any(|l| l.starts_with(want)),
5647 "no `{want}` line in {:?}",
5648 lines
5649 .iter()
5650 .filter(|l| l.contains('\u{FFFD}'))
5651 .collect::<Vec<_>>()
5652 );
5653 }
5654
5655 #[cfg(feature = "render")]
5661 #[test]
5662 fn an_invalid_metric_font_is_boxed_by_its_ink() {
5663 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5664 .join("../../tests/data/pdf/sources/2305.03393v1.pdf");
5665 let Ok(bytes) = std::fs::read(path) else {
5666 return;
5667 };
5668 let pages = super::pdf_textlines(&bytes);
5669 let line = |text: &str| {
5670 pages[9]
5671 .2
5672 .iter()
5673 .find(|c| c.text == text)
5674 .unwrap_or_else(|| panic!("no `{text}` line cell"))
5675 .clone()
5676 };
5677 let name = line("\"PMC2807444");
5678 let under: Vec<_> = pages[9].2.iter().filter(|c| c.text == "_").collect();
5679 assert_eq!(under.len(), 2, "two `_` cells");
5680 for u in under {
5681 assert!(
5682 u.t > name.b,
5683 "`_` under the digits' ink: {:?} vs {:?}",
5684 u,
5685 name
5686 );
5687 assert!(
5688 (u.b - u.t - 0.403).abs() < 0.01,
5689 "an outline-tight box: {u:?}"
5690 );
5691 }
5692 }
5693
5694 #[test]
5699 fn descriptor_metrics_follow_docling_parse() {
5700 use lopdf::{dictionary, Object};
5701 let font = |asc: Option<i64>, desc: Option<i64>, bbox: bool| {
5702 let mut fd = dictionary! { "Type" => "FontDescriptor", "FontName" => "X" };
5703 if let Some(a) = asc {
5704 fd.set("Ascent", a);
5705 }
5706 if let Some(d) = desc {
5707 fd.set("Descent", d);
5708 }
5709 if bbox {
5710 let b: Vec<Object> = [-196, -322, 1502, 937].map(Object::from).to_vec();
5711 fd.set("FontBBox", b);
5712 }
5713 let f = dictionary! {
5714 "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "X",
5715 "FontDescriptor" => fd,
5716 };
5717 super::font_ascent_descent(&lopdf::Document::with_version("1.5"), &f, false)
5718 };
5719 assert_eq!(font(Some(0), Some(0), true), (937.0, -322.0, true));
5720 assert_eq!(font(Some(700), Some(200), true), (937.0, -322.0, true));
5721 assert_eq!(font(Some(90000), Some(-250), true), (937.0, -250.0, true));
5722 assert_eq!(font(Some(718), Some(-207), true), (718.0, -207.0, false));
5723 assert_eq!(font(Some(0), Some(0), false), (750.0, -250.0, false));
5724 assert_eq!(font(None, None, true), (750.0, -250.0, false));
5725 }
5726
5727 #[test]
5737 fn the_char_box_is_scaled_by_cap_height_over_ascent() {
5738 use lopdf::dictionary;
5739 let font = |asc: i64, desc: i64, cap: Option<i64>| {
5740 let mut fd = dictionary! {
5741 "Type" => "FontDescriptor", "FontName" => "X",
5742 "Ascent" => asc, "Descent" => desc,
5743 };
5744 if let Some(c) = cap {
5745 fd.set("CapHeight", c);
5746 }
5747 let f = dictionary! {
5748 "Type" => "Font", "Subtype" => "TrueType", "BaseFont" => "X",
5749 "FontDescriptor" => fd,
5750 };
5751 let (a, d, invalid) =
5752 super::font_ascent_descent(&lopdf::Document::with_version("1.5"), &f, false);
5753 assert!(!invalid);
5754 ((a * 10.0).round() / 10.0, (d * 10.0).round() / 10.0)
5755 };
5756 assert_eq!(font(905, -212, Some(716)), (716.0, -167.7));
5757 assert_eq!(font(3117, -2464, Some(667)), (667.0, -527.3));
5758 assert_eq!(font(1047, -299, Some(667)), (667.0, -190.5));
5759 assert_eq!(font(905, -212, None), (905.0, -212.0));
5760 assert_eq!(font(905, -212, Some(1200)), (905.0, -212.0));
5761 assert_eq!(font(905, -212, Some(10)), (905.0, -212.0));
5762 assert_eq!(font(905, -212, Some(0)), (905.0, -212.0));
5763 }
5764
5765 #[test]
5770 fn symbol_private_use_values_read_as_the_glyphs() {
5771 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5772 .join("../../tests/data/pdf/sources/redp5110_sampled.pdf");
5773 let Ok(bytes) = std::fs::read(path) else {
5774 return;
5775 };
5776 let lines: Vec<String> = super::pdf_textlines(&bytes)
5777 .into_iter()
5778 .flat_map(|(_, _, c)| c)
5779 .map(|c| c.text)
5780 .collect();
5781 assert!(
5782 lines
5783 .iter()
5784 .any(|l| l.ends_with("click Schemas → HR_SCHEMA→")),
5785 "{:?}",
5786 lines
5787 .iter()
5788 .filter(|l| l.contains("Schemas"))
5789 .collect::<Vec<_>>()
5790 );
5791 assert!(lines.iter().all(|l| !l.contains('\u{F0AE}')));
5792 }
5793
5794 #[cfg(feature = "render")]
5800 #[test]
5801 fn a_symbolic_font_reads_through_its_builtin_encoding() {
5802 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5803 .join("../../tests/data/pdf/sources/2203.01017v2.pdf");
5804 let Ok(bytes) = std::fs::read(path) else {
5805 return;
5806 };
5807 let pages = super::pdf_textlines(&bytes);
5808 let text: Vec<&str> = pages[3].2.iter().map(|c| c.text.as_str()).collect();
5809 let page = text.join("\n");
5810 assert_eq!(page.matches('✓').count(), 11, "{text:?}");
5811 assert_eq!(page.matches('✗').count(), 1, "{text:?}");
5812 assert!(text.contains(&"✓ ✗ 145k JPEG"), "{text:?}");
5813 }
5814
5815 #[test]
5817 fn builtin_glyph_names_read_as_docling_parse() {
5818 let t = |n: &str| super::builtin_glyph_text(n);
5819 assert_eq!(t("a19").as_deref(), Some("✓"));
5820 assert_eq!(t("arrowright").as_deref(), Some("→"));
5821 assert_eq!(t("A").as_deref(), Some("A"));
5822 assert_eq!(t("one.oldstyle").as_deref(), Some("1"), "suffix dropped");
5823 assert_eq!(t("uni00660069").as_deref(), Some("fi"), "a uni sequence");
5824 assert_eq!(t("u1F600").as_deref(), Some("😀"));
5825 assert_eq!(t("g12"), None, "an index name");
5826 assert_eq!(t("GID00012"), None);
5827 assert_eq!(t("cid7"), None);
5828 assert_eq!(t(".notdef"), None);
5829 assert_eq!(t(""), None);
5830 assert_eq!(t("nosuchglyphname"), None);
5831 }
5832
5833 #[test]
5836 fn image_placements_are_the_pages_bitmaps() {
5837 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5838 .join("../docling/tests/fixtures/partial_text_layer/scan_with_native_word.pdf");
5839 let bytes = std::fs::read(path).expect("fixture");
5840 let mut parser = super::PageTextParser::open(&bytes).expect("parser");
5841 let page = parser.cells(0);
5842 assert_eq!(page.bitmaps, vec![[0.0, 0.0, 612.0, 792.0]]);
5843 assert_eq!(page.words.len(), 1);
5844 assert!(page.checkboxes.is_empty());
5845 }
5846
5847 #[test]
5851 fn surrogate_pair_bfrange_maps_each_code() {
5852 let map = super::parse_tounicode(
5853 b"1 beginbfrange <1d59> <1d5a> <d835dec2> endbfrange\n\
5854 1 beginbfrange <0010> <0011> <0041> endbfrange",
5855 );
5856 assert_eq!(map.get(&0x1d59).map(String::as_str), Some("\u{1D6C2}"));
5857 assert_eq!(map.get(&0x1d5a).map(String::as_str), Some("\u{1D6C3}"));
5858 assert_eq!(map.get(&0x11).map(String::as_str), Some("B"));
5859 }
5860
5861 #[test]
5865 fn unknown_glyph_names_follow_docling_parse() {
5866 for name in [
5867 "g115", "gid00043", "Glyph7", "cid42", "index9", "g3.alt", "g15C", "gA1", "G1F",
5868 ] {
5869 assert_eq!(super::unknown_name_text(name), None, "{name}");
5870 assert!(
5871 super::is_gid_name(name.split('.').next().unwrap().as_bytes()),
5872 "{name}"
5873 );
5874 }
5875 assert!(!super::is_gid_name(b"glyphs"), "not hexadecimal");
5876 assert!(!super::is_gid_name(b"uni0041"));
5877 assert_eq!(
5878 super::unknown_name_text("SM590000").as_deref(),
5879 Some("SM590000")
5880 );
5881 assert_eq!(
5882 super::unknown_name_text("SM590000.sc").as_deref(),
5883 Some("SM590000")
5884 );
5885 }
5886
5887 #[test]
5890 fn explicit_widths_win_and_unknown_faces_are_untouched() {
5891 let explicit = pdf_with_font(
5895 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/FirstChar 65\
5896 /Widths[100 100 100 100]/Encoding/WinAnsiEncoding>>",
5897 b"ABBA",
5898 );
5899 let builtin = pdf_with_font(
5900 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>",
5901 b"ABBA",
5902 );
5903 let w = |pdf: &[u8]| {
5904 let cs = cells(pdf);
5905 assert_eq!(cs.len(), 1, "one word cell: {cs:?}");
5906 cs[0].r - cs[0].l
5907 };
5908 let (we, wb) = (w(&explicit), w(&builtin));
5909 assert!(
5910 (we - 4.8).abs() < 0.1,
5911 "explicit widths must win: got {we}, want 4×100×12/1000"
5912 );
5913 assert!(
5914 wb > 2.0 * we,
5915 "built-in Helvetica is much wider: {wb} vs {we}"
5916 );
5917
5918 let unknown = pdf_with_font(
5922 b"<</Type/Font/Subtype/Type1/BaseFont/FancyCorp-Display>>",
5923 b"Mystery",
5924 );
5925 let cs = cells(&unknown);
5926 let text: String = cs.iter().map(|c| c.text.as_str()).collect();
5927 assert!(text.contains("Mystery"), "text still decodes: {cs:?}");
5928 }
5929
5930 #[test]
5937 fn tex_math_glyphs_at_low_codes_decode() {
5938 let font = b"<</Type/Font/Subtype/Type1/BaseFont/ABCDEF+LMMathExtension10-Regular\
5939 /FirstChar 0/LastChar 90/Widths[458 458 0 0 0 0 0 0 0 0 0 0 0 0 0 0 597 597 \
5940 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \
5941 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 472]\
5942 /Encoding<</Type/Encoding/Differences[0/parenleftbig/parenrightbig \
5943 16/parenleftBig/parenrightBig 90/integraldisplay]>>>>";
5944 let text = |bytes: &[u8]| -> String {
5945 cells(&pdf_with_font(font, bytes))
5946 .iter()
5947 .map(|c| c.text.as_str())
5948 .collect()
5949 };
5950 assert_eq!(text(b"\\000\\001"), "()");
5951 assert_eq!(text(b"\\020\\021Z"), "()∫");
5952 assert!(!text(b"\\000\\001\\020\\021Z").contains('\u{FFFD}'));
5953 }
5954
5955 #[cfg(feature = "glyph-list")]
5960 #[test]
5961 fn glyph_list_names_decode_a_reencoded_cyrillic_font() {
5962 let font = b"<</Type/Font/Subtype/Type1/BaseFont/ABCDEF+SchoolBookC\
5963 /FirstChar 65/LastChar 68/Widths[700 650 650 600]\
5964 /Encoding<</Type/Encoding/BaseEncoding/WinAnsiEncoding\
5965 /Differences[65/afii10017/afii10018/afii10019/afii10020]>>>>";
5966 let text: String = cells(&pdf_with_font(font, b"ABCD"))
5967 .iter()
5968 .map(|c| c.text.as_str())
5969 .collect();
5970 assert_eq!(text, "АБВГ");
5971 }
5972
5973 #[test]
5977 fn widthless_fonts_outside_the_core_14_names_keep_their_text() {
5978 let line = |base: &str, descriptor: &str| {
5981 let font = format!(
5982 "<</Type/Font/Subtype/TrueType/BaseFont/{base}/Encoding/WinAnsiEncoding{descriptor}>>"
5983 );
5984 let cs = cells(&pdf_with_font(font.as_bytes(), b"Hello World"));
5985 assert_eq!(cs.len(), 1, "{base}: {cs:?}");
5986 assert_eq!(cs[0].text, "Hello World", "{base}");
5987 cs[0].r - cs[0].l
5988 };
5989 let arial = line("ArialMT", "");
5992 assert!((arial - line("Arial", "")).abs() < 1e-3, "{arial}");
5993 for base in [
5994 "TimesNewRomanPSMT",
5995 "TimesNewRomanPS-BoldMT",
5996 "CourierNewPSMT",
5997 ] {
5998 line(base, "");
5999 }
6000 let georgia = line("Georgia", "");
6002 assert!((georgia - 11.0 * 6.0).abs() < 0.5, "{georgia}");
6003 let avg = line(
6004 "Tahoma",
6005 "/FontDescriptor<</Type/FontDescriptor/FontName/Tahoma/Flags 32/AvgWidth 400\
6006 /FontBBox[0 -200 1000 800]/Ascent 800/Descent -200/CapHeight 700>>",
6007 );
6008 assert!((avg - 11.0 * 4.8).abs() < 0.5, "{avg}");
6009 }
6010
6011 #[test]
6016 fn non_embedded_symbol_faces_read_through_their_encoding() {
6017 let dingbats = pdf_with_font(
6018 b"<</Type/Font/Subtype/Type1/BaseFont/ZapfDingbats/Name/F3>>",
6019 b"l",
6020 );
6021 let cs = cells(&dingbats);
6022 assert_eq!(cs.len(), 1, "{cs:?}");
6023 assert_eq!(cs[0].text, "●");
6024 assert!(
6025 (cs[0].r - cs[0].l - 791.0 * 12.0 / 1000.0).abs() < 0.1,
6026 "{cs:?}"
6027 );
6028 let symbol = pdf_with_font(b"<</Type/Font/Subtype/Type1/BaseFont/Symbol>>", b"abg");
6029 let text: String = cells(&symbol).iter().map(|c| c.text.as_str()).collect();
6030 assert_eq!(text, "αβγ");
6031 let symbol = pdf_with_font(b"<</Type/Font/Subtype/Type1/BaseFont/Symbol>>", b"a\xd7b");
6032 let text: String = cells(&symbol).iter().map(|c| c.text.as_str()).collect();
6033 assert_eq!(text, "α⋅β");
6034 }
6035
6036 #[test]
6044 fn a_symbol_face_follows_its_declared_encoding_where_it_has_the_glyph() {
6045 let read = |enc: &str, text: &[u8]| -> String {
6046 let font = format!("<</Type/Font/Subtype/Type1/BaseFont/Symbol/Encoding/{enc}>>");
6047 let pdf = pdf_with_font(font.as_bytes(), text);
6048 cells(&pdf).iter().map(|c| c.text.as_str()).collect()
6049 };
6050 assert_eq!(read("WinAnsiEncoding", b"a\xd7b"), "α×β");
6051 assert_eq!(read("MacRomanEncoding", b"ab"), "αβ");
6052 assert_eq!(read("MacRomanEncoding", b"\xa5"), "•");
6053 }
6054
6055 #[test]
6061 fn standard_and_mac_expert_encodings_have_their_own_tables() {
6062 let read = |font: &[u8], text: &[u8]| -> String {
6063 cells(&pdf_with_font(font, text))
6064 .iter()
6065 .map(|c| c.text.as_str())
6066 .collect()
6067 };
6068 let codes = b"x'`\xae\xaf\xe1\xf1\xa4\xd0y";
6069 for font in [
6070 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/StandardEncoding>>".as_slice(),
6071 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>",
6072 b"<</Type/Font/Subtype/Type1/BaseFont/Times-Roman/Encoding\
6073 <</Type/Encoding/BaseEncoding/StandardEncoding/Differences[200/zero]>>>>",
6074 ] {
6075 assert_eq!(
6076 read(font, codes),
6077 "x’‘fiflÆæ⁄—y",
6078 "{}",
6079 String::from_utf8_lossy(font)
6080 );
6081 }
6082 let expert = b"<</Type/Font/Subtype/Type1/BaseFont/ArialMT/Encoding/MacExpertEncoding>>";
6083 assert_eq!(read(expert, b"WX"), "fifl");
6084 let tt = b"<</Type/Font/Subtype/TrueType/BaseFont/Helvetica>>";
6086 assert_eq!(read(tt, b"x\xe1y"), "xáy");
6087 }
6088
6089 #[test]
6097 fn overprinted_text_reads_once() {
6098 const H: &[u8] =
6099 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6100 const HB: &[u8] =
6101 b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica-Bold/Encoding/WinAnsiEncoding>>";
6102 const A: &str = "ALPHA BETA GAMMA";
6103 const D: &str = "DELTA EPSILON ZETA";
6104 let lines = |fonts: &[&[u8]], content: &str| -> Vec<String> {
6105 cells(&pdf_with_fonts(fonts, content.as_bytes()))
6106 .into_iter()
6107 .map(|c| c.text)
6108 .collect()
6109 };
6110 let draws = |ds: &[(f32, f32, &str)]| -> String {
6111 ds.iter()
6112 .map(|(x, y, t)| format!("BT /F1 12 Tf {x} {y} Td ({t}) Tj ET\n"))
6113 .collect()
6114 };
6115 let cases: [(&str, String, Vec<&str>); 13] = [
6116 ("line3x", draws(&[(72.0, 700.0, A); 3]), vec![A]),
6117 ("exact2", draws(&[(72.0, 700.0, A); 2]), vec![A]),
6118 (
6119 "block3x",
6120 draws(&[(72.0, 700.0, A), (72.0, 660.0, D)].repeat(3)),
6121 vec![A, D],
6122 ),
6123 (
6124 "two_positions",
6125 draws(&[(72.0, 700.0, A), (72.0, 660.0, A)]),
6126 vec![A, A],
6127 ),
6128 (
6129 "nearby2",
6130 draws(&[(72.0, 700.0, A), (72.3, 700.0, A)]),
6131 vec![A],
6132 ),
6133 (
6134 "shift1pt",
6135 draws(&[(72.0, 700.0, A), (73.0, 700.0, A)]),
6136 vec![A],
6137 ),
6138 (
6139 "bat_pat",
6140 draws(&[(72.0, 700.0, "BAT"), (72.0, 660.0, D), (72.3, 700.0, "PAT")]),
6141 vec!["BAT", D, "PAT"],
6142 ),
6143 (
6144 "shifted_after",
6145 draws(&[(72.0, 700.0, A), (72.0, 660.0, D), (72.01, 700.01, A)]),
6146 vec![A, D],
6147 ),
6148 (
6149 "block_shift001",
6150 draws(&[
6151 (72.0, 700.0, A),
6152 (72.0, 660.0, D),
6153 (72.01, 700.01, A),
6154 (72.01, 660.01, D),
6155 ]),
6156 vec![A, D],
6157 ),
6158 (
6159 "token_alpha_beta",
6160 draws(&[
6161 (72.0, 700.0, "TOKEN ALPHA"),
6162 (72.0, 660.0, D),
6163 (72.01, 700.01, "TOKEN BETA"),
6164 ]),
6165 vec!["TOKEN ALPHA", D, "TOKEN BETA"],
6166 ),
6167 (
6168 "rotated",
6169 "BT /F1 12 Tf 0 1 -1 0 300 200 Tm (ALPHA BETA) Tj ET\n\
6170 BT /F1 12 Tf 0 1 -1 0 320 200 Tm (OTHER LINE) Tj ET\n\
6171 BT /F1 12 Tf 0 1 -1 0 300.01 200.01 Tm (ALPHA BETA) Tj ET\n"
6172 .to_string(),
6173 vec!["ALPHA BETA", "OTHER LINE"],
6174 ),
6175 (
6176 "small_partial",
6177 "BT /F1 1 Tf 72 700 Td (WORD) Tj ET\nBT /F1 12 Tf 72 660 Td (OTHER LINE) Tj ET\n\
6178 BT /F1 1 Tf 72.25 700.25 Td (WORD) Tj ET\n"
6179 .to_string(),
6180 vec!["WORD", "OTHER LINE", "WORD"],
6181 ),
6182 (
6183 "fonts",
6184 "BT /F1 12 Tf 72 700 Td (.) Tj ET\nBT /F1 12 Tf 72 660 Td (OTHER LINE) Tj ET\n\
6185 BT /F2 12 Tf 72.01 700.01 Td (.) Tj ET\n"
6186 .to_string(),
6187 vec![".", "OTHER LINE", "."],
6188 ),
6189 ];
6190 for (name, content, want) in cases {
6191 assert_eq!(lines(&[H, HB], &content), want, "{name}");
6192 }
6193 }
6194
6195 #[test]
6201 fn a_clip_that_cuts_a_glyph_separates_words_and_lines() {
6202 const HELV: &[u8] = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>";
6203 let read = |content: &str| -> (Vec<String>, Vec<String>) {
6204 let pdf = pdf_with_content(HELV, content.as_bytes());
6205 let words = super::pdf_words(&pdf)
6206 .into_iter()
6207 .flat_map(|(_, _, c)| c)
6208 .map(|c| c.text)
6209 .collect();
6210 let lines = cells(&pdf).into_iter().map(|c| c.text).collect();
6211 (words, lines)
6212 };
6213 let rows = [
6215 ["Code", "Description", "Unit", "Amount"],
6216 [
6217 "AB-1001-XYZ",
6218 "Replacement of the ventilation unit, roof level",
6219 "pcs",
6220 "1",
6221 ],
6222 ["AB-1002", "Gutter cleaning", "m", "120"],
6223 [
6224 "AB-1003-LONG",
6225 "Repainting of window frames and fascia boards",
6226 "m2",
6227 "85",
6228 ],
6229 ];
6230 let columns = [72.0, 122.0, 252.0, 302.0, 372.0];
6231 let (top, row_h) = (720.0, 22.0);
6232 let mut table = String::from("0.5 w\n");
6233 for i in 0..=rows.len() {
6234 let y = top - i as f64 * row_h;
6235 table += &format!("{} {y} m {} {y} l S\n", columns[0], columns[4]);
6236 }
6237 for x in columns {
6238 table += &format!("{x} {top} m {x} {} l S\n", top - rows.len() as f64 * row_h);
6239 }
6240 for (r, row) in rows.iter().enumerate() {
6241 for (c, text) in row.iter().enumerate() {
6242 let (x0, x1) = (columns[c], columns[c + 1]);
6243 let y1 = top - r as f64 * row_h;
6244 let y0 = y1 - row_h;
6245 table += &format!(
6246 "q {x0} {y0} {} {} re W n BT /F1 9 Tf {} {} Td ({text}) Tj ET Q\n",
6247 x1 - x0,
6248 y1 - y0,
6249 x0 + 3.0,
6250 y1 - 15.0
6251 );
6252 }
6253 }
6254 let (words, lines) = read(&table);
6255 let split = |s: &str| s.split(' ').map(String::from).collect::<Vec<_>>();
6256 let want_words: Vec<String> = rows.iter().flatten().flat_map(|t| split(t)).collect();
6257 assert_eq!(words, want_words);
6258 assert_eq!(
6261 lines,
6262 [
6263 "Code",
6264 "Description",
6265 "Unit",
6266 "Amount",
6267 "AB-1001-XYZ",
6268 "Replacement of the ventilation unit, roof level",
6269 "pcs",
6270 "1",
6271 "AB-1002 Gutter cleaning",
6272 "m",
6273 "120",
6274 "AB-1003-LONG",
6275 "Repainting of window frames and fascia boards",
6276 "m2",
6277 "85",
6278 ]
6279 );
6280
6281 let runs = |rs: &[(&str, f64, f64)]| -> String {
6283 rs.iter()
6284 .map(|(t, x, w)| {
6285 format!("q {x} 697 {w} 12 re W n BT /F1 10 Tf {x} 700 Td ({t}) Tj ET Q\n")
6286 })
6287 .collect()
6288 };
6289 let (words, lines) = read(&runs(&[
6291 ("Hel", 100.0, 15.0),
6292 ("lo", 115.0, 7.78),
6293 ("World", 125.56, 26.11),
6294 ]));
6295 assert_eq!(
6296 (words, lines),
6297 (
6298 vec!["Hello".into(), "World".into()],
6299 vec!["Hello World".into()]
6300 )
6301 );
6302 for visible in [12.0, 20.0] {
6304 let (words, lines) = read(&runs(&[("Hello", 100.0, visible), ("World", 115.0, 26.11)]));
6305 assert_eq!(words, ["Hello", "World"], "{visible}");
6306 assert_eq!(lines, ["Hello", "World"], "{visible}");
6307 }
6308 let (words, lines) = read(
6311 "BT /F1 10 Tf 100 700 Td (Montclai) Tj ET\n\
6312 q 100 697 38 12 re W n BT /F1 10 Tf 137.23 700 Td (r) Tj ET Q\n",
6313 );
6314 assert_eq!(
6315 (words, lines),
6316 (vec!["Montclair".into()], vec!["Montclair".into()])
6317 );
6318 let mut x = 100.0;
6321 let mut content = String::new();
6322 for (t, adv) in [
6323 ("a", 5.56),
6324 ("u", 5.56),
6325 ("f", 2.78),
6326 ("g", 5.56),
6327 ("e", 5.56),
6328 ("-", 3.33),
6329 ] {
6330 let clip = if t == "-" {
6331 format!("{} 697 2.0 12 re W n ", x + 0.6)
6332 } else {
6333 format!("{x} 697 {adv} 12 re W n ")
6334 };
6335 content += &format!("q {clip}BT /F1 10 Tf {x} 700 Td ({t}) Tj ET Q\n");
6336 x += adv;
6337 }
6338 let (words, lines) = read(&content);
6339 assert_eq!(
6340 (words, lines),
6341 (vec!["aufge-".into()], vec!["aufge-".into()])
6342 );
6343 let (_, lines) = read(
6346 "BT /F1 10 Tf 100 700 Td (d) Tj ET\n\
6347 q 105.3 697 0.3 12 re W n BT /F1 10 Tf 100 700 Td (d) Tj ET Q\n\
6348 BT /F1 10 Tf 105.56 700 Td (en) Tj ET\n",
6349 );
6350 assert_eq!(lines.len(), 1, "{lines:?}");
6351 let (_, lines) = read(
6354 "q 0 0 300 792 re W n BT /F1 12 Tf 72 700 Td (TOKEN) Tj ET Q\n\
6355 BT /F1 12 Tf 72 660 Td (OTHER LINE) Tj ET\n\
6356 q 0 0 400 792 re W n BT /F1 12 Tf 72.01 700.01 Td (TOKEN) Tj ET Q\n",
6357 );
6358 assert_eq!(lines, ["TOKEN", "OTHER LINE", "TOKEN"]);
6359 }
6360
6361 #[test]
6369 fn small_text_keeps_repeated_letters() {
6370 const T: &[u8] =
6371 b"<</Type/Font/Subtype/Type1/BaseFont/Times-Roman/Encoding/WinAnsiEncoding>>";
6372 const TEXT: &str = "Committee Participant benefits illegible";
6373 for size in ["12", "2", "1", "0.8", "0.5"] {
6374 for copies in [1, 2] {
6375 let run = format!("/F1 {size} Tf 50 400 Td ({TEXT}) Tj");
6376 let mut content = format!("BT 0 Tr {run} ET\n");
6377 if copies == 2 {
6378 content = format!("BT 1 Tr {run} ET\n{content}");
6379 }
6380 let text: String = cells(&pdf_with_content(T, content.as_bytes()))
6381 .iter()
6382 .map(|c| c.text.as_str())
6383 .collect::<Vec<_>>()
6384 .join(" ");
6385 if size == "12" {
6386 assert_eq!(text, TEXT, "{size} pt × {copies}");
6387 } else {
6388 let letters =
6389 |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
6390 assert_eq!(
6391 letters(&text),
6392 letters(TEXT),
6393 "{size} pt × {copies}: {text:?}"
6394 );
6395 }
6396 }
6397 }
6398 }
6399
6400 #[test]
6409 fn same_face_under_two_resource_keys_is_one_font_for_the_sanitizer() {
6410 let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6411 let f2 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding<</Type/Encoding\
6412 /BaseEncoding/WinAnsiEncoding/Differences[129/fi]>>>>";
6413 let content = b"BT 12 TL 72 720 Td \
6414 /F1 12 Tf (The ) Tj /F2 12 Tf (\\201nancial position) Tj \
6415 /F1 12 Tf ( of the company is shown in ) Tj /F2 12 Tf (\\201gure 3) Tj \
6416 /F1 12 Tf ( with the ) Tj /F2 12 Tf (\\201rst results.) Tj \
6417 T* T* /F2 12 Tf (Same words in /F2 only: \\201nancial, \\201gure, \\201rst.) Tj ET\n";
6418 let cs = cells(&pdf_with_fonts(&[f1, f2], content));
6419 let lines: Vec<&str> = cs.iter().map(|c| c.text.as_str()).collect();
6420 assert_eq!(
6421 lines,
6422 [
6423 "The financial position of the company is shown in figure 3 with the first results.",
6424 "Same words in /F2 only: financial, figure, first.",
6425 ],
6426 "{cs:?}"
6427 );
6428 }
6429
6430 #[test]
6437 fn different_faces_keep_the_font_barrier_only_under_legacy() {
6438 let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6439 let f2 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica-Bold/Encoding/WinAnsiEncoding>>";
6440 let content = b"BT 72 720 Td /F2 12 Tf (Total:) Tj /F1 12 Tf (42) Tj ET\n";
6441 let pdf = pdf_with_fonts(&[f1, f2], content);
6442 let lines = |gap| {
6443 let mut p = super::PageTextParser::open(&pdf).expect("opens");
6444 p.set_word_gap(Some(gap));
6445 p.cells(0)
6446 .prose
6447 .into_iter()
6448 .map(|c| c.text)
6449 .collect::<Vec<_>>()
6450 };
6451 assert_eq!(lines(crate::dp_lines::WordGap::Legacy), ["Total:", "42"]);
6452 assert_eq!(lines(crate::dp_lines::WordGap::Adaptive), ["Total:42"]);
6453 }
6454
6455 #[test]
6463 fn a_space_the_next_glyph_is_drawn_over_is_not_a_character() {
6464 let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6465 let lines = |content: &[u8]| {
6466 let pdf = pdf_with_content(f1, content);
6467 super::PageTextParser::open(&pdf)
6468 .expect("opens")
6469 .cells(0)
6470 .prose
6471 .into_iter()
6472 .map(|c| c.text)
6473 .collect::<Vec<_>>()
6474 };
6475 assert_eq!(
6478 lines(b"BT /F1 12 Tf 72 700 Td [(EG \\() ( ) 300 (1) ( ) 300 (\\) erf)] TJ ET\n"),
6479 ["EG (1) erf"]
6480 );
6481 assert_eq!(
6482 lines(b"BT /F1 12 Tf 72 700 Td [(EG \\() ( ) 100 (1) ( ) 100 (\\) erf)] TJ ET\n"),
6483 ["EG ( 1 ) erf"]
6484 );
6485 assert_eq!(
6487 lines(b"BT /F1 12 Tf 72 700 Td (first line ) Tj 0 -14 Td (second) Tj ET\n"),
6488 ["first line", "second"]
6489 );
6490 assert_eq!(
6494 lines(b"BT 0 1 -1 0 300 100 Tm /F1 12 Tf (Nullam mollis) Tj ET\n"),
6495 ["Nullam mollis"]
6496 );
6497 }
6498
6499 fn letter_spaced(words: &[&str], within: i32, between: i32) -> Vec<String> {
6505 letter_spaced_under(crate::dp_lines::WordGap::Adaptive, words, within, between)
6506 }
6507
6508 fn letter_spaced_under(
6510 gap: crate::dp_lines::WordGap,
6511 words: &[&str],
6512 within: i32,
6513 between: i32,
6514 ) -> Vec<String> {
6515 let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6516 let mut tj = String::new();
6517 for (wi, word) in words.iter().enumerate() {
6518 for (ci, ch) in word.chars().enumerate() {
6519 if wi + ci > 0 {
6520 let offset = if ci == 0 { between } else { within };
6521 tj.push_str(&format!("( ) {offset} "));
6522 }
6523 match ch {
6524 '(' | ')' => tj.push_str(&format!("(\\{ch}) ")),
6525 _ => tj.push_str(&format!("({ch}) ")),
6526 }
6527 }
6528 }
6529 let content = format!("BT /F1 7.5 Tf 1 0 0 1 72 700 Tm [{tj}] TJ ET\n");
6530 let pdf = pdf_with_content(f1, content.as_bytes());
6531 let mut parser = super::PageTextParser::open(&pdf).expect("opens");
6532 parser.set_word_gap(Some(gap));
6533 parser
6534 .cells(0)
6535 .prose
6536 .iter()
6537 .flat_map(|c| c.text.split(' ').map(str::to_owned).collect::<Vec<_>>())
6538 .collect()
6539 }
6540
6541 #[test]
6550 fn letters_set_apart_with_space_glyphs_are_one_word() {
6551 let heading = ["KPI", "bezogen", "auf", "den", "Umsatz", "(Umsatz-KPI)"];
6552 assert_eq!(letter_spaced(&heading, 50, -400), heading);
6553 assert_eq!(letter_spaced(&heading, 50, -6000), heading);
6558 assert_eq!(letter_spaced(&["INHALT"], 50, 0), ["INHALT"]);
6560 assert_eq!(
6563 letter_spaced_under(crate::dp_lines::WordGap::Factor(0.2), &heading, 50, -400),
6564 heading
6565 );
6566 let legacy = letter_spaced_under(crate::dp_lines::WordGap::Legacy, &heading, 50, -400);
6570 assert_eq!(legacy[..3], ["K", "P", "I"], "{legacy:?}");
6571 }
6572
6573 #[test]
6577 fn single_letters_between_spaces_are_not_always_letter_spacing() {
6578 let each = |words: &[&str]| -> Vec<String> {
6579 words
6580 .iter()
6581 .flat_map(|w| w.chars().map(String::from))
6582 .collect()
6583 };
6584 let heading = ["KPI", "bezogen", "auf"];
6585 assert_eq!(letter_spaced(&heading, 0, -400), each(&heading));
6587 assert_eq!(letter_spaced(&heading, -100, -400), each(&heading));
6588 assert_eq!(letter_spaced(&heading, 50, 0), each(&heading));
6591 let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6594 let line = |content: &[u8]| -> Vec<String> {
6595 super::PageTextParser::open(&pdf_with_content(f1, content))
6596 .expect("opens")
6597 .cells(0)
6598 .prose
6599 .into_iter()
6600 .map(|c| c.text)
6601 .collect()
6602 };
6603 assert_eq!(
6604 line(
6605 b"BT /F1 10 Tf 72 700 Td \
6606 [(von) ( ) 50 (a) ( ) 50 (b) ( ) 50 (c) ( ) 50 (d) ( ) 50 (bis)] TJ ET\n"
6607 ),
6608 ["von a b c d bis"]
6609 );
6610 assert_eq!(letter_spaced(&["CCCCC"], 50, 0), each(&["CCCCC"]));
6613 assert_eq!(letter_spaced(&["12345"], 50, 0), each(&["12345"]));
6614 }
6615
6616 #[test]
6627 fn the_page_shapes_follow_docling_parse() {
6628 let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6629 let shapes = |content: &[u8]| {
6630 let pdf = pdf_with_content(f1, content);
6631 super::PageTextParser::open(&pdf)
6632 .expect("opens")
6633 .cells(0)
6634 .shapes
6635 };
6636 let s = shapes(b"2 w 72 400 m 540 400 l S\n");
6637 assert_eq!(s.lines, vec![[72.0, 442.0, 540.0, 442.0]]);
6638 assert_eq!(s.boxes, vec![[71.0, 441.0, 541.0, 443.0]]);
6640
6641 let s = shapes(b"72 300 468 1 re f\n");
6642 assert!(s.lines.is_empty(), "a fill strokes no line");
6643 assert_eq!(s.boxes, vec![[72.0, 541.0, 540.0, 542.0]]);
6644
6645 let s = shapes(b"100 100 200 50 re S\n");
6647 assert_eq!(s.lines.len(), 4);
6648
6649 let s = shapes(b"72 400 m 100 450 l 200 300 300 500 400 400 c S\n");
6650 assert!(s.lines.is_empty(), "neither a diagonal nor a curve");
6651 assert_eq!(s.boxes.len(), 1);
6652
6653 let s = shapes(b"q 0 0 300 842 re W n 72 400 m 540 400 l S 400 100 m 400 700 l S Q\n");
6654 assert_eq!(
6655 s.lines,
6656 vec![[72.0, 442.0, 300.0, 442.0]],
6657 "cut to the clip"
6658 );
6659 assert_eq!(s.boxes.len(), 1, "the vertical rule is clipped away");
6660
6661 let s = shapes(b"/Pattern cs /P0 scn 72 300 468 1 re f\n");
6662 assert!(s.lines.is_empty() && s.boxes.is_empty());
6663
6664 let s = shapes(b"72 300 100 1 re f 172 300 100 1 re f 400 600 10 10 re f\n");
6666 assert_eq!(
6667 s.boxes,
6668 vec![[72.0, 541.0, 272.0, 542.0], [400.0, 232.0, 410.0, 242.0]]
6669 );
6670
6671 let s = shapes(
6679 b"56.64 690.22 33.504 1.44 re f 90.144 690.22 1.44 1.44 re f \
6680 91.584 690.22 54.48 1.44 re f 146.06 690.22 1.44 1.44 re f \
6681 147.5 690.22 159.86 1.44 re f 307.37 690.22 1.44 1.44 re f \
6682 308.81 690.22 50.304 1.44 re f\n",
6683 );
6684 let spans: Vec<(f32, f32)> = s.boxes.iter().map(|b| (b[0], b[2])).collect();
6685 assert_eq!(spans, vec![(56.64, 307.36), (307.37, 359.114)]);
6686 }
6687
6688 #[test]
6690 fn transparent_paths_are_no_shapes() {
6691 let rule = |closed| super::ShapeSub {
6692 start: (0.0, 0.0),
6693 cur: (100.0, 0.0),
6694 pts: vec![(0.0, 0.0), (100.0, 0.0)],
6695 lines: vec![((0.0, 0.0), (100.0, 0.0))],
6696 closed,
6697 };
6698 let gs = |stroke_alpha, fill_alpha| super::ShapeGs {
6699 stroke_alpha,
6700 fill_alpha,
6701 ..super::ShapeGs::INIT
6702 };
6703 let mut shapes = super::Shapes::default();
6704 super::record_shape(&[rule(false)], true, false, &gs(0.0, 1.0), 1.0, &mut shapes);
6705 assert_eq!(shapes, super::Shapes::default());
6706 super::record_shape(&[rule(true)], false, true, &gs(1.0, 0.0), 1.0, &mut shapes);
6707 assert_eq!(shapes, super::Shapes::default());
6708 super::record_shape(&[rule(false)], true, false, &gs(0.5, 0.0), 1.0, &mut shapes);
6709 assert_eq!(shapes.lines.len(), 1);
6710 }
6711
6712 #[test]
6715 fn a_run_drawn_again_over_itself_is_read_once() {
6716 let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica-Bold/Encoding/WinAnsiEncoding>>";
6717 let lines = |content: &[u8]| {
6718 let pdf = pdf_with_content(f1, content);
6719 super::PageTextParser::open(&pdf)
6720 .expect("opens")
6721 .cells(0)
6722 .prose
6723 .into_iter()
6724 .map(|c| c.text)
6725 .collect::<Vec<_>>()
6726 };
6727 assert_eq!(
6729 lines(
6730 b"BT 0 g /F1 18 Tf 1 0 0 1 72 720 Tm (Safety instructions) Tj ET\n\
6731 BT 0.8 0 0 rg /F1 18 Tf 1 0 0 1 71.5 720.5 Tm (Safety instructions) Tj ET\n"
6732 ),
6733 ["Safety instructions"]
6734 );
6735 assert_eq!(
6737 lines(
6738 b"BT /F1 14 Tf 1 0 0 1 72 656 Tm (Maintenance) Tj ET\n\
6739 BT /F1 14 Tf 1 0 0 1 71.2 656.8 Tm (Maintenance) Tj ET\n\
6740 BT /F1 11 Tf 1 0 0 1 72 632 Tm (Clean the filter) Tj ET\n"
6741 ),
6742 ["Maintenance", "Clean the filter"]
6743 );
6744 assert_eq!(
6746 lines(b"BT /F1 12 Tf 72 700 Td (very very small) Tj ET\n"),
6747 ["very very small"]
6748 );
6749 assert_eq!(
6750 lines(b"BT /F1 12 Tf 72 700 Td (Hello, all) Tj ET\n"),
6751 ["Hello, all"]
6752 );
6753 assert_eq!(
6754 lines(b"BT /F1 12 Tf 72 700 Td (Total) Tj 0 -14 Td (Total) Tj ET\n"),
6755 ["Total", "Total"]
6756 );
6757 for tc in ["-2.28", "-2.08", "-1.78"] {
6761 let content = format!(
6762 "BT /F1 10 Tf 72 700 Td (Contents) Tj {tc} Tc (..........) Tj 0 Tc ( 5) Tj ET\n"
6763 );
6764 assert_eq!(
6765 lines(content.as_bytes()),
6766 ["Contents.......... 5"],
6767 "Tc {tc}"
6768 );
6769 }
6770 }
6771
6772 #[test]
6775 fn actual_text_replaces_the_glyphs_of_its_span() {
6776 let helvetica = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6777 let caron = b"<</Type/Font/Subtype/TrueType/BaseFont/SynthCaron/FirstChar 77/LastChar 77\
6780 /Widths[0]/Encoding/WinAnsiEncoding/FontDescriptor<</Type/FontDescriptor\
6781 /FontName/SynthCaron/Flags 32/FontBBox[-540 -200 0 800]/ItalicAngle 0/Ascent 800\
6782 /Descent -200/CapHeight 700/StemV 80>>>>";
6783 let ligature = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica\
6785 /Encoding<</Type/Encoding/BaseEncoding/WinAnsiEncoding/Differences[1/fi]>>>>";
6786 let text = |content: &str| {
6787 let pdf = pdf_with_fonts(&[helvetica, caron, ligature], content.as_bytes());
6788 super::PageTextParser::open(&pdf)
6789 .expect("opens")
6790 .cells(0)
6791 .prose
6792 .into_iter()
6793 .map(|c| c.text)
6794 .collect::<String>()
6795 };
6796 assert_eq!(
6798 text("BT /F1 24 Tf 40 50 Td (Ore) Tj (s) Tj /F2 24 Tf <4D> Tj /F1 24 Tf (i) Tj ET"),
6799 "OresMi"
6800 );
6801 assert_eq!(
6803 text(
6804 "BT /F1 24 Tf 40 50 Td (Ore) Tj /Span <</ActualText <FEFF0161>>> BDC \
6805 (s) Tj /F2 24 Tf <4D> Tj EMC /F1 24 Tf (i) Tj ET"
6806 ),
6807 "Oreši"
6808 );
6809 assert_eq!(
6811 text("BT /F1 24 Tf 40 50 Td /Span <</ActualText (ab)>> BDC (xy) Tj EMC (z) Tj ET"),
6812 "abz"
6813 );
6814 assert_eq!(
6816 text("BT /F3 24 Tf 40 50 Td <01> Tj /F1 24 Tf (a) Tj ET"),
6817 "fia"
6818 );
6819 assert_eq!(
6820 text(
6821 "BT /F3 24 Tf 40 50 Td /Span <</ActualText (XY)>> BDC <01> Tj \
6822 /F1 24 Tf (a) Tj EMC (z) Tj ET"
6823 ),
6824 "XYz"
6825 );
6826 let hyphen = text(
6829 "BT /F1 24 Tf 40 50 Td (exam) Tj /Span <</ActualText <FEFF>>> BDC (-) Tj EMC \
6830 (ple) Tj ET",
6831 );
6832 assert!(!hyphen.contains('-'), "{hyphen}");
6833 assert_eq!(hyphen.replace(' ', ""), "example");
6834 assert_eq!(
6836 text(
6837 "BT /F1 24 Tf 40 50 Td /Span <</ActualText (A long description that belongs \
6838 in Alt not here)>> BDC (ab) Tj EMC ET"
6839 ),
6840 "ab"
6841 );
6842 assert_eq!(
6844 text(
6845 "BT /F1 24 Tf 40 50 Td (x) Tj ET /Span <</ActualText (ghost)>> BDC \
6846 10 10 50 50 re f EMC"
6847 ),
6848 "x"
6849 );
6850 assert_eq!(
6852 text("BT /F1 24 Tf 40 50 Td /OC /MC0 BDC (ok) Tj EMC ET"),
6853 "ok"
6854 );
6855 assert_eq!(
6857 text(
6858 "BT /F1 24 Tf 40 50 Td /Span <</ActualText (AB)>> BDC (a) Tj \
6859 /Span <</ActualText (Z)>> BDC (b) Tj EMC EMC ET"
6860 ),
6861 "AB"
6862 );
6863 let nested = |depth: usize| {
6865 text(&format!(
6866 "BT /F1 24 Tf 40 50 Td {}/Span <</ActualText (z)>> BDC (a) Tj EMC{} ET",
6867 "/X BMC ".repeat(depth),
6868 " EMC".repeat(depth)
6869 ))
6870 };
6871 assert_eq!(nested(super::MAX_ACTUAL_TEXT_DEPTH - 1), "z");
6872 assert_eq!(nested(super::MAX_ACTUAL_TEXT_DEPTH), "a");
6873 }
6874
6875 #[test]
6878 fn actual_text_one_for_one_keeps_each_cells_box() {
6879 let glyph = |ch, x: f32, pen: f32| super::Glyph {
6880 ch,
6881 l: x,
6882 b: 0.0,
6883 r: x + 5.0,
6884 t: 10.0,
6885 ll: x,
6886 lb: -2.0,
6887 lr: x + 5.0,
6888 lt: 10.0,
6889 font: 0,
6890 quad: None,
6891 pen: Some([pen, 0.0, 10.0]),
6892 math_font: false,
6893 invisible: false,
6894 spaced: false,
6895 clip: None,
6896 exact: 0,
6897 };
6898 let mut out = vec![
6899 glyph('o', 0.0, 0.0),
6900 glyph('f', 10.0, 10.0),
6901 glyph('i', 15.0, 10.0),
6902 glyph('a', 20.0, 20.0),
6903 ];
6904 super::apply_actual_text(&mut out, 1, "XY");
6905 let got: Vec<(char, f32)> = out.iter().map(|g| (g.ch, g.l)).collect();
6906 assert_eq!(got, [('o', 0.0), ('X', 10.0), ('Y', 20.0)]);
6907 }
6908
6909 #[test]
6914 fn math_faces_are_named_like_docling_parse_names_them() {
6915 for name in [
6916 "ABCDEF+CMR7",
6917 "CMMI10",
6918 "MSBM10",
6919 "Cambria-Math",
6920 "Symbol",
6921 "MTExtra",
6922 ] {
6923 assert!(super::is_math_font_name(name.as_bytes()), "{name}");
6924 }
6925 for name in ["Helvetica", "ABCDEF+TimesNewRomanPSMT", "Arial-BoldMT"] {
6926 assert!(!super::is_math_font_name(name.as_bytes()), "{name}");
6927 }
6928 }
6929
6930 #[test]
6931 fn sanitizer_font_name_follows_docling_parse_precedence() {
6932 use lopdf::{dictionary, Document, Object};
6933 let mut doc = Document::with_version("1.4");
6934 let fd_a =
6935 doc.add_object(dictionary! { "Type" => "FontDescriptor", "FontName" => "AAAAAA+Face" });
6936 let fd_b =
6937 doc.add_object(dictionary! { "Type" => "FontDescriptor", "FontName" => "BBBBBB+Face" });
6938 let with = |fd: Option<lopdf::ObjectId>, base: &str| {
6939 let mut d = dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => base };
6940 if let Some(id) = fd {
6941 d.set("FontDescriptor", Object::Reference(id));
6942 }
6943 d
6944 };
6945 let name = |d: &lopdf::Dictionary| {
6946 String::from_utf8(super::sanitizer_font_name(&doc, d, false)).unwrap()
6947 };
6948 assert_eq!(name(&with(Some(fd_a), "Face")), "AAAAAA+Face");
6949 assert_eq!(name(&with(Some(fd_b), "Face")), "BBBBBB+Face");
6950 assert_eq!(name(&with(None, "ABCDEF+Face")), "ABCDEF+Face");
6951 assert_eq!(
6952 name(&dictionary! { "Type" => "Font", "Name" => "F7" }),
6953 "F7"
6954 );
6955 assert_eq!(name(&dictionary! { "Type" => "Font" }), "null");
6956 }
6957}
6958
6959#[cfg(test)]
6960mod overpainted {
6961 use crate::pdfium_backend::TextCell;
6962
6963 fn cell(text: &str, l: f32, t: f32, r: f32, b: f32) -> TextCell {
6964 TextCell {
6965 text: text.into(),
6966 l,
6967 t,
6968 r,
6969 b,
6970 }
6971 }
6972
6973 #[test]
6977 fn stacked_logo_glyphs_are_dropped() {
6978 let mut cells = vec![
6979 cell("\"", 72.7, 21.5, 86.4, 31.5),
6980 cell("==", 59.4, 21.5, 99.6, 31.5),
6981 cell("Herr", 65.2, 151.3, 81.7, 161.3),
6982 ];
6983 super::drop_overpainted_cells(&mut cells);
6984 assert_eq!(cells.len(), 1, "cells: {cells:?}");
6985 assert_eq!(cells[0].text, "Herr");
6986 }
6987
6988 #[test]
6992 fn prose_and_double_draw_are_kept() {
6993 let mut cells = vec![
6994 cell("Telefon", 354.3, 133.2, 381.5, 143.2),
6995 cell("0676/2000", 387.3, 133.2, 428.7, 143.2),
6996 cell("Bold", 100.0, 50.0, 130.0, 60.0),
6997 cell("Bold", 100.3, 50.0, 130.3, 60.0),
6998 ];
6999 super::drop_overpainted_cells(&mut cells);
7000 assert_eq!(cells.len(), 4);
7001 }
7002
7003 #[test]
7011 fn lines_of_a_tall_box_font_are_not_paint() {
7012 let mut cells = vec![
7013 cell(
7014 "17. Carefully pour off the supernatant from both tubes. Invert the",
7015 72.0,
7016 77.1,
7017 514.4,
7018 132.7,
7019 ),
7020 cell(
7021 "tubes and tap them gently on the surface of a clean paper towel.",
7022 72.0,
7023 88.8,
7024 453.0,
7025 144.4,
7026 ),
7027 cell("“Evidence A” DNA*", 77.6, 412.5, 150.6, 462.7),
7028 cell("“Evidence B” DNA*", 77.6, 423.0, 150.5, 473.2),
7029 cell("enzyme mixture*", 77.6, 444.1, 143.9, 494.4),
7030 cell("\"", 72.7, 600.0, 86.4, 655.6),
7032 cell("==", 59.4, 600.0, 99.6, 655.6),
7033 ];
7034 super::drop_overpainted_cells(&mut cells);
7035 let texts: Vec<&str> = cells.iter().map(|c| c.text.as_str()).collect();
7036 assert_eq!(texts.len(), 5, "{texts:?}");
7037 assert!(
7038 !texts.contains(&"==") && !texts.contains(&"\""),
7039 "{texts:?}"
7040 );
7041 }
7042
7043 #[test]
7051 fn a_tall_box_font_keeps_its_lines_on_the_text_layer_page() {
7052 let widths = "500 ".repeat(91);
7053 let font = format!(
7054 "<</Type/Font/Subtype/TrueType/BaseFont/Cambria/Encoding/WinAnsiEncoding\
7055 /FirstChar 32/LastChar 122/Widths[{widths}]\
7056 /FontDescriptor<</Type/FontDescriptor/FontName/Cambria/Flags 32\
7057 /FontBBox[-1475 -2464 2868 3117]/Ascent 3117/Descent -2464\
7058 /ItalicAngle 0/StemV 80>>>>"
7059 );
7060 let content = b"BT /F1 10 Tf 72 700 Td \
7061 (Carefully pour off the supernatant from both of the tubes) Tj \
7062 0 -12 Td (and tap them gently on the surface of a clean towel) Tj \
7063 0 -12 Td (to drain them.) Tj ET\n";
7064 let pdf = super::base14_fonts::pdf_with_content(font.as_bytes(), content);
7065 let page = super::pdf_text_pages(&pdf).remove(0);
7066 assert!(
7067 page.cells.iter().all(|c| c.b - c.t > 50.0),
7068 "the boxes are the font's 5.6 em: {:?}",
7069 page.cells
7070 );
7071 let lines: Vec<&str> = page.cells.iter().map(|c| c.text.as_str()).collect();
7072 assert_eq!(
7073 lines,
7074 [
7075 "Carefully pour off the supernatant from both of the tubes",
7076 "and tap them gently on the surface of a clean towel",
7077 "to drain them.",
7078 ]
7079 );
7080 assert_eq!(page.word_cells.len(), 24, "{:?}", page.word_cells);
7081 }
7082}
7083
7084#[cfg(test)]
7085mod vestigial_layer {
7086 use crate::pdfium_backend::{PdfPage, TextCell};
7087
7088 fn page_with(texts: &[&str]) -> PdfPage {
7089 let cells = texts
7090 .iter()
7091 .enumerate()
7092 .map(|(i, t)| TextCell {
7093 text: t.to_string(),
7094 l: 10.0,
7095 t: 10.0 + 12.0 * i as f32,
7096 r: 90.0,
7097 b: 20.0 + 12.0 * i as f32,
7098 })
7099 .collect();
7100 PdfPage::from_cells(595.0, 842.0, 1.0, cells)
7101 }
7102
7103 #[test]
7108 fn typed_in_form_fields_are_not_a_text_layer() {
7109 let pages = vec![
7110 page_with(&["03", "05", "2025"]),
7111 page_with(&[]),
7112 page_with(&[]),
7113 ];
7114 assert!(super::text_layer_is_vestigial(&pages));
7115 assert!(super::text_layer_is_vestigial(&[page_with(&[])]));
7116 }
7117
7118 #[test]
7121 fn sparse_but_real_documents_pass() {
7122 let one_pager = vec![page_with(&[
7123 "Confidential briefing",
7124 "Prepared for the board meeting",
7125 "Do not distribute",
7126 ])];
7127 assert!(!super::text_layer_is_vestigial(&one_pager));
7128 }
7129}
7130
7131#[cfg(test)]
7135mod form_cache {
7136 use lopdf::content::{Content, Operation};
7137 use lopdf::{dictionary, Document, Object, Stream};
7138
7139 fn form(doc: &mut Document, text: &str) -> lopdf::ObjectId {
7140 let ops = vec![
7141 Operation::new("BT", vec![]),
7142 Operation::new("Tf", vec!["F1".into(), 12.into()]),
7143 Operation::new("Td", vec![40.into(), 500.into()]),
7144 Operation::new("Tj", vec![Object::string_literal(text)]),
7145 Operation::new("ET", vec![]),
7146 ];
7147 let data = Content { operations: ops }.encode().unwrap();
7148 doc.add_object(Stream::new(
7149 dictionary! { "Type" => "XObject", "Subtype" => "Form",
7150 "BBox" => vec![0.into(), 0.into(), 595.into(), 842.into()] },
7151 data,
7152 ))
7153 }
7154
7155 #[test]
7156 fn single_use_forms_are_not_retained_shared_ones_are() {
7157 let mut doc = Document::with_version("1.5");
7158 let pages_id = doc.new_object_id();
7159 let font = doc.add_object(
7160 dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" },
7161 );
7162 let header = form(&mut doc, "Header");
7163 let mut kids = Vec::new();
7164 let mut own_forms = Vec::new();
7165 for p in 0..3 {
7166 let own = form(&mut doc, &format!("Body{p}"));
7167 own_forms.push(own);
7168 let content = doc.add_object(Stream::new(
7169 dictionary! {},
7170 b"q /Hd Do Q q /Fx Do Q".to_vec(),
7171 ));
7172 kids.push(Object::Reference(doc.add_object(dictionary! {
7173 "Type" => "Page", "Parent" => pages_id,
7174 "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
7175 "Contents" => content,
7176 "Resources" => dictionary! {
7177 "Font" => dictionary! { "F1" => font },
7178 "XObject" => dictionary! { "Hd" => header, "Fx" => own },
7179 },
7180 })));
7181 }
7182 doc.objects.insert(
7183 pages_id,
7184 Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => 3 }),
7185 );
7186 let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
7187 doc.trailer.set("Root", catalog);
7188
7189 let mut caches = super::DocCaches::default();
7190 let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
7191 pages.sort_by_key(|(n, _)| *n);
7192 for (i, (_, pid)) in pages.iter().enumerate() {
7193 let text: String = super::page_glyphs_cached(&doc, *pid, &mut caches)
7194 .iter()
7195 .map(|g| g.ch)
7196 .collect();
7197 assert!(text.contains("Header"), "page {i}: {text:?}");
7199 assert!(text.contains(&format!("Body{i}")), "page {i}: {text:?}");
7200 }
7201 assert!(caches.forms.contains_key(&header));
7204 for own in &own_forms {
7205 assert!(!caches.forms.contains_key(own));
7206 }
7207 assert_eq!(caches.forms.len(), 1);
7208 }
7209}
7210
7211#[cfg(test)]
7212mod cid_collections {
7213 use super::base14_fonts::{cells, pdf_with_content};
7214
7215 fn type0(encoding: &str) -> Vec<u8> {
7216 format!(
7217 "<</Type/Font/Subtype/Type0/BaseFont/Test-Font-Light/Encoding/{encoding}\
7218 /DescendantFonts[<</Type/Font/Subtype/CIDFontType0/BaseFont/Test-Font-Light\
7219 /CIDSystemInfo<</Registry(Adobe)/Ordering(Japan1)/Supplement 7>>/DW 1000>>]>>"
7220 )
7221 .into_bytes()
7222 }
7223
7224 fn text(fontdict: &[u8], hex: &str) -> String {
7225 let content = format!("BT /F1 12 Tf 72 700 Td <{hex}> Tj ET\n");
7226 cells(&pdf_with_content(fontdict, content.as_bytes()))
7227 .iter()
7228 .map(|c| c.text.as_str())
7229 .collect()
7230 }
7231
7232 #[test]
7233 #[cfg(feature = "cid-collections")]
7234 fn identity_codes_read_through_the_collection() {
7235 assert_eq!(text(&type0("Identity-H"), "0CD40E8A07A0"), "日本語");
7236 }
7237
7238 #[test]
7239 fn unicode_keyed_cmaps_read_the_code() {
7240 assert_eq!(text(&type0("UniJIS-UCS2-H"), "65E5672C8A9E"), "日本語");
7241 }
7242
7243 #[test]
7244 #[cfg(feature = "cid-collections")]
7245 fn collection_ranges_keep_supplementary_characters() {
7246 assert_eq!(text(&type0("Identity-H"), "0CD44507450807A0"), "日𢭏𢭐語");
7247 let text = |o: &[u8], cid| super::collection_text(super::collection_table(o).unwrap(), cid);
7248 assert_eq!(text(b"Japan1", 0x2714).as_deref(), Some("🄐"));
7249 assert_eq!(text(b"CNS1", 0x3a32).as_deref(), Some("𡤃"));
7250 }
7251
7252 #[test]
7253 #[cfg(feature = "cid-collections")]
7254 fn collection_entries_are_plain_characters() {
7255 assert_eq!(text(&type0("Identity-H"), "046D"), "逢");
7256 let text = |o: &[u8], cid| super::collection_text(super::collection_table(o).unwrap(), cid);
7257 assert_eq!(text(b"Korea1", 8752), None);
7258 assert_eq!(text(b"KR", 11704), None);
7259 assert_eq!(text(b"Japan1", 0x1ffd).as_deref(), Some("sec"));
7260 }
7261
7262 #[test]
7263 fn tounicode_ranges_increment_the_utf16_string() {
7264 let map = super::parse_tounicode(
7265 b"3 beginbfrange\n\
7266 <01> <02> <d842dfb7>\n\
7267 <03> <04> <00660069>\n\
7268 <05> <06> <0061>\n\
7269 endbfrange",
7270 );
7271 assert_eq!(map[&1], "𠮷");
7272 assert_eq!(map[&2], "𠮸");
7273 assert_eq!(map[&3], "fi");
7274 assert_eq!(map[&4], "fj");
7275 assert_eq!(map[&5], "a");
7276 assert_eq!(map[&6], "b");
7277 }
7278
7279 #[test]
7280 fn tounicode_skips_lone_surrogates_overflows_and_huge_ranges() {
7281 let map = super::parse_tounicode(
7282 b"2 beginbfchar\n<01> <d842>\n<02> <0041>\nendbfchar\n\
7283 4 beginbfrange\n\
7284 <10> <11> [<dc00> <0042>]\n\
7285 <20> <22> <0041fffe>\n\
7286 <30> <31> <d842dfff>\n\
7287 <00010000> <ffffffff> <>\n\
7288 endbfrange",
7289 );
7290 assert!(!map.contains_key(&0x01));
7291 assert_eq!(map[&0x02], "A");
7292 assert!(!map.contains_key(&0x10));
7293 assert_eq!(map[&0x11], "B");
7294 assert_eq!(map[&0x20], "A\u{fffe}");
7295 assert_eq!(map[&0x21], "A\u{ffff}");
7296 assert!(!map.contains_key(&0x22));
7297 assert_eq!(map[&0x30], "\u{20bff}");
7298 assert!(!map.contains_key(&0x31));
7299 assert_eq!(map[&0x1ffff], "");
7300 assert_eq!(map.len(), 5 + 0x10000);
7301 }
7302
7303 #[test]
7304 fn utf16_pairs_are_one_glyph_and_one_advance() {
7305 let font = type0("UniJIS-UTF16-H");
7306 assert_eq!(text(&font, "65E5D842DFB78A9E"), "日𠮷語");
7307 let content = b"BT /F1 12 Tf 72 700 Td <65E5D842DFB78A9E> Tj ET\n";
7308 let pdf = pdf_with_content(&font, content);
7309 let doc = lopdf::Document::load_mem(&pdf).unwrap();
7310 let glyphs = super::page_glyphs(&doc, doc.get_pages()[&1]);
7311 assert_eq!(glyphs.len(), 3);
7312 assert!((glyphs[2].l - glyphs[0].l - 24.0).abs() < 0.001);
7313 }
7314
7315 #[test]
7316 fn utf16_codes_preserve_tounicode_keys_and_identity_cids() {
7317 use lopdf::{dictionary, Document};
7318 let doc = Document::with_version("1.4");
7319 let dict = dictionary! {"Subtype" => "Type0", "Encoding" => "UniJIS-UTF16-H"};
7320 let mut font = super::parse_font(&doc, b"F1", &dict);
7321 assert_eq!(
7322 super::codes(&font, &[0xd8, 0x42, 0xdf, 0xb7]),
7323 vec![0xd842dfb7]
7324 );
7325 font.to_unicode.insert(0xd842dfb7, "override".into());
7326 assert_eq!(font.decode_code(0xd842dfb7).0.as_deref(), Some("override"));
7327 assert_eq!(
7328 super::codes(&font, &[0xd8, 0x42, 0x65, 0xe5]),
7329 vec![0xd842, 0x65e5]
7330 );
7331 let dict = dictionary! {"Subtype" => "Type0", "Encoding" => "Identity-H"};
7332 let font = super::parse_font(&doc, b"F1", &dict);
7333 assert_eq!(
7334 super::codes(&font, &[0xd8, 0x42, 0xdf, 0xb7]),
7335 vec![0xd842, 0xdfb7]
7336 );
7337 }
7338}