oxidize-pdf 2.4.2

A pure Rust PDF generation and manipulation library with zero external dependencies
Documentation
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
/// Utilities for analyzing and modifying PDF content streams
///
/// This module provides functions to extract font references, remap names,
/// and perform other content stream transformations needed for overlay operations.
use std::collections::{HashMap, HashSet};

/// Extract all font references from a content stream
///
/// Searches for "/Fx" patterns where x is a number or name, typically appearing
/// in font selection operators like "BT /F1 12 Tf (Hello) Tj ET"
///
/// # Arguments
/// * `content` - Raw content stream bytes
///
/// # Returns
/// Set of font names referenced in the stream (e.g., ["F1", "F2", "Arial"])
///
/// # Example
/// ```ignore
/// let content = b"BT /F1 12 Tf (Hello) Tj /F2 10 Tf (World) Tj ET";
/// let fonts = extract_font_references(content);
/// assert!(fonts.contains("F1"));
/// assert!(fonts.contains("F2"));
/// ```
#[allow(dead_code)] // Will be used in Phase 2
pub fn extract_font_references(content: &[u8]) -> HashSet<String> {
    let mut font_names = HashSet::new();

    // Convert to string for easier parsing
    let content_str = String::from_utf8_lossy(content);

    // Look for "/FontName" patterns followed by Tf operator
    // Pattern: /FontName <number> Tf
    for line in content_str.lines() {
        let tokens: Vec<&str> = line.split_whitespace().collect();

        for (i, token) in tokens.iter().enumerate() {
            // Check if this is a font name (starts with /)
            if token.starts_with('/') {
                // Check if followed by number and Tf (font selection operator)
                if i + 2 < tokens.len() {
                    // tokens[i+1] should be number (size)
                    // tokens[i+2] should be "Tf"
                    if tokens[i + 2] == "Tf" {
                        // Extract font name (remove leading /)
                        let font_name = token[1..].to_string();
                        font_names.insert(font_name);
                    }
                }
            }
        }
    }

    font_names
}

/// Rename fonts in a dictionary by adding a prefix
///
/// Takes a font dictionary and renames all font keys by adding "Orig" prefix.
/// This prevents naming conflicts between preserved fonts and overlay fonts.
///
/// # Arguments
/// * `fonts` - Font dictionary from preserved resources
///
/// # Returns
/// New dictionary with renamed fonts (/F1 → /OrigF1, /Arial → /OrigArial)
///
/// # Limitations
/// - Does not detect naming collisions if /OrigF1 already exists (rare but possible)
/// - Clones entire font dictionaries (acceptable for typical PDFs with <50 fonts)
/// - No validation that font names are valid PDF names
///
/// # Example
/// ```ignore
/// use std::collections::HashMap;
/// let mut fonts = HashMap::new();
/// fonts.insert("F1".to_string(), "font_dict_1");
/// fonts.insert("F2".to_string(), "font_dict_2");
///
/// let renamed = rename_preserved_fonts(&fonts);
/// assert!(renamed.contains_key("OrigF1"));
/// assert!(renamed.contains_key("OrigF2"));
/// ```
#[allow(dead_code)] // Will be used in Phase 2.3
pub fn rename_preserved_fonts(fonts: &crate::objects::Dictionary) -> crate::objects::Dictionary {
    let mut renamed = crate::objects::Dictionary::new();

    for (key, value) in fonts.iter() {
        // Add "Orig" prefix to font name
        let new_name = format!("Orig{}", key);
        renamed.set(new_name, value.clone());
    }

    renamed
}

