oxidize-pdf 2.5.0

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
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
//! Text streaming for incremental text extraction
//!
//! Extracts text from PDF content streams incrementally, processing
//! text operations as they are encountered.

use crate::error::Result;
use crate::parser::content::{ContentOperation, ContentParser};
use std::collections::VecDeque;

/// A chunk of extracted text with position information
#[derive(Debug, Clone)]
pub struct TextChunk {
    /// The extracted text
    pub text: String,
    /// X position on the page
    pub x: f64,
    /// Y position on the page
    pub y: f64,
    /// Font size
    pub font_size: f64,
    /// Font name (if known)
    pub font_name: Option<String>,
}

/// Options for text streaming
#[derive(Debug, Clone)]
pub struct TextStreamOptions {
    /// Minimum text size to include
    pub min_font_size: f64,
    /// Maximum buffer size for text chunks
    pub max_buffer_size: usize,
    /// Whether to preserve formatting
    pub preserve_formatting: bool,
    /// Whether to sort by position
    pub sort_by_position: bool,
}

impl Default for TextStreamOptions {
    fn default() -> Self {
        Self {
            min_font_size: 0.0,
            max_buffer_size: 1024 * 1024, // 1MB
            preserve_formatting: true,
            sort_by_position: true,
        }
    }
}

/// Streams text from PDF content
pub struct TextStreamer {
    options: TextStreamOptions,
    buffer: VecDeque<TextChunk>,
    current_font: Option<String>,
    current_font_size: f64,
    current_x: f64,
    current_y: f64,
}

impl TextStreamer {
    /// Create a new text streamer
    pub fn new(options: TextStreamOptions) -> Self {
        Self {
            options,
            buffer: VecDeque::new(),
            current_font: None,
            current_font_size: 12.0,
            current_x: 0.0,
            current_y: 0.0,
        }
    }

    /// Process a content stream chunk
    pub fn process_chunk(&mut self, data: &[u8]) -> Result<Vec<TextChunk>> {
        let operations = ContentParser::parse(data)
            .map_err(|e| crate::error::PdfError::ParseError(e.to_string()))?;

        let mut chunks = Vec::new();

        for op in operations {
            match op {
                ContentOperation::SetFont(name, size) => {
                    self.current_font = Some(name);
                    self.current_font_size = size as f64;
                }
                ContentOperation::MoveText(x, y) => {
                    self.current_x += x as f64;
                    self.current_y += y as f64;
                }
                ContentOperation::ShowText(bytes) => {
                    if self.current_font_size >= self.options.min_font_size {
                        let text = String::from_utf8_lossy(&bytes).to_string();
                        let chunk = TextChunk {
                            text,
                            x: self.current_x,
                            y: self.current_y,
                            font_size: self.current_font_size,
                            font_name: self.current_font.clone(),
                        };
                        chunks.push(chunk);
                    }
                }
                ContentOperation::BeginText => {
                    self.current_x = 0.0;
                    self.current_y = 0.0;
                }
                _ => {} // Ignore other operations
            }
        }

        // Add to buffer if needed
        for chunk in &chunks {
            self.buffer.push_back(chunk.clone());
        }

        // Check buffer size
        self.check_buffer_size();

        Ok(chunks)
    }

    /// Get all buffered text chunks
    pub fn get_buffered_chunks(&self) -> Vec<TextChunk> {
        self.buffer.iter().cloned().collect()
    }

    /// Clear the buffer
    pub fn clear_buffer(&mut self) {
        self.buffer.clear();
    }

    /// Extract text as a single string
    pub fn extract_text(&self) -> String {
        let mut chunks = self.get_buffered_chunks();

        if self.options.sort_by_position {
            // Sort by Y position (top to bottom), then X (left to right)
            chunks.sort_by(|a, b| b.y.total_cmp(&a.y).then(a.x.total_cmp(&b.x)));
        }

        chunks
            .into_iter()
            .map(|chunk| chunk.text)
            .collect::<Vec<_>>()
            .join(" ")
    }

    fn check_buffer_size(&mut self) {
        let total_size: usize = self.buffer.iter().map(|chunk| chunk.text.len()).sum();

        // Remove oldest chunks if buffer is too large
        while total_size > self.options.max_buffer_size && !self.buffer.is_empty() {
            self.buffer.pop_front();
        }
    }
}

