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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
use crate::error::Result;
use crate::page::Margins;
use crate::text::{measure_text, split_into_words, Font};
use std::fmt::Write;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TextAlign {
    Left,
    Right,
    Center,
    Justified,
}

pub struct TextFlowContext {
    operations: String,
    current_font: Font,
    font_size: f64,
    line_height: f64,
    cursor_x: f64,
    cursor_y: f64,
    alignment: TextAlign,
    page_width: f64,
    #[allow(dead_code)]
    page_height: f64,
    margins: Margins,
}

impl TextFlowContext {
    pub fn new(page_width: f64, page_height: f64, margins: Margins) -> Self {
        Self {
            operations: String::new(),
            current_font: Font::Helvetica,
            font_size: 12.0,
            line_height: 1.2,
            cursor_x: margins.left,
            cursor_y: page_height - margins.top,
            alignment: TextAlign::Left,
            page_width,
            page_height,
            margins,
        }
    }

    pub fn set_font(&mut self, font: Font, size: f64) -> &mut Self {
        self.current_font = font;
        self.font_size = size;
        self
    }

    pub fn set_line_height(&mut self, multiplier: f64) -> &mut Self {
        self.line_height = multiplier;
        self
    }

    pub fn set_alignment(&mut self, alignment: TextAlign) -> &mut Self {
        self.alignment = alignment;
        self
    }

    pub fn at(&mut self, x: f64, y: f64) -> &mut Self {
        self.cursor_x = x;
        self.cursor_y = y;
        self
    }

    pub fn content_width(&self) -> f64 {
        self.page_width - self.margins.left - self.margins.right
    }

    /// Returns the width available for text starting at the current cursor_x position.
    ///
    /// Unlike `content_width()` which always uses `margins.left` as the origin,
    /// `available_width()` accounts for the actual cursor position so that text
    /// placed via `.at(x, y)` does not overflow the right margin.
    pub fn available_width(&self) -> f64 {
        (self.page_width - self.margins.right - self.cursor_x).max(0.0)
    }

    pub fn write_wrapped(&mut self, text: &str) -> Result<&mut Self> {
        let start_x = self.cursor_x;
        let available_width = self.available_width();

        // Split text into words
        let words = split_into_words(text);
        let mut lines: Vec<Vec<&str>> = Vec::new();
        let mut current_line: Vec<&str> = Vec::new();
        let mut current_width = 0.0;

        // Build lines based on available width (respects cursor_x offset)
        for word in words {
            let word_width = measure_text(word, &self.current_font, self.font_size);

            // Check if we need to start a new line
            if !current_line.is_empty() && current_width + word_width > available_width {
                lines.push(current_line);
                current_line = vec![word];
                current_width = word_width;
            } else {
                current_line.push(word);
                current_width += word_width;
            }
        }

        if !current_line.is_empty() {
            lines.push(current_line);
        }

        // Render each line
        for (i, line) in lines.iter().enumerate() {
            let line_text = line.join("");
            let line_width = measure_text(&line_text, &self.current_font, self.font_size);

            // Calculate x position based on alignment.
            // start_x is the column where this block of text begins (set via .at()).
            // Left/Justified start at start_x; Center is relative to start_x;
            // Right stays anchored to the right margin.
            let x = match self.alignment {
                TextAlign::Left => start_x,
                TextAlign::Right => self.page_width - self.margins.right - line_width,
                TextAlign::Center => start_x + (available_width - line_width) / 2.0,
                TextAlign::Justified => start_x,
            };

            // Begin text object
            self.operations.push_str("BT\n");

            // Set font
            writeln!(
                &mut self.operations,
                "/{} {} Tf",
                self.current_font.pdf_name(),
                self.font_size
            )
            .expect("Writing to String should never fail");

            // Set text position
            writeln!(&mut self.operations, "{:.2} {:.2} Td", x, self.cursor_y)
                .expect("Writing to String should never fail");

            // Handle justification
            if self.alignment == TextAlign::Justified && i < lines.len() - 1 && line.len() > 1 {
                // Calculate extra space to distribute
                let spaces_count = line.iter().filter(|w| w.trim().is_empty()).count();
                if spaces_count > 0 {
                    let extra_space = available_width - line_width;
                    let space_adjustment = extra_space / spaces_count as f64;

                    // Set word spacing
                    writeln!(&mut self.operations, "{space_adjustment:.2} Tw")
                        .expect("Writing to String should never fail");
                }
            }

            // Show text
            self.operations.push('(');
            for ch in line_text.chars() {
                match ch {
                    '(' => self.operations.push_str("\\("),
                    ')' => self.operations.push_str("\\)"),
                    '\\' => self.operations.push_str("\\\\"),
                    '\n' => self.operations.push_str("\\n"),
                    '\r' => self.operations.push_str("\\r"),
                    '\t' => self.operations.push_str("\\t"),
                    _ => self.operations.push(ch),
                }
            }
            self.operations.push_str(") Tj\n");

            // Reset word spacing if it was set
            if self.alignment == TextAlign::Justified && i < lines.len() - 1 {
                self.operations.push_str("0 Tw\n");
            }

            // End text object
            self.operations.push_str("ET\n");

            // Move cursor down for next line
            self.cursor_y -= self.font_size * self.line_height;
        }

        Ok(self)
    }