/// Rewrite font references in a content stream using a name mapping
///
/// Searches for font selection operators ("/FontName size Tf") and replaces
/// the font names according to the provided mapping. This is used to update
/// content streams when fonts have been renamed to avoid conflicts.
///
/// # Arguments
/// * `content` - Original content stream bytes
/// * `mappings` - Map from old font names to new font names (e.g., "F1" → "OrigF1")
///
/// # Returns
/// New content stream with updated font references
///
/// # Limitations
/// - **Whitespace normalization**: Original whitespace (multiple spaces, tabs) is
///   normalized to single spaces. PDF remains valid but loses formatting fidelity.
/// - **Binary data risk**: Uses lossy UTF-8 conversion. Safe for text-only content streams,
///   but may corrupt streams with inline images or binary data (rare in practice).
/// - **Performance**: Creates complete copy of content stream. For very large streams
///   (>5MB), consider streaming approach.
/// - **No validation**: Does not verify that resulting PDF operators are valid.
///
/// # Example
/// ```ignore
/// use std::collections::HashMap;
/// let content = b"BT /F1 12 Tf (Hello) Tj ET";
/// let mut mappings = HashMap::new();
/// mappings.insert("F1".to_string(), "OrigF1".to_string());
///
/// let rewritten = rewrite_font_references(content, &mappings);
/// // Result: b"BT /OrigF1 12 Tf (Hello) Tj ET"
/// ```
#[allow(dead_code)] // Will be used in Phase 2.3
pub fn rewrite_font_references(content: &[u8], mappings: &HashMap<String, String>) -> Vec<u8> {
    let content_str = String::from_utf8_lossy(content);
    let mut result = String::new();

    for line in content_str.lines() {
        let tokens: Vec<&str> = line.split_whitespace().collect();
        let mut rewritten_line = String::new();

        let mut i = 0;
        while i < tokens.len() {
            let token = tokens[i];

            // Check if this is a font name (starts with /) followed by size and Tf
            if token.starts_with('/') && i + 2 < tokens.len() && tokens[i + 2] == "Tf" {
                // Extract font name (without leading /)
                let font_name = &token[1..];

                // Check if we have a mapping for this font
                if let Some(new_name) = mappings.get(font_name) {
                    // Write renamed font
                    rewritten_line.push('/');
                    rewritten_line.push_str(new_name);
                } else {
                    // Keep original font name
                    rewritten_line.push_str(token);
                }
            } else {
                // Not a font reference, keep as-is
                rewritten_line.push_str(token);
            }

            // Add space after token (except for last token)
            if i < tokens.len() - 1 {
                rewritten_line.push(' ');
            }

            i += 1;
        }

        result.push_str(&rewritten_line);
        result.push('\n');
    }

    // Remove trailing newline if original didn't have it
    if !content.ends_with(b"\n") && result.ends_with('\n') {
        result.pop();
    }

    result.into_bytes()
}

