-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtounicode.rs
More file actions
3632 lines (3353 loc) · 125 KB
/
Copy pathtounicode.rs
File metadata and controls
3632 lines (3353 loc) · 125 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! ToUnicode CMap parsing for PDF text extraction
//!
//! This module parses ToUnicode CMaps to convert CID-encoded text to Unicode.
use log::{debug, warn};
use lopdf::{Document, Object, ObjectId};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
#[cfg(not(target_arch = "wasm32"))]
use std::path::{Path, PathBuf};
use crate::glyph_names::glyph_to_char;
#[cfg(target_arch = "wasm32")]
static BUILTIN_CMAPS: include_dir::Dir<'_> =
include_dir::include_dir!("$CARGO_MANIFEST_DIR/external/bcmaps");
/// A parsed ToUnicode CMap mapping CIDs to Unicode strings
#[derive(Debug, Default, Clone)]
pub struct ToUnicodeCMap {
/// Direct character mappings (CID -> Unicode codepoint(s))
pub char_map: HashMap<u16, String>,
/// Range mappings (start_cid, end_cid) -> base_unicode
pub ranges: Vec<(u16, u16, u32)>,
/// Byte width of source codes (1 or 2), determined from codespace and CMap entries
pub code_byte_length: u8,
/// When true, unmapped CIDs are interpreted as Unicode codepoints directly.
/// Used as a last resort for Identity-H fonts without ToUnicode/cmap/glyph names.
pub cid_passthrough: bool,
}
/// Detect whether a parsed ToUnicode CMap is a degenerate full-range identity
/// bfrange (`<0000> <FFFF> <0000>`) with no other mappings.
///
/// Some PDF producers (notably dompdf) emit this single range as the entire
/// ToUnicode, asserting that every CID equals its Unicode codepoint. For
/// subset CIDFontType2 fonts where CIDs are renumbered GIDs, that identity is
/// false, and the range silently corrupts roughly a third of CJK characters
/// into Latin-1 mojibake. The correct mapping must come from the embedded
/// TrueType `cmap` table instead.
///
/// Returns `true` when the CMap consists of exactly one range covering the
/// full 16-bit CID space with a base offset of 0, and has no `char_map`
/// entries. The caller should treat such a CMap as absent.
fn is_degenerate_identity_bfrange(cmap: &ToUnicodeCMap) -> bool {
cmap.char_map.is_empty()
&& cmap.ranges.len() == 1
&& cmap.ranges[0].0 == 0
&& cmap.ranges[0].1 == 0xFFFF
&& cmap.ranges[0].2 == 0
}
pub(crate) fn build_cmap_entry_from_stream(
data: &[u8],
font_dict: &lopdf::Dictionary,
doc: &Document,
obj_num: u32,
) -> Option<CMapEntry> {
if let Some(cmap) = ToUnicodeCMap::parse(data) {
if is_degenerate_identity_bfrange(&cmap) {
debug!(
"ToUnicode obj={}: full-range identity bfrange detected; treating as absent",
obj_num
);
} else {
let (mut primary, mut remapped) = try_remap_subset_cmap(cmap, font_dict, doc, obj_num);
let mut fallback = build_fallback_tounicode_from_encoding(font_dict, doc)
.or_else(|| build_fallback_cmap_for_type0(font_dict, doc))
.or_else(|| build_fallback_cmap_for_simple(font_dict, doc));
let primary_entries = primary.char_map.len() + primary.ranges.len();
if primary_entries < 10 {
if let Some(fb) = fallback.take() {
debug!(
"ToUnicode CMap obj={} too sparse ({} entries); using fallback",
obj_num, primary_entries
);
remapped = Some(primary);
primary = fb;
}
}
// When a sequential remap was applied and a TrueType fallback has more
// entries than the primary ToUnicode CMap, prefer the TrueType cmap.
// Subset fonts number GIDs by document encounter order, so the sorted
// sequential remap scrambles characters. The TrueType cmap table maps
// the real GID→Unicode and is authoritative.
if remapped.is_some() {
if let Some(ref fb) = fallback {
let fb_entries = fb.char_map.len() + fb.ranges.len();
if fb_entries > primary_entries {
debug!(
"ToUnicode CMap obj={}: TrueType fallback ({} entries) > primary ({}); promoting over sequential remap",
obj_num, fb_entries, primary_entries
);
let old_remap = remapped.take().unwrap();
remapped = fallback.take();
fallback = Some(old_remap);
}
}
}
return Some(CMapEntry {
primary,
remapped,
fallback,
});
} // else: degenerate identity bfrange - fall through to fallback
}
let fallback = build_fallback_cmap_for_type0(font_dict, doc)
.or_else(|| build_fallback_cmap_for_simple(font_dict, doc))?;
debug!(
"ToUnicode CMap obj={} parse failed; using fallback (entries={})",
obj_num,
fallback.char_map.len()
);
Some(CMapEntry {
primary: fallback,
remapped: None,
fallback: None,
})
}
impl ToUnicodeCMap {
/// Create a new empty CMap
pub fn new() -> Self {
Self::default()
}
/// Parse a ToUnicode CMap from its decompressed content
pub fn parse(content: &[u8]) -> Option<Self> {
let text = String::from_utf8_lossy(content);
let mut cmap = ToUnicodeCMap::new();
let mut src_hex_lengths: Vec<usize> = Vec::new();
let mut use_cmap_name: Option<String> = None;
// Parse begincodespacerange ... endcodespacerange to determine byte width
let mut codespace_byte_len: Option<u8> = None;
if let Some(cs_start) = text.find("begincodespacerange") {
let section_start = cs_start + "begincodespacerange".len();
if let Some(cs_end) = text[section_start..].find("endcodespacerange") {
let section = &text[section_start..section_start + cs_end];
// Parse hex values to determine byte length
let mut in_hex = false;
let mut hex_len = 0;
for c in section.chars() {
if c == '<' {
in_hex = true;
hex_len = 0;
} else if c == '>' {
if in_hex && hex_len > 0 {
let byte_len = (hex_len + 1) / 2; // 2 hex digits = 1 byte
codespace_byte_len = Some(byte_len as u8);
}
in_hex = false;
} else if in_hex && c.is_ascii_hexdigit() {
hex_len += 1;
}
}
}
}
// Parse "usecmap" if present
if let Some(name) = find_usecmap_name(&text) {
use_cmap_name = Some(name);
}
// Parse beginbfchar ... endbfchar sections
let mut pos = 0;
while let Some(start) = text[pos..].find("beginbfchar") {
let section_start = pos + start + "beginbfchar".len();
if let Some(end) = text[section_start..].find("endbfchar") {
let section = &text[section_start..section_start + end];
cmap.parse_bfchar_section(section, &mut src_hex_lengths);
pos = section_start + end;
} else {
break;
}
}
// Parse beginbfrange ... endbfrange sections
pos = 0;
while let Some(start) = text[pos..].find("beginbfrange") {
let section_start = pos + start + "beginbfrange".len();
if let Some(end) = text[section_start..].find("endbfrange") {
let section = &text[section_start..section_start + end];
cmap.parse_bfrange_section(section, &mut src_hex_lengths);
pos = section_start + end;
} else {
break;
}
}
if cmap.char_map.is_empty() && cmap.ranges.is_empty() {
return None;
}
// Determine byte width: use codespace if available, otherwise infer from entries
cmap.code_byte_length = if let Some(cs_len) = codespace_byte_len {
// If codespace says 2-byte but ALL entries use 1-byte source codes
// (hex length <= 2), treat as 1-byte. This handles the common case where
// codespace is <0000><FFFF> but entries are <20>, <41>, etc.
if cs_len == 2 && !src_hex_lengths.is_empty() && src_hex_lengths.iter().all(|&l| l <= 2)
{
1
} else {
cs_len
}
} else if !src_hex_lengths.is_empty() {
// No codespace declaration: infer from entry hex lengths
let max_hex_len = src_hex_lengths.iter().max().copied().unwrap_or(4);
if max_hex_len <= 2 {
1
} else {
2
}
} else {
2 // Default to 2-byte
};
// Sort ranges by start CID for binary search in lookup()
cmap.ranges.sort_unstable_by_key(|&(start, _, _)| start);
if let Some(name) = use_cmap_name {
if let Some(base) = load_builtin_cmap_by_name(&name) {
cmap = merge_cmaps(base, cmap);
} else {
warn!("usecmap={} could not be loaded", name);
}
}
Some(cmap)
}
/// Parse a bfchar section: <src> <dst> pairs
fn parse_bfchar_section(&mut self, section: &str, src_hex_lengths: &mut Vec<usize>) {
// Match pairs of hex values: <XXXX> <YYYY>
let mut chars = section.chars().peekable();
loop {
// Skip whitespace
while chars.peek().is_some_and(|c| c.is_whitespace()) {
chars.next();
}
// Look for opening <
if chars.peek() != Some(&'<') {
break;
}
chars.next(); // consume <
// Read source hex
let mut src_hex = String::new();
while chars.peek().is_some_and(|&c| c != '>') {
if let Some(c) = chars.next() {
src_hex.push(c);
}
}
chars.next(); // consume >
// Track source hex length for byte width detection
let trimmed_src = src_hex.trim();
if !trimmed_src.is_empty() {
src_hex_lengths.push(trimmed_src.len());
}
// Skip whitespace
while chars.peek().is_some_and(|c| c.is_whitespace()) {
chars.next();
}
// Look for opening <
if chars.peek() != Some(&'<') {
continue;
}
chars.next(); // consume <
// Read destination hex
let mut dst_hex = String::new();
while chars.peek().is_some_and(|&c| c != '>') {
if let Some(c) = chars.next() {
dst_hex.push(c);
}
}
chars.next(); // consume >
// Parse and store mapping
if let (Some(src), Some(dst)) =
(parse_hex_u16(&src_hex), hex_to_unicode_string(&dst_hex))
{
self.char_map.insert(src, dst);
}
}
}
/// Parse a bfrange section: <start> <end> <base> or <start> <end> [<u1> <u2> ...] triplets
fn parse_bfrange_section(&mut self, section: &str, src_hex_lengths: &mut Vec<usize>) {
let mut chars = section.chars().peekable();
loop {
// Skip whitespace
while chars.peek().is_some_and(|c| c.is_whitespace()) {
chars.next();
}
// Look for opening <
if chars.peek() != Some(&'<') {
break;
}
chars.next(); // consume <
// Read start hex
let mut start_hex = String::new();
while chars.peek().is_some_and(|&c| c != '>') {
if let Some(c) = chars.next() {
start_hex.push(c);
}
}
chars.next(); // consume >
// Track source hex length
let trimmed_start = start_hex.trim();
if !trimmed_start.is_empty() {
src_hex_lengths.push(trimmed_start.len());
}
// Skip whitespace
while chars.peek().is_some_and(|c| c.is_whitespace()) {
chars.next();
}
// Read end hex
if chars.peek() != Some(&'<') {
continue;
}
chars.next();
let mut end_hex = String::new();
while chars.peek().is_some_and(|&c| c != '>') {
if let Some(c) = chars.next() {
end_hex.push(c);
}
}
chars.next();
// Skip whitespace
while chars.peek().is_some_and(|c| c.is_whitespace()) {
chars.next();
}
// Read base - could be <hex> or [array]
if chars.peek() == Some(&'<') {
chars.next();
let mut base_hex = String::new();
while chars.peek().is_some_and(|&c| c != '>') {
if let Some(c) = chars.next() {
base_hex.push(c);
}
}
chars.next();
// Store range mapping
if let (Some(start), Some(end), Some(base)) = (
parse_hex_u16(&start_hex),
parse_hex_u16(&end_hex),
hex_to_unicode_scalar(&base_hex),
) {
self.ranges.push((start, end, base));
}
} else if chars.peek() == Some(&'[') {
// Array format: [<unicode1> <unicode2> ...]
// Each entry maps to start_cid + index
chars.next(); // consume [
if let (Some(start), Some(end)) =
(parse_hex_u16(&start_hex), parse_hex_u16(&end_hex))
{
let mut cid = start;
loop {
// Skip whitespace
while chars.peek().is_some_and(|c| c.is_whitespace()) {
chars.next();
}
if chars.peek() == Some(&']') {
chars.next();
break;
}
if chars.peek() != Some(&'<') {
break;
}
chars.next(); // consume <
let mut hex = String::new();
while chars.peek().is_some_and(|&c| c != '>') {
if let Some(c) = chars.next() {
hex.push(c);
}
}
chars.next(); // consume >
if let Some(unicode_str) = hex_to_unicode_string(&hex) {
self.char_map.insert(cid, unicode_str);
}
if cid >= end {
// Skip remaining entries and closing bracket
while chars.peek().is_some_and(|&c| c != ']') {
chars.next();
}
if chars.peek() == Some(&']') {
chars.next();
}
break;
}
cid = cid.saturating_add(1);
}
} else {
// Couldn't parse start/end, skip the array
while chars.peek().is_some_and(|&c| c != ']') {
chars.next();
}
if chars.peek() == Some(&']') {
chars.next();
}
}
}
}
}
/// Look up a CID and return the Unicode string
pub fn lookup(&self, cid: u16) -> Option<String> {
// First check direct mappings
if let Some(s) = self.char_map.get(&cid) {
return Some(s.clone());
}
// Binary search through sorted ranges
let idx = self
.ranges
.binary_search_by(|&(start, _, _)| start.cmp(&cid))
.unwrap_or_else(|i| i);
// Check the range at idx (where start == cid)
if idx < self.ranges.len() {
let (start, end, base) = self.ranges[idx];
if cid >= start && cid <= end {
let unicode = base + (cid - start) as u32;
if let Some(c) = char::from_u32(unicode) {
return Some(c.to_string());
}
}
}
// Check the range before idx (cid may fall within a range that starts before it)
if idx > 0 {
let (start, end, base) = self.ranges[idx - 1];
if cid >= start && cid <= end {
let unicode = base + (cid - start) as u32;
if let Some(c) = char::from_u32(unicode) {
return Some(c.to_string());
}
}
}
None
}
/// Per-byte CMap lookup without Latin-1 fallback.
/// Returns `(raw_byte, Option<cmap_result>)` for each byte.
/// Only meaningful for single-byte (code_byte_length==1) CMaps.
pub fn lookup_bytes(&self, bytes: &[u8]) -> Vec<(u8, Option<String>)> {
bytes
.iter()
.map(|&b| {
let code = b as u16;
let result = self.lookup(code).filter(|s| !s.contains('\u{FFFD}'));
(b, result)
})
.collect()
}
/// Decode a byte slice to a Unicode string, respecting the CMap's code byte width
pub fn decode_cids(&self, bytes: &[u8]) -> String {
let mut result = String::new();
let mut unmapped_count = 0usize;
if self.code_byte_length == 1 {
// Single-byte codes: each byte is a code
for &b in bytes {
let code = b as u16;
match self.lookup(code) {
Some(s) if !s.contains('\u{FFFD}') => result.push_str(&s),
_ => {
// For single-byte unmapped codes, try as Latin-1
// (the byte IS the character code in most legacy encodings)
if b >= 0x20 {
result.push(b as char);
}
unmapped_count += 1;
}
}
}
} else {
// Two-byte codes: CIDs are 2 bytes each (big-endian)
for chunk in bytes.chunks(2) {
if chunk.len() == 2 {
let cid = u16::from_be_bytes([chunk[0], chunk[1]]);
match self.lookup(cid) {
Some(s) if !s.contains('\u{FFFD}') => result.push_str(&s),
_ => {
if self.cid_passthrough {
// Last-resort: treat CID as Unicode codepoint.
// Valid for Identity-H fonts where the PDF generator
// used Unicode values as CIDs but stripped the cmap.
if let Some(ch) = char::from_u32(cid as u32) {
if !ch.is_control() || ch == '\t' || ch == '\n' {
result.push(ch);
} else {
unmapped_count += 1;
}
} else {
unmapped_count += 1;
}
} else {
// CIDs are font-internal indices, not Unicode values.
// Unmapped 2-byte CIDs are skipped to avoid CJK garbage.
unmapped_count += 1;
}
}
}
}
}
}
// If too many codes were unmapped, signal failure by returning empty
// so the caller can fall through to other decoding methods
let total = if self.code_byte_length == 1 {
bytes.len()
} else {
bytes.len() / 2
};
if total > 0 && unmapped_count > total / 2 {
return String::new();
}
result
}
/// Get the minimum source CID across all mappings (char_map + ranges).
fn min_source_cid(&self) -> Option<u16> {
let char_min = self.char_map.keys().copied().min();
let range_min = self.ranges.iter().map(|&(start, _, _)| start).min();
match (char_min, range_min) {
(Some(a), Some(b)) => Some(a.min(b)),
(a @ Some(_), None) => a,
(None, b @ Some(_)) => b,
(None, None) => None,
}
}
/// Get the maximum source CID across all mappings (char_map + ranges).
fn max_source_cid(&self) -> Option<u16> {
let char_max = self.char_map.keys().copied().max();
let range_max = self.ranges.iter().map(|&(_, end, _)| end).max();
match (char_max, range_max) {
(Some(a), Some(b)) => Some(a.max(b)),
(a @ Some(_), None) => a,
(None, b @ Some(_)) => b,
(None, None) => None,
}
}
/// Remap a CMap that references pre-subsetting GIDs to sequential post-subsetting GIDs.
/// Collects all source CIDs, sorts them, and reassigns to 1, 2, 3, ...
///
/// Range expansion stops after `MAX_CID_W_EXPANSION` CID visits, counting
/// overwrites, so repeated full-width `bfrange`s cannot re-expand the
/// 16-bit domain. Later overlapping ranges that would have introduced new
/// CIDs after that many visits are truncated.
pub fn remap_to_sequential(&self) -> ToUnicodeCMap {
let mut cid_to_unicode: HashMap<u16, String> = HashMap::new();
expand_bfranges_for_remap(&self.ranges, &mut cid_to_unicode, MAX_CID_W_EXPANSION);
// char_map entries override range entries
for (&cid, unicode) in &self.char_map {
cid_to_unicode.insert(cid, unicode.clone());
}
// Sort old CIDs ascending
let mut old_cids: Vec<u16> = cid_to_unicode.keys().copied().collect();
old_cids.sort_unstable();
// Build new CMap with sequential CIDs starting at 1
let mut new_cmap = ToUnicodeCMap::new();
for (i, &old_cid) in old_cids.iter().enumerate() {
let new_cid = (i + 1) as u16; // GID 0 is .notdef, content CIDs start at 1
if let Some(unicode) = cid_to_unicode.get(&old_cid) {
new_cmap.char_map.insert(new_cid, unicode.clone());
}
}
new_cmap.code_byte_length = self.code_byte_length;
new_cmap
}
}
/// Expand `bfrange` entries into individual CID→Unicode inserts.
/// Returns how many CIDs were visited. Counts overwrites so a repeated
/// full-width range cannot keep working after `max_assignments`.
fn expand_bfranges_for_remap(
ranges: &[(u16, u16, u32)],
cid_to_unicode: &mut HashMap<u16, String>,
max_assignments: usize,
) -> usize {
let mut assigned = 0usize;
'ranges: for &(start, end, base) in ranges {
if start > end {
continue;
}
for cid in start..=end {
if assigned >= max_assignments {
break 'ranges;
}
assigned += 1;
let unicode_cp = base + (cid - start) as u32;
if let Some(ch) = char::from_u32(unicode_cp) {
cid_to_unicode.insert(cid, ch.to_string());
}
}
}
assigned
}
/// Parse a hex string to u16
fn parse_hex_u16(hex: &str) -> Option<u16> {
u16::from_str_radix(hex.trim(), 16).ok()
}
/// Convert a ToUnicode destination hex string to Unicode.
///
/// PDF ToUnicode destinations are UTF-16BE strings. Supplementary-plane
/// characters are encoded as surrogate pairs, so treating each 4-hex chunk as
/// a scalar drops emoji like D83CDF1F.
fn hex_to_unicode_string(hex: &str) -> Option<String> {
let hex: String = hex.chars().filter(|ch| !ch.is_ascii_whitespace()).collect();
if hex.is_empty() || !hex.len().is_multiple_of(2) {
return None;
}
let bytes: Option<Vec<u8>> = (0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok())
.collect();
let bytes = bytes?;
if bytes.len().is_multiple_of(2) {
let units: Vec<u16> = bytes
.chunks_exact(2)
.map(|chunk| u16::from_be_bytes([chunk[0], chunk[1]]))
.collect();
if let Ok(result) = String::from_utf16(&units) {
if !result.is_empty() {
return Some(normalize_tounicode_destination(result));
}
}
}
// Be permissive for non-standard one-byte destinations.
if bytes.len() == 1 {
let ch = bytes[0] as char;
if !ch.is_control() || ch == '\t' || ch == '\n' {
return Some(ch.to_string());
}
}
None
}
fn normalize_tounicode_destination(text: String) -> String {
let is_multi_char = text.chars().nth(1).is_some();
// Some malformed producer CMaps put a list of alternative whitespace or
// hyphen codepoints into one destination. Keep ordinary multi-character
// mappings intact unless that malformed signature is present.
if is_multi_char
&& text.chars().all(char::is_whitespace)
&& text.chars().any(|ch| matches!(ch, '\t' | '\n' | '\r'))
{
return if text.contains('\t') {
"\t".to_string()
} else {
" ".to_string()
};
}
if is_multi_char
&& text.contains('\u{00ad}')
&& text.chars().all(|ch| {
matches!(
ch,
'-' | '\u{00ad}' | '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2212}'
)
})
{
return "-".to_string();
}
text
}
fn hex_to_unicode_scalar(hex: &str) -> Option<u32> {
let text = hex_to_unicode_string(hex)?;
let mut chars = text.chars();
let ch = chars.next()?;
if chars.next().is_none() {
Some(ch as u32)
} else {
None
}
}
fn find_usecmap_name(text: &str) -> Option<String> {
for line in text.lines() {
if line.contains("usecmap") {
let parts: Vec<&str> = line.split_whitespace().collect();
for i in 0..parts.len() {
if parts[i] == "usecmap" && i > 0 {
let name = parts[i - 1].trim();
if let Some(stripped) = name.strip_prefix('/') {
return Some(stripped.to_string());
}
}
}
}
}
None
}
/// Navigate to the first DescendantFont dictionary of a Type0 font.
fn get_descendant_cid_font<'a>(
font_dict: &'a lopdf::Dictionary,
doc: &'a Document,
) -> Option<&'a lopdf::Dictionary> {
let desc_fonts_obj = font_dict.get(b"DescendantFonts").ok()?;
let arr = match desc_fonts_obj {
Object::Array(arr) => arr,
Object::Reference(r) => match doc.get_object(*r) {
Ok(Object::Array(arr)) => arr,
_ => return None,
},
_ => return None,
};
if arr.is_empty() {
return None;
}
match &arr[0] {
Object::Reference(r) => doc.get_dictionary(*r).ok(),
Object::Dictionary(d) => Some(d),
_ => None,
}
}
/// Get the starting CID from a CIDFont's W (widths) array.
fn get_w_array_start_cid(cid_font_dict: &lopdf::Dictionary, doc: &Document) -> Option<u16> {
let w_obj = cid_font_dict.get(b"W").ok()?;
let arr = match w_obj {
Object::Array(arr) => arr,
Object::Reference(r) => match doc.get_object(*r) {
Ok(Object::Array(arr)) => arr,
_ => return None,
},
_ => return None,
};
if arr.is_empty() {
return None;
}
match &arr[0] {
Object::Integer(n) => Some(*n as u16),
Object::Reference(r) => match doc.get_object(*r) {
Ok(Object::Integer(n)) => Some(*n as u16),
_ => None,
},
_ => None,
}
}
/// Return true if the CIDFont's W (widths) array explicitly covers the given CID.
///
/// The W array uses two formats (PDF 32000-1:2008, §9.7.4.3):
/// 1. `c [w1 w2 ... wn]` — widths for CIDs c, c+1, ..., c+n-1
/// 2. `c_first c_last w` — CIDs c_first..c_last all have width w
fn w_array_covers_cid(cid_font_dict: &lopdf::Dictionary, doc: &Document, target: u16) -> bool {
let Ok(w_obj) = cid_font_dict.get(b"W") else {
return false;
};
let arr = match w_obj {
Object::Array(arr) => arr,
Object::Reference(r) => match doc.get_object(*r) {
Ok(Object::Array(arr)) => arr,
_ => return false,
},
_ => return false,
};
let resolve_int = |o: &Object| -> Option<i64> {
match o {
Object::Integer(n) => Some(*n),
Object::Reference(r) => match doc.get_object(*r) {
Ok(Object::Integer(n)) => Some(*n),
_ => None,
},
_ => None,
}
};
let resolve_arr = |o: &Object| -> Option<Vec<Object>> {
match o {
Object::Array(a) => Some(a.clone()),
Object::Reference(r) => match doc.get_object(*r) {
Ok(Object::Array(a)) => Some(a.clone()),
_ => None,
},
_ => None,
}
};
let target = target as i64;
let mut i = 0usize;
while i < arr.len() {
let Some(first) = resolve_int(&arr[i]) else {
break;
};
i += 1;
if i >= arr.len() {
break;
}
// Peek at arr[i] to decide format.
if let Some(widths) = resolve_arr(&arr[i]) {
// Format 1: c [w1 ... wn]
let last = first + widths.len() as i64 - 1;
if target >= first && target <= last {
return true;
}
i += 1;
} else if let Some(last) = resolve_int(&arr[i]) {
// Format 2: c_first c_last w
i += 1;
if i < arr.len() {
i += 1; // skip the width value
}
if target >= first && target <= last {
return true;
}
} else {
// Unknown token — abort parsing safely
break;
}
}
false
}
/// Extract CIDToGIDMap as a vector of GIDs (u16) indexed by CID.
fn get_cid_to_gid_map(cid_font_dict: &lopdf::Dictionary, doc: &Document) -> Option<Vec<u16>> {
let obj = cid_font_dict.get(b"CIDToGIDMap").ok()?;
match obj {
Object::Name(n) if n.as_slice() == b"Identity" => None,
Object::Reference(r) => match doc.get_object(*r) {
Ok(Object::Stream(s)) => parse_cid_to_gid_stream(&s.decompressed_content().ok()?),
_ => None,
},
Object::Stream(s) => parse_cid_to_gid_stream(&s.decompressed_content().ok()?),
_ => None,
}
}
fn parse_cid_to_gid_stream(data: &[u8]) -> Option<Vec<u16>> {
if data.len() < 2 {
return None;
}
let mut map = Vec::with_capacity(data.len() / 2);
for chunk in data.chunks_exact(2) {
map.push(u16::from_be_bytes([chunk[0], chunk[1]]));
}
Some(map)
}
/// Build a CID→Unicode CMap by applying a CIDToGIDMap to an existing CMap that maps GID→Unicode.
fn build_cmap_with_cid_to_gid_map(
cmap: &ToUnicodeCMap,
cid_to_gid: &[u16],
) -> Option<ToUnicodeCMap> {
let mut new_cmap = ToUnicodeCMap::new();
for (cid, &gid) in cid_to_gid.iter().enumerate() {
if let Some(s) = cmap.lookup(gid) {
new_cmap.char_map.insert(cid as u16, s);
}
}
if new_cmap.char_map.is_empty() {
None
} else {
new_cmap.code_byte_length = 2;
Some(new_cmap)
}
}
/// Detect and fix broken ToUnicode CMaps from subset fonts with GID mismatch.
///
/// Some PDF generators subset-embed fonts by renumbering GIDs sequentially (1, 2, 3...)
/// but fail to update the ToUnicode CMap, which still references original GID values.
/// This detects the mismatch and remaps the CMap to sequential positions.
fn try_remap_subset_cmap(
cmap: ToUnicodeCMap,
font_dict: &lopdf::Dictionary,
doc: &Document,
obj_num: u32,
) -> (ToUnicodeCMap, Option<ToUnicodeCMap>) {
// Only applies to Identity-H/V CID fonts
let encoding = font_dict
.get(b"Encoding")
.ok()
.and_then(|o| o.as_name().ok());
if encoding != Some(b"Identity-H") && encoding != Some(b"Identity-V") {
return (cmap, None);
}
// CMap's minimum source CID must be > 2 (indicating old, non-sequential GIDs)
let min_cid = match cmap.min_source_cid() {
Some(c) if c > 2 => c,
_ => return (cmap, None),
};
// Navigate to DescendantFonts[0]
let cid_font_dict = match get_descendant_cid_font(font_dict, doc) {
Some(d) => d,
None => return (cmap, None),
};
// Both repair paths below assume CIDs are glyph indices that a subsetter can
// renumber, which is only true for CIDFontType2 (TrueType). For CIDFontType0
// (CFF), CIDs are resolved through the CFF charset, so a valid CMap stays valid
// after subsetting and renumbering it corrupts otherwise-correct text.
// CIDToGIDMap is likewise CIDFontType2-only (PDF 32000-1:2008, 9.7.4.2), so this
// also ignores a CIDToGIDMap that a malformed producer attached to a CFF font.
// /Subtype may be an indirect reference, so resolve it through the document.
// Only bail out when the descendant is *explicitly* something other than
// CIDFontType2: a missing or unresolvable /Subtype keeps the previous
// behaviour rather than silently disabling the repair.
let subtype = cid_font_dict.get(b"Subtype").ok().and_then(|o| match o {
Object::Reference(r) => doc.get_object(*r).ok().and_then(|o| o.as_name().ok()),
other => other.as_name().ok(),
});
if subtype.is_some_and(|name| name != b"CIDFontType2") {
debug!("Subset remap skipped for obj={obj_num}: descendant is not CIDFontType2");
return (cmap, None);
}
// If there's an explicit CIDToGIDMap, build a repaired CMap using it.
if let Some(cid_to_gid) = get_cid_to_gid_map(cid_font_dict, doc) {
if let Some(repaired) = build_cmap_with_cid_to_gid_map(&cmap, &cid_to_gid) {
debug!(
"CIDToGIDMap repair applied for obj={}: {} entries",
obj_num,
repaired.char_map.len()
);
return (cmap, Some(repaired));
}
// Fall through to sequential remap if repair failed.
}
// W array must start at a low CID (≤ 2), indicating sequential post-subset GIDs
let w_start = match get_w_array_start_cid(cid_font_dict, doc) {
Some(c) if c <= 2 => c,
_ => return (cmap, None),
};
// If the W array actually covers the CMap's max source CID, the CMap is
// aligned with the font — no sequential renumbering happened. A sparse W
// array starting at CID 0 (for .notdef) with additional high-CID entries
// matching the CMap is the normal subset layout, not a mismatch.
if let Some(max_cid) = cmap.max_source_cid() {
if w_array_covers_cid(cid_font_dict, doc, max_cid) {
debug!(
"Subset remap skipped for obj={}: W array covers CMap max CID {}",
obj_num, max_cid
);
return (cmap, None);
}
}
debug!(
"Subset GID mismatch detected for obj={}: W starts at CID {}, CMap min CID {}. Remapping to sequential.",
obj_num, w_start, min_cid
);
let remapped = cmap.remap_to_sequential();
(cmap, Some(remapped))
}
/// Build a ToUnicodeCMap from an embedded TrueType font's cmap table.
///
/// For Identity-H CID fonts, CID == GID. The TrueType cmap maps Unicode→GID,
/// so we reverse it to get GID→Unicode (i.e. CID→Unicode).
pub fn build_cmap_from_truetype(font_data: &[u8]) -> Option<ToUnicodeCMap> {
let face = ttf_parser::Face::parse(font_data, 0).ok()?;