    pub fn write_paragraph(&mut self, text: &str) -> Result<&mut Self> {
        self.write_wrapped(text)?;
        // Add extra space after paragraph
        self.cursor_y -= self.font_size * self.line_height * 0.5;
        Ok(self)
    }

    pub fn newline(&mut self) -> &mut Self {
        self.cursor_y -= self.font_size * self.line_height;
        self.cursor_x = self.margins.left;
        self
    }

    pub fn cursor_position(&self) -> (f64, f64) {
        (self.cursor_x, self.cursor_y)
    }

    pub fn generate_operations(&self) -> Vec<u8> {
        self.operations.as_bytes().to_vec()
    }

    /// Get the current alignment
    pub fn alignment(&self) -> TextAlign {
        self.alignment
    }

    /// Get the page dimensions
    pub fn page_dimensions(&self) -> (f64, f64) {
        (self.page_width, self.page_height)
    }

    /// Get the margins
    pub fn margins(&self) -> &Margins {
        &self.margins
    }

    /// Get current line height multiplier
    pub fn line_height(&self) -> f64 {
        self.line_height
    }

    /// Get the operations string
    pub fn operations(&self) -> &str {
        &self.operations
    }

    /// Clear all operations
    pub fn clear(&mut self) {
        self.operations.clear();
    }
}

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

    fn create_test_margins() -> Margins {
        Margins {
            left: 50.0,
            right: 50.0,
            top: 50.0,
            bottom: 50.0,
        }
    }

    #[test]
    fn test_text_flow_context_new() {
        let margins = create_test_margins();
        let context = TextFlowContext::new(400.0, 600.0, margins);

        assert_eq!(context.current_font, Font::Helvetica);
        assert_eq!(context.font_size, 12.0);
        assert_eq!(context.line_height, 1.2);
        assert_eq!(context.alignment, TextAlign::Left);
        assert_eq!(context.page_width, 400.0);
        assert_eq!(context.page_height, 600.0);
        assert_eq!(context.cursor_x, 50.0); // margins.left
        assert_eq!(context.cursor_y, 550.0); // page_height - margins.top
    }

    #[test]
    fn test_set_font() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_font(Font::TimesBold, 16.0);
        assert_eq!(context.current_font, Font::TimesBold);
        assert_eq!(context.font_size, 16.0);
    }

    #[test]
    fn test_set_line_height() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_line_height(1.5);
        assert_eq!(context.line_height(), 1.5);
    }

    #[test]
    fn test_set_alignment() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_alignment(TextAlign::Center);
        assert_eq!(context.alignment(), TextAlign::Center);
    }

    #[test]
    fn test_at_position() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.at(100.0, 200.0);
        let (x, y) = context.cursor_position();
        assert_eq!(x, 100.0);
        assert_eq!(y, 200.0);
    }

    #[test]
    fn test_content_width() {
        let margins = create_test_margins();
        let context = TextFlowContext::new(400.0, 600.0, margins);

        let content_width = context.content_width();
        assert_eq!(content_width, 300.0); // 400 - 50 - 50
    }

    #[test]
    fn test_text_align_variants() {
        assert_eq!(TextAlign::Left, TextAlign::Left);
        assert_eq!(TextAlign::Right, TextAlign::Right);
        assert_eq!(TextAlign::Center, TextAlign::Center);
        assert_eq!(TextAlign::Justified, TextAlign::Justified);

        assert_ne!(TextAlign::Left, TextAlign::Right);
    }

    #[test]
    fn test_write_wrapped_simple() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.write_wrapped("Hello World").unwrap();

        let ops = context.operations();
        assert!(ops.contains("BT\n"));
        assert!(ops.contains("ET\n"));
        assert!(ops.contains("/Helvetica 12 Tf"));
        assert!(ops.contains("(Hello World) Tj"));
    }

    #[test]
    fn test_write_paragraph() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        let initial_y = context.cursor_y;
        context.write_paragraph("Test paragraph").unwrap();

        // Y position should have moved down more than just line height
        assert!(context.cursor_y < initial_y);
    }

    #[test]
    fn test_newline() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins.clone());

        let initial_y = context.cursor_y;
        context.newline();

        assert_eq!(context.cursor_x, margins.left);
        assert!(context.cursor_y < initial_y);
        assert_eq!(
            context.cursor_y,
            initial_y - context.font_size * context.line_height
        );
    }

    #[test]
    fn test_cursor_position() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.at(75.0, 125.0);
        let (x, y) = context.cursor_position();
        assert_eq!(x, 75.0);
        assert_eq!(y, 125.0);
    }

    #[test]
    fn test_generate_operations() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.write_wrapped("Test").unwrap();
        let ops_bytes = context.generate_operations();
        let ops_string = String::from_utf8(ops_bytes).unwrap();

        assert_eq!(ops_string, context.operations());
    }

    #[test]
    fn test_clear_operations() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.write_wrapped("Test").unwrap();
        assert!(!context.operations().is_empty());

        context.clear();
        assert!(context.operations().is_empty());
    }

    #[test]
    fn test_page_dimensions() {
        let margins = create_test_margins();
        let context = TextFlowContext::new(400.0, 600.0, margins);

        let (width, height) = context.page_dimensions();
        assert_eq!(width, 400.0);
        assert_eq!(height, 600.0);
    }

    #[test]
    fn test_margins_access() {
        let margins = create_test_margins();
        let context = TextFlowContext::new(400.0, 600.0, margins);

        let ctx_margins = context.margins();
        assert_eq!(ctx_margins.left, 50.0);
        assert_eq!(ctx_margins.right, 50.0);
        assert_eq!(ctx_margins.top, 50.0);
        assert_eq!(ctx_margins.bottom, 50.0);
    }

    #[test]
    fn test_method_chaining() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context
            .set_font(Font::Courier, 10.0)
            .set_line_height(1.5)
            .set_alignment(TextAlign::Center)
            .at(100.0, 200.0);

        assert_eq!(context.current_font, Font::Courier);
        assert_eq!(context.font_size, 10.0);
        assert_eq!(context.line_height(), 1.5);
        assert_eq!(context.alignment(), TextAlign::Center);
        let (x, y) = context.cursor_position();
        assert_eq!(x, 100.0);
        assert_eq!(y, 200.0);
    }

    #[test]
    fn test_text_align_debug() {
        let align = TextAlign::Center;
        let debug_str = format!("{align:?}");
        assert_eq!(debug_str, "Center");
    }

    #[test]
    fn test_text_align_clone() {
        let align1 = TextAlign::Justified;
        let align2 = align1;
        assert_eq!(align1, align2);
    }

    #[test]
    fn test_text_align_copy() {
        let align1 = TextAlign::Right;
        let align2 = align1; // Copy semantics
        assert_eq!(align1, align2);

        // Both variables should still be usable
        assert_eq!(align1, TextAlign::Right);
        assert_eq!(align2, TextAlign::Right);
    }

    #[test]
    fn test_write_wrapped_with_alignment_right() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_alignment(TextAlign::Right);
        context.write_wrapped("Right aligned text").unwrap();

        let ops = context.operations();
        assert!(ops.contains("BT\n"));
        assert!(ops.contains("ET\n"));
        // Right alignment should position text differently
        assert!(ops.contains("Td"));
    }

    #[test]
    fn test_write_wrapped_with_alignment_center() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_alignment(TextAlign::Center);
        context.write_wrapped("Centered text").unwrap();

        let ops = context.operations();
        assert!(ops.contains("BT\n"));
        assert!(ops.contains("(Centered text) Tj"));
    }

    #[test]
    fn test_write_wrapped_with_alignment_justified() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_alignment(TextAlign::Justified);
        // Long text that will wrap and justify
        context.write_wrapped("This is a longer text that should wrap across multiple lines to test justification").unwrap();

        let ops = context.operations();
        assert!(ops.contains("BT\n"));
        // Justified text may have word spacing adjustments
        assert!(ops.contains("Tw") || ops.contains("0 Tw"));
    }

    #[test]
    fn test_write_wrapped_empty_text() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.write_wrapped("").unwrap();

        // Empty text should not generate operations
        assert!(context.operations().is_empty());
    }

    #[test]
    fn test_write_wrapped_whitespace_only() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.write_wrapped("   ").unwrap();

        let ops = context.operations();
        // Should handle whitespace-only text
        assert!(ops.contains("BT\n") || ops.is_empty());
    }

    #[test]
    fn test_write_wrapped_special_characters() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context
            .write_wrapped("Text with (parentheses) and \\backslash\\")
            .unwrap();

        let ops = context.operations();
        // Special characters should be escaped
        assert!(ops.contains("\\(parentheses\\)"));
        assert!(ops.contains("\\\\backslash\\\\"));
    }

    #[test]
    fn test_write_wrapped_newlines_tabs() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.write_wrapped("Line1\nLine2\tTabbed").unwrap();

        let ops = context.operations();
        // Newlines and tabs should be escaped
        assert!(ops.contains("\\n") || ops.contains("\\t"));
    }

    #[test]
    fn test_write_wrapped_very_long_word() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(200.0, 600.0, margins); // Narrow page

        let long_word = "a".repeat(100);
        context.write_wrapped(&long_word).unwrap();

        let ops = context.operations();
        assert!(ops.contains("BT\n"));
        assert!(ops.contains(&long_word));
    }

    #[test]
    fn test_write_wrapped_cursor_movement() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        let initial_y = context.cursor_y;

        context.write_wrapped("Line 1").unwrap();
        let y_after_line1 = context.cursor_y;

        context.write_wrapped("Line 2").unwrap();
        let y_after_line2 = context.cursor_y;

        // Cursor should move down after each line
        assert!(y_after_line1 < initial_y);
        assert!(y_after_line2 < y_after_line1);
    }

    #[test]
    fn test_write_paragraph_spacing() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        let initial_y = context.cursor_y;
        context.write_paragraph("Paragraph 1").unwrap();
        let y_after_p1 = context.cursor_y;

        context.write_paragraph("Paragraph 2").unwrap();
        let y_after_p2 = context.cursor_y;

        // Paragraphs should have extra spacing
        let spacing1 = initial_y - y_after_p1;
        let spacing2 = y_after_p1 - y_after_p2;

        assert!(spacing1 > 0.0);
        assert!(spacing2 > 0.0);
    }

    #[test]
    fn test_multiple_newlines() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        let initial_y = context.cursor_y;

        context.newline();
        let y1 = context.cursor_y;

        context.newline();
        let y2 = context.cursor_y;

        context.newline();
        let y3 = context.cursor_y;

        // Each newline should move cursor down by same amount
        let spacing1 = initial_y - y1;
        let spacing2 = y1 - y2;
        let spacing3 = y2 - y3;

        // Use approximate equality for floating point comparisons
        assert!((spacing1 - spacing2).abs() < 1e-10);
        assert!((spacing2 - spacing3).abs() < 1e-10);
        assert!((spacing1 - context.font_size * context.line_height).abs() < 1e-10);
    }

    #[test]
    fn test_content_width_different_margins() {
        let margins = Margins {
            left: 30.0,
            right: 70.0,
            top: 40.0,
            bottom: 60.0,
        };
        let context = TextFlowContext::new(500.0, 700.0, margins);

        let content_width = context.content_width();
        assert_eq!(content_width, 400.0); // 500 - 30 - 70
    }

    #[test]
    fn test_custom_line_height() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_line_height(2.0);

        let initial_y = context.cursor_y;
        context.newline();
        let y_after = context.cursor_y;

        let spacing = initial_y - y_after;
        assert_eq!(spacing, context.font_size * 2.0); // line_height = 2.0
    }

    #[test]
    fn test_different_fonts() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        let fonts = vec![
            Font::Helvetica,
            Font::HelveticaBold,
            Font::TimesRoman,
            Font::TimesBold,
            Font::Courier,
            Font::CourierBold,
        ];

        for font in fonts {
            context.clear();
            let font_name = font.pdf_name();
            context.set_font(font, 14.0);
            context.write_wrapped("Test text").unwrap();

            let ops = context.operations();
            assert!(ops.contains(&format!("/{font_name} 14 Tf")));
        }
    }

    #[test]
    fn test_font_size_variations() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        let sizes = vec![8.0, 10.0, 12.0, 14.0, 16.0, 24.0, 36.0];

        for size in sizes {
            context.clear();
            context.set_font(Font::Helvetica, size);
            context.write_wrapped("Test").unwrap();

            let ops = context.operations();
            assert!(ops.contains(&format!("/Helvetica {size} Tf")));
        }
    }

    #[test]
    fn test_at_position_edge_cases() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        // Test zero position
        context.at(0.0, 0.0);
        assert_eq!(context.cursor_position(), (0.0, 0.0));

        // Test negative position
        context.at(-10.0, -20.0);
        assert_eq!(context.cursor_position(), (-10.0, -20.0));

        // Test large position
        context.at(10000.0, 20000.0);
        assert_eq!(context.cursor_position(), (10000.0, 20000.0));
    }

    #[test]
    fn test_write_wrapped_with_narrow_content() {
        let margins = Margins {
            left: 190.0,
            right: 190.0,
            top: 50.0,
            bottom: 50.0,
        };
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        // Content width is only 20.0 units
        context
            .write_wrapped("This text should wrap a lot")
            .unwrap();

        let ops = context.operations();
        // Should have multiple text objects for wrapped lines
        let bt_count = ops.matches("BT\n").count();
        assert!(bt_count > 1);
    }

    #[test]
    fn test_justified_text_single_word_line() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_alignment(TextAlign::Justified);
        context.write_wrapped("SingleWord").unwrap();

        let ops = context.operations();
        // Single word lines should not have word spacing
        assert!(!ops.contains(" Tw") || ops.contains("0 Tw"));
    }

    #[test]
    fn test_justified_text_last_line() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_alignment(TextAlign::Justified);
        // Text that will create multiple lines
        context.write_wrapped("This is a test of justified text alignment where the last line should not be justified").unwrap();

        let ops = context.operations();
        // Should reset word spacing (0 Tw) for last line
        assert!(ops.contains("0 Tw"));
    }

    #[test]
    fn test_generate_operations_encoding() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.write_wrapped("UTF-8 Text: Ñ").unwrap();

        let ops_bytes = context.generate_operations();
        let ops_string = String::from_utf8(ops_bytes.clone()).unwrap();

        assert_eq!(ops_bytes, context.operations().as_bytes());
        assert_eq!(ops_string, context.operations());
    }

    #[test]
    fn test_clear_resets_operations_only() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_font(Font::TimesBold, 18.0);
        context.set_alignment(TextAlign::Right);
        context.at(100.0, 200.0);
        context.write_wrapped("Text").unwrap();

        context.clear();

        // Operations should be cleared
        assert!(context.operations().is_empty());

        // But other settings should remain
        assert_eq!(context.current_font, Font::TimesBold);
        assert_eq!(context.font_size, 18.0);
        assert_eq!(context.alignment(), TextAlign::Right);
        // Cursor position should reflect where we are after writing text (moved down by line height)
        let (x, y) = context.cursor_position();
        assert_eq!(x, 100.0); // X position should be unchanged
        assert!(y < 200.0); // Y position should have moved down after writing text
    }

    #[test]
    fn test_long_text_wrapping() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        let long_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
                        Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.";

        context.write_wrapped(long_text).unwrap();

        let ops = context.operations();
        // Should have multiple lines
        let tj_count = ops.matches(") Tj").count();
        assert!(tj_count > 1);
    }

    #[test]
    fn test_empty_operations_initially() {
        let margins = create_test_margins();
        let context = TextFlowContext::new(400.0, 600.0, margins);

        assert!(context.operations().is_empty());
        assert_eq!(context.generate_operations().len(), 0);
    }

    #[test]
    fn test_write_paragraph_empty() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        let initial_y = context.cursor_y;
        context.write_paragraph("").unwrap();

        // Empty paragraph should still add spacing
        assert!(context.cursor_y < initial_y);
    }

    #[test]
    fn test_extreme_line_height() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        // Very small line height
        context.set_line_height(0.1);
        let initial_y = context.cursor_y;
        context.newline();
        assert_eq!(context.cursor_y, initial_y - context.font_size * 0.1);

        // Very large line height
        context.set_line_height(10.0);
        let initial_y2 = context.cursor_y;
        context.newline();
        assert_eq!(context.cursor_y, initial_y2 - context.font_size * 10.0);
    }

    #[test]
    fn test_zero_content_width() {
        let margins = Margins {
            left: 200.0,
            right: 200.0,
            top: 50.0,
            bottom: 50.0,
        };
        let context = TextFlowContext::new(400.0, 600.0, margins);

        assert_eq!(context.content_width(), 0.0);
    }

    #[test]
    fn test_cursor_x_reset_on_newline() {
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins.clone());

        context.at(250.0, 300.0); // Move cursor to custom position
        context.newline();

        // X should reset to left margin
        assert_eq!(context.cursor_x, margins.left);
        // Y should decrease by line height
        assert_eq!(
            context.cursor_y,
            300.0 - context.font_size * context.line_height
        );
    }

    // --- Issue #167: available_width respects cursor_x ---

    #[test]
    fn test_available_width_respects_cursor_x() {
        // Page: 400pt wide, 50pt margins each side → content_width = 300pt
        let margins = create_test_margins(); // left=50, right=50
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        // Default: cursor_x == margins.left == 50, available_width == 300
        assert_eq!(context.available_width(), 300.0);

        // After .at(200, 500): cursor_x = 200, available_width = 400 - 50 - 200 = 150
        context.at(200.0, 500.0);
        assert_eq!(context.available_width(), 150.0);
    }

    #[test]
    fn test_available_width_clamps_to_zero() {
        // cursor_x past the right margin → available_width = 0 (not negative)
        let margins = create_test_margins(); // right = 50
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        // cursor_x = 380, right margin = 50 → would be 400-50-380 = -30 → clamp to 0
        context.at(380.0, 500.0);
        assert_eq!(context.available_width(), 0.0);
    }

    #[test]
    fn test_write_wrapped_at_x_limits_available_width() {
        // Page 400pt, margins 50pt each → content_width = 300pt
        // Place cursor at x=250: available_width = 400-50-250 = 100pt
        // Use text wider than 100pt but narrower than 300pt → must wrap at x=250
        let margins = create_test_margins();
        let mut context = TextFlowContext::new(400.0, 600.0, margins);

        context.set_font(Font::Helvetica, 12.0);
        // "Hello World Hello World" at 12pt Helvetica exceeds 100pt easily
        context.at(250.0, 500.0);
        context.write_wrapped("Hello World Hello World").unwrap();

        let ops = context.operations();
        // Multiple BT blocks → wrapping occurred
        let bt_count = ops.matches("BT\n").count();
        assert!(
            bt_count > 1,
            "Expected wrapping (multiple lines), got {bt_count} BT blocks. ops:\n{ops}"
        );
    }

    #[test]
    fn test_write_wrapped_respects_cursor_x_offset() {
        // Cursor at x=300, page 600pt wide, margins 50pt each → available_width = 250pt
        let margins = Margins {
            left: 50.0,
            right: 50.0,
            top: 50.0,
            bottom: 50.0,
        };
        let mut context = TextFlowContext::new(600.0, 800.0, margins);

        context.set_font(Font::Helvetica, 12.0);
        context.at(300.0, 700.0);
        context
            .write_wrapped("Hello World Foo Bar Baz Qux")
            .unwrap();

        let ops = context.operations();
        // Every Td x-coordinate should be >= 300.0
        for line in ops.lines() {
            if line.ends_with(" Td") {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 3 {
                    let x: f64 = parts[0].parse().expect("Td x should be a number");
                    assert!(
                        x >= 300.0 - 1e-6,
                        "Expected Td x >= 300.0 but got {x}. ops:\n{ops}"
                    );
                }
            }
        }
    }
}