/// Stream text from multiple content streams
pub fn stream_text<F>(content_streams: Vec<Vec<u8>>, mut callback: F) -> Result<()>
where
    F: FnMut(TextChunk) -> Result<()>,
{
    let mut streamer = TextStreamer::new(TextStreamOptions::default());

    for stream in content_streams {
        let chunks = streamer.process_chunk(&stream)?;
        for chunk in chunks {
            callback(chunk)?;
        }
    }

    Ok(())
}

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

    #[test]
    fn test_text_chunk() {
        let chunk = TextChunk {
            text: "Hello".to_string(),
            x: 100.0,
            y: 700.0,
            font_size: 12.0,
            font_name: Some("Helvetica".to_string()),
        };

        assert_eq!(chunk.text, "Hello");
        assert_eq!(chunk.x, 100.0);
        assert_eq!(chunk.y, 700.0);
        assert_eq!(chunk.font_size, 12.0);
        assert_eq!(chunk.font_name, Some("Helvetica".to_string()));
    }

    #[test]
    fn test_text_stream_options_default() {
        let options = TextStreamOptions::default();
        assert_eq!(options.min_font_size, 0.0);
        assert_eq!(options.max_buffer_size, 1024 * 1024);
        assert!(options.preserve_formatting);
        assert!(options.sort_by_position);
    }

    #[test]
    fn test_text_streamer_creation() {
        let options = TextStreamOptions::default();
        let streamer = TextStreamer::new(options);

        assert!(streamer.buffer.is_empty());
        assert_eq!(streamer.current_font_size, 12.0);
        assert_eq!(streamer.current_x, 0.0);
        assert_eq!(streamer.current_y, 0.0);
    }

    #[test]
    fn test_process_chunk_text() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Simple text showing operation
        let content = b"BT /F1 14 Tf 100 700 Td (Hello World) Tj ET";
        let chunks = streamer.process_chunk(content).unwrap();

        assert!(!chunks.is_empty());
        assert_eq!(chunks[0].text, "Hello World");
        assert_eq!(chunks[0].font_size, 14.0);
    }

    #[test]
    fn test_min_font_size_filter() {
        let mut options = TextStreamOptions::default();
        options.min_font_size = 10.0;
        let mut streamer = TextStreamer::new(options);

        // Text with small font (8pt) - should be filtered out
        let content = b"BT /F1 8 Tf 100 700 Td (Small Text) Tj ET";
        let chunks = streamer.process_chunk(content).unwrap();
        assert!(chunks.is_empty());

        // Text with large font (12pt) - should be included
        let content = b"BT /F1 12 Tf 100 650 Td (Large Text) Tj ET";
        let chunks = streamer.process_chunk(content).unwrap();
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0].text, "Large Text");
    }

    #[test]
    fn test_extract_text_sorted() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Add text in random order
        streamer.buffer.push_back(TextChunk {
            text: "Bottom".to_string(),
            x: 100.0,
            y: 100.0,
            font_size: 12.0,
            font_name: None,
        });

        streamer.buffer.push_back(TextChunk {
            text: "Top".to_string(),
            x: 100.0,
            y: 700.0,
            font_size: 12.0,
            font_name: None,
        });

        streamer.buffer.push_back(TextChunk {
            text: "Middle".to_string(),
            x: 100.0,
            y: 400.0,
            font_size: 12.0,
            font_name: None,
        });

        let text = streamer.extract_text();
        assert_eq!(text, "Top Middle Bottom");
    }

    #[test]
    fn test_buffer_management() {
        let mut options = TextStreamOptions::default();
        options.max_buffer_size = 10; // Very small buffer
        let mut streamer = TextStreamer::new(options);

        // Add chunks that exceed buffer size
        for i in 0..5 {
            streamer.buffer.push_back(TextChunk {
                text: format!("Text{i}"),
                x: 0.0,
                y: 0.0,
                font_size: 12.0,
                font_name: None,
            });
        }

        streamer.check_buffer_size();

        // Buffer should be limited
        assert!(streamer.buffer.len() < 5);
    }

    #[test]
    fn test_stream_text_function() {
        let content1 = b"BT /F1 12 Tf 100 700 Td (Page 1) Tj ET".to_vec();
        let content2 = b"BT /F1 12 Tf 100 650 Td (Page 2) Tj ET".to_vec();
        let streams = vec![content1, content2];

        let mut collected = Vec::new();
        stream_text(streams, |chunk| {
            collected.push(chunk.text);
            Ok(())
        })
        .unwrap();

        assert_eq!(collected.len(), 2);
        assert_eq!(collected[0], "Page 1");
        assert_eq!(collected[1], "Page 2");
    }

    #[test]
    fn test_text_chunk_debug_clone() {
        let chunk = TextChunk {
            text: "Test".to_string(),
            x: 50.0,
            y: 100.0,
            font_size: 10.0,
            font_name: Some("Arial".to_string()),
        };

        let debug_str = format!("{chunk:?}");
        assert!(debug_str.contains("TextChunk"));
        assert!(debug_str.contains("Test"));

        let cloned = chunk.clone();
        assert_eq!(cloned.text, chunk.text);
        assert_eq!(cloned.x, chunk.x);
        assert_eq!(cloned.y, chunk.y);
        assert_eq!(cloned.font_size, chunk.font_size);
        assert_eq!(cloned.font_name, chunk.font_name);
    }

    #[test]
    fn test_text_stream_options_custom() {
        let options = TextStreamOptions {
            min_font_size: 8.0,
            max_buffer_size: 2048,
            preserve_formatting: false,
            sort_by_position: false,
        };

        assert_eq!(options.min_font_size, 8.0);
        assert_eq!(options.max_buffer_size, 2048);
        assert!(!options.preserve_formatting);
        assert!(!options.sort_by_position);
    }

    #[test]
    fn test_text_stream_options_debug_clone() {
        let options = TextStreamOptions::default();

        let debug_str = format!("{options:?}");
        assert!(debug_str.contains("TextStreamOptions"));

        let cloned = options.clone();
        assert_eq!(cloned.min_font_size, options.min_font_size);
        assert_eq!(cloned.max_buffer_size, options.max_buffer_size);
        assert_eq!(cloned.preserve_formatting, options.preserve_formatting);
        assert_eq!(cloned.sort_by_position, options.sort_by_position);
    }

    #[test]
    fn test_text_streamer_process_empty_chunk() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());
        let chunks = streamer.process_chunk(b"").unwrap();
        assert!(chunks.is_empty());
    }

    #[test]
    fn test_text_streamer_process_invalid_content() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());
        // Invalid PDF content should be handled gracefully
        let content = b"Not valid PDF content";
        let result = streamer.process_chunk(content);
        // Should either succeed with no chunks or return an error
        match result {
            Ok(chunks) => assert!(chunks.is_empty()),
            Err(_) => {} // Error is also acceptable
        }
    }

    #[test]
    fn test_text_streamer_font_tracking() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Set font operation
        let content = b"BT /Helvetica-Bold 16 Tf ET";
        let _ = streamer.process_chunk(content).unwrap();

        assert_eq!(streamer.current_font, Some("Helvetica-Bold".to_string()));
        assert_eq!(streamer.current_font_size, 16.0);
    }

    #[test]
    fn test_text_streamer_position_tracking() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Move text position
        let content = b"BT 50 100 Td ET";
        let _ = streamer.process_chunk(content).unwrap();

        assert_eq!(streamer.current_x, 50.0);
        assert_eq!(streamer.current_y, 100.0);
    }

    #[test]
    fn test_text_streamer_begin_text_resets_position() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Set position
        streamer.current_x = 100.0;
        streamer.current_y = 200.0;

        // BeginText should reset position
        let content = b"BT ET";
        let _ = streamer.process_chunk(content).unwrap();

        assert_eq!(streamer.current_x, 0.0);
        assert_eq!(streamer.current_y, 0.0);
    }

    #[test]
    fn test_text_streamer_clear_buffer() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Add some chunks
        streamer.buffer.push_back(TextChunk {
            text: "Chunk1".to_string(),
            x: 0.0,
            y: 0.0,
            font_size: 12.0,
            font_name: None,
        });
        streamer.buffer.push_back(TextChunk {
            text: "Chunk2".to_string(),
            x: 0.0,
            y: 0.0,
            font_size: 12.0,
            font_name: None,
        });

        assert_eq!(streamer.buffer.len(), 2);

        streamer.clear_buffer();
        assert!(streamer.buffer.is_empty());
    }

    #[test]
    fn test_text_streamer_get_buffered_chunks() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        let chunk1 = TextChunk {
            text: "First".to_string(),
            x: 10.0,
            y: 20.0,
            font_size: 14.0,
            font_name: Some("Times".to_string()),
        };
        let chunk2 = TextChunk {
            text: "Second".to_string(),
            x: 30.0,
            y: 40.0,
            font_size: 16.0,
            font_name: Some("Arial".to_string()),
        };

        streamer.buffer.push_back(chunk1);
        streamer.buffer.push_back(chunk2);

        let chunks = streamer.get_buffered_chunks();
        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].text, "First");
        assert_eq!(chunks[1].text, "Second");
    }

    #[test]
    fn test_extract_text_no_sorting() {
        let mut options = TextStreamOptions::default();
        options.sort_by_position = false;
        let mut streamer = TextStreamer::new(options);

        // Add text in specific order
        streamer.buffer.push_back(TextChunk {
            text: "First".to_string(),
            x: 200.0,
            y: 100.0,
            font_size: 12.0,
            font_name: None,
        });
        streamer.buffer.push_back(TextChunk {
            text: "Second".to_string(),
            x: 100.0,
            y: 200.0,
            font_size: 12.0,
            font_name: None,
        });

        let text = streamer.extract_text();
        assert_eq!(text, "First Second"); // Should maintain insertion order
    }

    #[test]
    fn test_extract_text_horizontal_sorting() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Add text on same line, different X positions
        streamer.buffer.push_back(TextChunk {
            text: "Right".to_string(),
            x: 300.0,
            y: 500.0,
            font_size: 12.0,
            font_name: None,
        });
        streamer.buffer.push_back(TextChunk {
            text: "Left".to_string(),
            x: 100.0,
            y: 500.0,
            font_size: 12.0,
            font_name: None,
        });
        streamer.buffer.push_back(TextChunk {
            text: "Middle".to_string(),
            x: 200.0,
            y: 500.0,
            font_size: 12.0,
            font_name: None,
        });

        let text = streamer.extract_text();
        assert_eq!(text, "Left Middle Right");
    }

    #[test]
    fn test_check_buffer_size_edge_cases() {
        let mut options = TextStreamOptions::default();
        options.max_buffer_size = 20;
        let mut streamer = TextStreamer::new(options);

        // Add chunk that exactly fills buffer
        streamer.buffer.push_back(TextChunk {
            text: "a".repeat(20),
            x: 0.0,
            y: 0.0,
            font_size: 12.0,
            font_name: None,
        });

        streamer.check_buffer_size();
        assert_eq!(streamer.buffer.len(), 1); // Should keep the chunk

        // Add another chunk to exceed limit
        streamer.buffer.push_back(TextChunk {
            text: "b".to_string(),
            x: 0.0,
            y: 0.0,
            font_size: 12.0,
            font_name: None,
        });

        streamer.check_buffer_size();
        // Should have removed the first chunk
        assert!(streamer.buffer.len() <= 1);
    }

    #[test]
    fn test_stream_text_with_error_callback() {
        let content = b"BT /F1 12 Tf 100 700 Td (Test) Tj ET".to_vec();
        let streams = vec![content];

        let result = stream_text(streams, |_chunk| {
            Err(crate::error::PdfError::ParseError("Test error".to_string()))
        });

        assert!(result.is_err());
    }

    #[test]
    fn test_stream_text_empty_streams() {
        let streams: Vec<Vec<u8>> = vec![];

        let mut collected = Vec::new();
        stream_text(streams, |chunk| {
            collected.push(chunk);
            Ok(())
        })
        .unwrap();

        assert!(collected.is_empty());
    }

    #[test]
    fn test_text_chunk_without_font_name() {
        let chunk = TextChunk {
            text: "No Font".to_string(),
            x: 0.0,
            y: 0.0,
            font_size: 12.0,
            font_name: None,
        };

        assert_eq!(chunk.font_name, None);
    }

    #[test]
    fn test_process_chunk_multiple_operations() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Content with multiple text operations
        let content = b"BT /F1 10 Tf 100 700 Td (First) Tj 50 0 Td (Second) Tj ET";
        let chunks = streamer.process_chunk(content).unwrap();

        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].text, "First");
        assert_eq!(chunks[1].text, "Second");
        assert_eq!(chunks[0].x, 100.0);
        assert_eq!(chunks[1].x, 150.0); // 100 + 50
    }

    #[test]
    fn test_buffer_size_calculation() {
        let mut options = TextStreamOptions::default();
        options.max_buffer_size = 100;
        let mut streamer = TextStreamer::new(options);

        // Add chunks with known sizes
        for _i in 0..10 {
            streamer.buffer.push_back(TextChunk {
                text: "1234567890".to_string(), // 10 bytes each
                x: 0.0,
                y: 0.0,
                font_size: 12.0,
                font_name: None,
            });
        }

        // Total size is 100 bytes
        streamer.check_buffer_size();

        // Add one more to exceed
        streamer.buffer.push_back(TextChunk {
            text: "x".to_string(),
            x: 0.0,
            y: 0.0,
            font_size: 12.0,
            font_name: None,
        });

        streamer.check_buffer_size();

        // Should have removed oldest chunks
        let total_size: usize = streamer.buffer.iter().map(|c| c.text.len()).sum();
        assert!(total_size <= 100);
    }

    #[test]
    fn test_text_chunk_extreme_positions() {
        let chunk = TextChunk {
            text: "Extreme".to_string(),
            x: f64::MAX,
            y: f64::MIN,
            font_size: 0.1,
            font_name: Some("TinyFont".to_string()),
        };

        assert_eq!(chunk.x, f64::MAX);
        assert_eq!(chunk.y, f64::MIN);
        assert_eq!(chunk.font_size, 0.1);
    }

    #[test]
    fn test_text_streamer_accumulated_position() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Multiple move operations should accumulate
        let content = b"BT 10 20 Td 5 10 Td 15 -5 Td ET";
        let _ = streamer.process_chunk(content).unwrap();

        assert_eq!(streamer.current_x, 30.0); // 10 + 5 + 15
        assert_eq!(streamer.current_y, 25.0); // 20 + 10 + (-5)
    }

    #[test]
    fn test_process_chunk_with_multiple_font_changes() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        let content = b"BT /F1 10 Tf (Small) Tj /F2 24 Tf (Large) Tj /F3 16 Tf (Medium) Tj ET";
        let chunks = streamer.process_chunk(content).unwrap();

        assert_eq!(chunks.len(), 3);
        assert_eq!(chunks[0].font_size, 10.0);
        assert_eq!(chunks[1].font_size, 24.0);
        assert_eq!(chunks[2].font_size, 16.0);
    }

    #[test]
    fn test_empty_text_operations() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Empty text operations
        let content = b"BT /F1 12 Tf () Tj ( ) Tj ET";
        let chunks = streamer.process_chunk(content).unwrap();

        assert_eq!(chunks.len(), 2);
        assert!(chunks[0].text.is_empty());
        assert_eq!(chunks[1].text, " ");
    }

    #[test]
    fn test_text_with_special_characters() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        let content = b"BT /F1 12 Tf (\xC3\xA9\xC3\xA0\xC3\xB1) Tj ET"; // UTF-8: éàñ
        let chunks = streamer.process_chunk(content).unwrap();

        assert!(!chunks.is_empty());
        // The text should contain the special characters (lossy conversion)
        assert!(!chunks[0].text.is_empty());
    }

    #[test]
    fn test_sorting_with_equal_positions() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Add chunks with same position
        for i in 0..3 {
            streamer.buffer.push_back(TextChunk {
                text: format!("Text{i}"),
                x: 100.0,
                y: 100.0,
                font_size: 12.0,
                font_name: None,
            });
        }

        let text = streamer.extract_text();
        // Should maintain order when positions are equal
        assert!(text.contains("Text0"));
        assert!(text.contains("Text1"));
        assert!(text.contains("Text2"));
    }

    #[test]
    fn test_max_buffer_size_zero() {
        let mut options = TextStreamOptions::default();
        options.max_buffer_size = 0;
        let mut streamer = TextStreamer::new(options);

        streamer.buffer.push_back(TextChunk {
            text: "Should be removed".to_string(),
            x: 0.0,
            y: 0.0,
            font_size: 12.0,
            font_name: None,
        });

        streamer.check_buffer_size();
        assert!(streamer.buffer.is_empty());
    }

    #[test]
    fn test_font_name_with_spaces() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        let content = b"BT /Times New Roman 14 Tf ET";
        let result = streamer.process_chunk(content);

        // This should fail because "New" is treated as an unknown operator
        assert!(result.is_err());

        // The font and size should remain unchanged (default values)
        assert_eq!(streamer.current_font, None);
        assert_eq!(streamer.current_font_size, 12.0);
    }

    #[test]
    fn test_stream_text_with_mixed_content() {
        let content1 = b"BT /F1 8 Tf (Small) Tj ET".to_vec();
        let content2 = b"Invalid content".to_vec();
        let content3 = b"BT /F2 16 Tf (Large) Tj ET".to_vec();
        let streams = vec![content1, content2, content3];

        let mut collected = Vec::new();
        let result = stream_text(streams, |chunk| {
            collected.push(chunk.text);
            Ok(())
        });

        // Should handle mixed valid/invalid content
        assert!(result.is_ok() || result.is_err());
        // Check that collected is valid (len() is always >= 0 for Vec)
    }

    #[test]
    fn test_preserve_formatting_option() {
        let mut options = TextStreamOptions::default();
        options.preserve_formatting = false;
        let streamer = TextStreamer::new(options.clone());

        assert!(!streamer.options.preserve_formatting);
        assert_eq!(streamer.options.min_font_size, options.min_font_size);
    }

    #[test]
    fn test_very_large_font_size() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        let content = b"BT /F1 9999 Tf (Huge) Tj ET";
        let chunks = streamer.process_chunk(content).unwrap();

        assert!(!chunks.is_empty());
        assert_eq!(chunks[0].font_size, 9999.0);
        assert_eq!(chunks[0].text, "Huge");
    }

    #[test]
    fn test_negative_font_size() {
        let mut options = TextStreamOptions::default();
        options.min_font_size = -10.0; // Allow negative sizes
        let mut streamer = TextStreamer::new(options);

        streamer.current_font_size = -5.0;
        let content = b"BT (Negative) Tj ET";
        let chunks = streamer.process_chunk(content).unwrap();

        assert!(!chunks.is_empty());
        assert_eq!(chunks[0].font_size, -5.0);
    }

    #[test]
    fn test_text_position_nan_handling() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Create chunks with NaN positions
        let chunk1 = TextChunk {
            text: "NaN X".to_string(),
            x: f64::NAN,
            y: 100.0,
            font_size: 12.0,
            font_name: None,
        };
        let chunk2 = TextChunk {
            text: "NaN Y".to_string(),
            x: 100.0,
            y: f64::NAN,
            font_size: 12.0,
            font_name: None,
        };

        streamer.buffer.push_back(chunk1);
        streamer.buffer.push_back(chunk2);

        // extract_text should handle NaN gracefully
        let text = streamer.extract_text();
        assert!(text.contains("NaN"));
    }

    #[test]
    fn test_buffer_with_different_font_names() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        let fonts = ["Arial", "Times", "Courier", "Helvetica"];
        for (i, font) in fonts.iter().enumerate() {
            streamer.buffer.push_back(TextChunk {
                text: format!("Font{i}"),
                x: 0.0,
                y: 0.0,
                font_size: 12.0,
                font_name: Some((*font).to_string()),
            });
        }

        let chunks = streamer.get_buffered_chunks();
        assert_eq!(chunks.len(), 4);
        for (i, chunk) in chunks.iter().enumerate() {
            assert_eq!(chunk.font_name, Some(fonts[i].to_string()));
        }
    }

    #[test]
    fn test_process_chunk_error_propagation() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // This will cause a parse error
        let content = b"\xFF\xFE\xFD\xFC"; // Invalid UTF-8
        let result = streamer.process_chunk(content);

        // Should handle the error gracefully
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_extract_text_empty_buffer() {
        let streamer = TextStreamer::new(TextStreamOptions::default());
        let text = streamer.extract_text();
        assert!(text.is_empty());
    }

    #[test]
    fn test_extract_text_single_chunk() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        streamer.buffer.push_back(TextChunk {
            text: "Single".to_string(),
            x: 0.0,
            y: 0.0,
            font_size: 12.0,
            font_name: None,
        });

        let text = streamer.extract_text();
        assert_eq!(text, "Single");
    }

    #[test]
    fn test_check_buffer_size_empty() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());
        streamer.check_buffer_size(); // Should not panic on empty buffer
        assert!(streamer.buffer.is_empty());
    }

    #[test]
    fn test_complex_content_operations() {
        let mut streamer = TextStreamer::new(TextStreamOptions::default());

        // Complex PDF content with mixed operations
        let content = b"BT /F1 12 Tf 0 0 Td (Start) Tj ET q Q BT 50 50 Td (End) Tj ET";
        let chunks = streamer.process_chunk(content).unwrap();

        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].text, "Start");
        assert_eq!(chunks[1].text, "End");
        assert_eq!(chunks[0].x, 0.0);
        assert_eq!(chunks[1].x, 50.0);
    }

    #[test]
    fn test_stream_text_callback_state() {
        let content = b"BT /F1 12 Tf (Test) Tj ET".to_vec();
        let streams = vec![content; 3]; // Same content 3 times

        let mut count = 0;
        stream_text(streams, |_chunk| {
            count += 1;
            Ok(())
        })
        .unwrap();

        assert_eq!(count, 3);
    }
}