/// Check if a font has embedded font data (FontFile/FontFile2/FontFile3)
///
/// Analyzes a font dictionary to determine if it contains embedded font program data.
/// Embedded fonts have a FontDescriptor that references font stream objects.
///
/// # Font Stream Types (ISO 32000-1):
/// - **FontFile**: Type 1 font program (PostScript)
/// - **FontFile2**: TrueType font program
/// - **FontFile3**: Subtype-specific font (CFF, OpenType, etc.)
///
/// # Arguments
/// * `font_dict` - Font dictionary to analyze
///
/// # Returns
/// `true` if font has embedded data, `false` for standard/base fonts
///
/// # Example
/// ```ignore
/// // Embedded font (e.g., Arial with TTF data)
/// let font_dict = Dictionary::from([
///     ("Type", "Font"),
///     ("FontDescriptor", Reference(10, 0)), // -> has FontFile2
/// ]);
/// assert!(has_embedded_font_data(&font_dict)); // true
///
/// // Standard font (e.g., Helvetica)
/// let standard_font = Dictionary::from([
///     ("Type", "Font"),
///     ("BaseFont", "Helvetica"),
/// ]);
/// assert!(!has_embedded_font_data(&standard_font)); // false
/// ```
#[allow(dead_code)] // Will be used in Phase 3.2
pub fn has_embedded_font_data(font_dict: &crate::objects::Dictionary) -> bool {
    use crate::objects::Object;

    // Check if font has a FontDescriptor
    if let Some(Object::Dictionary(descriptor)) = font_dict.get("FontDescriptor") {
        // Check for any of the three font stream types
        descriptor.contains_key("FontFile")
            || descriptor.contains_key("FontFile2")
            || descriptor.contains_key("FontFile3")
    } else if let Some(Object::Reference(_)) = font_dict.get("FontDescriptor") {
        // FontDescriptor is a reference - we need to resolve it to check
        // For now, assume it MIGHT have embedded data (conservative approach)
        // Phase 3.2 will handle proper resolution
        true
    } else {
        // No FontDescriptor = standard font (Helvetica, Times, etc.)
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_font_references_simple() {
        let content = b"BT /F1 12 Tf (Hello) Tj ET";
        let fonts = extract_font_references(content);

        assert_eq!(fonts.len(), 1);
        assert!(fonts.contains("F1"));
    }

    #[test]
    fn test_extract_font_references_multiple() {
        let content = b"BT /F1 12 Tf (Hello) Tj ET BT /F2 10 Tf (World) Tj ET";
        let fonts = extract_font_references(content);

        assert_eq!(fonts.len(), 2);
        assert!(fonts.contains("F1"));
        assert!(fonts.contains("F2"));
    }

    #[test]
    fn test_extract_font_references_with_named_fonts() {
        let content = b"BT /ArialBold 14 Tf (Test) Tj /Helvetica 10 Tf (More) Tj ET";
        let fonts = extract_font_references(content);

        assert_eq!(fonts.len(), 2);
        assert!(fonts.contains("ArialBold"));
        assert!(fonts.contains("Helvetica"));
    }

    #[test]
    fn test_extract_font_references_multiline() {
        let content = b"BT\n/F1 12 Tf\n(Line 1) Tj\nET\nBT\n/F2 10 Tf\n(Line 2) Tj\nET";
        let fonts = extract_font_references(content);

        assert_eq!(fonts.len(), 2);
        assert!(fonts.contains("F1"));
        assert!(fonts.contains("F2"));
    }

    #[test]
    fn test_extract_font_references_no_fonts() {
        let content = b"100 200 m 300 400 l S";
        let fonts = extract_font_references(content);

        assert_eq!(fonts.len(), 0);
    }

    #[test]
    fn test_extract_font_references_ignore_false_positives() {
        // /Pattern shouldn't be detected as a font (not followed by Tf)
        let content = b"/Pattern cs /P1 scn 100 100 m 200 200 l S";
        let fonts = extract_font_references(content);

        assert_eq!(fonts.len(), 0);
    }

    // Tests for rename_preserved_fonts

    #[test]
    fn test_rename_preserved_fonts_simple() {
        use crate::objects::{Dictionary, Object};

        let mut fonts = Dictionary::new();
        fonts.set("F1", Object::Integer(1));
        fonts.set("F2", Object::Integer(2));

        let renamed = rename_preserved_fonts(&fonts);

        assert_eq!(renamed.len(), 2);
        assert!(renamed.contains_key("OrigF1"));
        assert!(renamed.contains_key("OrigF2"));
        assert!(!renamed.contains_key("F1")); // Original keys should not exist
        assert!(!renamed.contains_key("F2"));
    }

    #[test]
    fn test_rename_preserved_fonts_named_fonts() {
        use crate::objects::{Dictionary, Object};

        let mut fonts = Dictionary::new();
        fonts.set("Arial", Object::Integer(10));
        fonts.set("Helvetica", Object::Integer(20));
        fonts.set("TimesNewRoman", Object::Integer(30));

        let renamed = rename_preserved_fonts(&fonts);

        assert_eq!(renamed.len(), 3);
        assert!(renamed.contains_key("OrigArial"));
        assert!(renamed.contains_key("OrigHelvetica"));
        assert!(renamed.contains_key("OrigTimesNewRoman"));
    }

    #[test]
    fn test_rename_preserved_fonts_preserves_values() {
        use crate::objects::{Dictionary, Object};

        let mut fonts = Dictionary::new();
        fonts.set("F1", Object::Integer(42));
        fonts.set("Arial", Object::String("test".to_string()));

        let renamed = rename_preserved_fonts(&fonts);

        // Values should be preserved
        assert_eq!(renamed.get("OrigF1"), Some(&Object::Integer(42)));
        assert_eq!(
            renamed.get("OrigArial"),
            Some(&Object::String("test".to_string()))
        );
    }

    #[test]
    fn test_rename_preserved_fonts_empty_dictionary() {
        use crate::objects::Dictionary;

        let fonts = Dictionary::new();
        let renamed = rename_preserved_fonts(&fonts);

        assert_eq!(renamed.len(), 0);
    }

    #[test]
    fn test_rename_preserved_fonts_complex_objects() {
        use crate::objects::{Dictionary, Object};

        let mut fonts = Dictionary::new();

        // Create a complex font dictionary
        let mut font_dict = Dictionary::new();
        font_dict.set("Type", Object::Name("Font".to_string()));
        font_dict.set("Subtype", Object::Name("Type1".to_string()));
        font_dict.set("BaseFont", Object::Name("Helvetica".to_string()));

        fonts.set("F1", Object::Dictionary(font_dict.clone()));

        let renamed = rename_preserved_fonts(&fonts);

        assert_eq!(renamed.len(), 1);
        assert!(renamed.contains_key("OrigF1"));

        // Verify the complex object is preserved
        if let Some(Object::Dictionary(dict)) = renamed.get("OrigF1") {
            assert_eq!(dict.get("Type"), Some(&Object::Name("Font".to_string())));
            assert_eq!(
                dict.get("Subtype"),
                Some(&Object::Name("Type1".to_string()))
            );
            assert_eq!(
                dict.get("BaseFont"),
                Some(&Object::Name("Helvetica".to_string()))
            );
        } else {
            panic!("Expected dictionary object");
        }
    }

    #[test]
    fn test_rename_preserved_fonts_all_keys_prefixed() {
        use crate::objects::{Dictionary, Object};

        let mut fonts = Dictionary::new();
        fonts.set("F1", Object::Integer(1));
        fonts.set("F2", Object::Integer(2));
        fonts.set("Arial", Object::Integer(3));
        fonts.set("Helvetica", Object::Integer(4));

        let renamed = rename_preserved_fonts(&fonts);

        // Verify ALL keys have "Orig" prefix
        for key in renamed.keys() {
            assert!(
                key.starts_with("Orig"),
                "Key '{}' should start with 'Orig'",
                key
            );
        }
    }

    // Tests for rewrite_font_references

    #[test]
    fn test_rewrite_font_references_simple() {
        let content = b"BT /F1 12 Tf (Hello) Tj ET";
        let mut mappings = HashMap::new();
        mappings.insert("F1".to_string(), "OrigF1".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        assert_eq!(result, "BT /OrigF1 12 Tf (Hello) Tj ET");
    }

    #[test]
    fn test_rewrite_font_references_multiple() {
        let content = b"BT /F1 12 Tf (Hello) Tj ET BT /F2 10 Tf (World) Tj ET";
        let mut mappings = HashMap::new();
        mappings.insert("F1".to_string(), "OrigF1".to_string());
        mappings.insert("F2".to_string(), "OrigF2".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        assert_eq!(
            result,
            "BT /OrigF1 12 Tf (Hello) Tj ET BT /OrigF2 10 Tf (World) Tj ET"
        );
    }

    #[test]
    fn test_rewrite_font_references_named_fonts() {
        let content = b"BT /Arial 14 Tf (Test) Tj /Helvetica 10 Tf (More) Tj ET";
        let mut mappings = HashMap::new();
        mappings.insert("Arial".to_string(), "OrigArial".to_string());
        mappings.insert("Helvetica".to_string(), "OrigHelvetica".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        assert_eq!(
            result,
            "BT /OrigArial 14 Tf (Test) Tj /OrigHelvetica 10 Tf (More) Tj ET"
        );
    }

    #[test]
    fn test_rewrite_font_references_multiline() {
        let content = b"BT\n/F1 12 Tf\n(Line 1) Tj\nET\nBT\n/F2 10 Tf\n(Line 2) Tj\nET";
        let mut mappings = HashMap::new();
        mappings.insert("F1".to_string(), "OrigF1".to_string());
        mappings.insert("F2".to_string(), "OrigF2".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        assert!(result.contains("/OrigF1 12 Tf"));
        assert!(result.contains("/OrigF2 10 Tf"));
        assert!(!result.contains("/F1 12 Tf"));
        assert!(!result.contains("/F2 10 Tf"));
    }

    #[test]
    fn test_rewrite_font_references_partial_mapping() {
        // Only map F1, leave F2 unchanged
        let content = b"BT /F1 12 Tf (Hello) Tj /F2 10 Tf (World) Tj ET";
        let mut mappings = HashMap::new();
        mappings.insert("F1".to_string(), "OrigF1".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        assert!(result.contains("/OrigF1 12 Tf"));
        assert!(result.contains("/F2 10 Tf")); // F2 unchanged
        assert!(!result.contains("/F1 12 Tf"));
    }

    #[test]
    fn test_rewrite_font_references_no_mappings() {
        let content = b"BT /F1 12 Tf (Hello) Tj ET";
        let mappings = HashMap::new();

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        // Should remain unchanged
        assert_eq!(result, "BT /F1 12 Tf (Hello) Tj ET");
    }

    #[test]
    fn test_rewrite_font_references_non_font_operators() {
        // Content with /Pattern (not a font)
        let content = b"/Pattern cs /P1 scn 100 100 m 200 200 l S";
        let mut mappings = HashMap::new();
        mappings.insert("Pattern".to_string(), "OrigPattern".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        // /Pattern should NOT be rewritten (not followed by Tf)
        assert!(result.contains("/Pattern cs"));
        assert!(!result.contains("/OrigPattern"));
    }

    #[test]
    fn test_rewrite_font_references_preserves_other_content() {
        let content = b"100 200 m 300 400 l S BT /F1 12 Tf (Text) Tj ET q Q";
        let mut mappings = HashMap::new();
        mappings.insert("F1".to_string(), "OrigF1".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        // Font should be rewritten
        assert!(result.contains("/OrigF1 12 Tf"));
        // Other operators preserved
        assert!(result.contains("100 200 m"));
        assert!(result.contains("300 400 l"));
        assert!(result.contains("(Text) Tj"));
    }

    // Edge case tests - documenting known limitations

    #[test]
    fn test_rewrite_font_references_normalizes_whitespace() {
        // DOCUMENTED LIMITATION: Whitespace is normalized
        let content = b"BT  /F1   12  Tf  (Text)  Tj  ET"; // Multiple spaces
        let mut mappings = HashMap::new();
        mappings.insert("F1".to_string(), "OrigF1".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        // Font renamed correctly
        assert!(result.contains("/OrigF1 12 Tf"));
        // Whitespace normalized (not "  /OrigF1   12")
        assert!(!result.contains("  /OrigF1"));
        // PDF is still valid (single spaces are sufficient)
    }

    #[test]
    fn test_rewrite_font_references_with_indentation() {
        // DOCUMENTED LIMITATION: Indentation is lost
        let content = b"BT\n  /F1 12 Tf\n  100 700 Td\n  (Text) Tj\nET";
        let mut mappings = HashMap::new();
        mappings.insert("F1".to_string(), "OrigF1".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        // Font renamed
        assert!(result.contains("/OrigF1 12 Tf"));
        // Original indentation lost (becomes single line tokens)
        // This is acceptable - PDF readers don't care about formatting
    }

    #[test]
    fn test_rename_preserved_fonts_no_collision_detection() {
        // DOCUMENTED LIMITATION: No collision detection
        use crate::objects::{Dictionary, Object};

        let mut fonts = Dictionary::new();
        fonts.set("F1", Object::Integer(1));
        fonts.set("OrigF1", Object::Integer(2)); // Already has "Orig" prefix!

        let renamed = rename_preserved_fonts(&fonts);

        // Both get renamed (collision not detected)
        assert!(renamed.contains_key("OrigF1")); // From original "OrigF1"
        assert!(renamed.contains_key("OrigOrigF1")); // From "F1"

        // This is acceptable - naming collisions are extremely rare in real PDFs
        // If needed, integration code can detect and handle this
    }

    #[test]
    fn test_rewrite_font_references_with_tabs() {
        // Tabs are normalized to spaces
        let content = b"BT\t/F1\t12\tTf\t(Text)\tTj\tET";
        let mut mappings = HashMap::new();
        mappings.insert("F1".to_string(), "OrigF1".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        // Font renamed correctly despite tabs
        assert!(result.contains("/OrigF1 12 Tf"));
    }

    #[test]
    fn test_rewrite_font_references_hyphenated_font_names() {
        // Font names with hyphens (common in real PDFs: Arial-Bold, etc.)
        let content = b"BT /Arial-Bold 14 Tf (Text) Tj /Times-Italic 12 Tf (More) Tj ET";
        let mut mappings = HashMap::new();
        mappings.insert("Arial-Bold".to_string(), "OrigArial-Bold".to_string());
        mappings.insert("Times-Italic".to_string(), "OrigTimes-Italic".to_string());

        let rewritten = rewrite_font_references(content, &mappings);
        let result = String::from_utf8(rewritten).unwrap();

        assert!(result.contains("/OrigArial-Bold 14 Tf"));
        assert!(result.contains("/OrigTimes-Italic 12 Tf"));
    }

    // Tests for has_embedded_font_data

    #[test]
    fn test_has_embedded_font_data_with_fontfile() {
        use crate::objects::{Dictionary, Object, ObjectId};

        let mut descriptor = Dictionary::new();
        descriptor.set("Type", Object::Name("FontDescriptor".to_string()));
        descriptor.set("FontFile", Object::Reference(ObjectId::new(10, 0))); // Type 1 font

        let mut font_dict = Dictionary::new();
        font_dict.set("Type", Object::Name("Font".to_string()));
        font_dict.set("FontDescriptor", Object::Dictionary(descriptor));

        assert!(has_embedded_font_data(&font_dict));
    }

    #[test]
    fn test_has_embedded_font_data_with_fontfile2() {
        use crate::objects::{Dictionary, Object, ObjectId};

        let mut descriptor = Dictionary::new();
        descriptor.set("Type", Object::Name("FontDescriptor".to_string()));
        descriptor.set("FontFile2", Object::Reference(ObjectId::new(20, 0))); // TrueType

        let mut font_dict = Dictionary::new();
        font_dict.set("Type", Object::Name("Font".to_string()));
        font_dict.set("FontDescriptor", Object::Dictionary(descriptor));

        assert!(has_embedded_font_data(&font_dict));
    }

    #[test]
    fn test_has_embedded_font_data_with_fontfile3() {
        use crate::objects::{Dictionary, Object, ObjectId};

        let mut descriptor = Dictionary::new();
        descriptor.set("Type", Object::Name("FontDescriptor".to_string()));
        descriptor.set("FontFile3", Object::Reference(ObjectId::new(30, 0))); // CFF/OpenType

        let mut font_dict = Dictionary::new();
        font_dict.set("Type", Object::Name("Font".to_string()));
        font_dict.set("FontDescriptor", Object::Dictionary(descriptor));

        assert!(has_embedded_font_data(&font_dict));
    }

    #[test]
    fn test_has_embedded_font_data_descriptor_without_streams() {
        use crate::objects::{Dictionary, Object};

        // FontDescriptor exists but no font streams (unusual but possible)
        let mut descriptor = Dictionary::new();
        descriptor.set("Type", Object::Name("FontDescriptor".to_string()));
        descriptor.set("FontName", Object::Name("Arial".to_string()));
        // NO FontFile/FontFile2/FontFile3

        let mut font_dict = Dictionary::new();
        font_dict.set("Type", Object::Name("Font".to_string()));
        font_dict.set("FontDescriptor", Object::Dictionary(descriptor));

        assert!(!has_embedded_font_data(&font_dict));
    }

    #[test]
    fn test_has_embedded_font_data_descriptor_as_reference() {
        use crate::objects::{Dictionary, Object, ObjectId};

        // FontDescriptor is a reference (common in real PDFs)
        let mut font_dict = Dictionary::new();
        font_dict.set("Type", Object::Name("Font".to_string()));
        font_dict.set("FontDescriptor", Object::Reference(ObjectId::new(100, 0)));

        // Conservative: assume reference MIGHT have embedded data
        assert!(has_embedded_font_data(&font_dict));
    }

    #[test]
    fn test_has_embedded_font_data_standard_font() {
        use crate::objects::{Dictionary, Object};

        // Standard font (Helvetica) - no FontDescriptor
        let mut font_dict = Dictionary::new();
        font_dict.set("Type", Object::Name("Font".to_string()));
        font_dict.set("Subtype", Object::Name("Type1".to_string()));
        font_dict.set("BaseFont", Object::Name("Helvetica".to_string()));
        // NO FontDescriptor

        assert!(!has_embedded_font_data(&font_dict));
    }

    #[test]
    fn test_has_embedded_font_data_multiple_font_files() {
        use crate::objects::{Dictionary, Object, ObjectId};

        // Font with BOTH FontFile2 and FontFile3 (unusual but test it)
        let mut descriptor = Dictionary::new();
        descriptor.set("Type", Object::Name("FontDescriptor".to_string()));
        descriptor.set("FontFile2", Object::Reference(ObjectId::new(10, 0)));
        descriptor.set("FontFile3", Object::Reference(ObjectId::new(11, 0)));

        let mut font_dict = Dictionary::new();
        font_dict.set("Type", Object::Name("Font".to_string()));
        font_dict.set("FontDescriptor", Object::Dictionary(descriptor));

        // Should detect embedded data (has at least one stream)
        assert!(has_embedded_font_data(&font_dict));
    }

    #[test]
    fn test_has_embedded_font_data_empty_dict() {
        use crate::objects::Dictionary;

        // Empty font dictionary
        let font_dict = Dictionary::new();

        assert!(!has_embedded_font_data(&font_dict));
    }
}