oxidize-pdf 2.4.3

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
//! PDF page rotation functionality
//!
//! This module provides functionality to rotate pages in PDF documents.

use super::{OperationError, OperationResult, PageRange};
use crate::parser::page_tree::ParsedPage;
use crate::parser::{ContentOperation, ContentParser, PdfDocument, PdfReader};
use crate::{Document, Page};
use std::fs::File;
use std::path::Path;

/// Rotation angle
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RotationAngle {
    /// No rotation (0 degrees)
    None,
    /// 90 degrees clockwise
    Clockwise90,
    /// 180 degrees
    Rotate180,
    /// 270 degrees clockwise (90 degrees counter-clockwise)
    Clockwise270,
}

impl RotationAngle {
    /// Create from degrees
    pub fn from_degrees(degrees: i32) -> Result<Self, OperationError> {
        let normalized = degrees % 360;
        let normalized = if normalized < 0 {
            normalized + 360
        } else {
            normalized
        };

        match normalized {
            0 => Ok(RotationAngle::None),
            90 => Ok(RotationAngle::Clockwise90),
            180 => Ok(RotationAngle::Rotate180),
            270 => Ok(RotationAngle::Clockwise270),
            _ => Err(OperationError::InvalidRotation(degrees)),
        }
    }

    /// Convert to degrees
    pub fn to_degrees(self) -> i32 {
        match self {
            RotationAngle::None => 0,
            RotationAngle::Clockwise90 => 90,
            RotationAngle::Rotate180 => 180,
            RotationAngle::Clockwise270 => 270,
        }
    }

    /// Combine two rotations
    pub fn combine(self, other: RotationAngle) -> RotationAngle {
        let total = (self.to_degrees() + other.to_degrees()) % 360;
        // SAFETY: The modulo 360 operation guarantees only valid angles (0, 90, 180, 270)
        // since all RotationAngle variants are multiples of 90 degrees
        match total {
            0 => RotationAngle::None,
            90 => RotationAngle::Clockwise90,
            180 => RotationAngle::Rotate180,
            270 => RotationAngle::Clockwise270,
            _ => unreachable!("Modulo 360 of multiples of 90 can only be 0, 90, 180, or 270"),
        }
    }
}

/// Options for page rotation
#[derive(Debug, Clone)]
pub struct RotateOptions {
    /// Pages to rotate
    pub pages: PageRange,
    /// Rotation angle
    pub angle: RotationAngle,
    /// Whether to preserve the original page size (vs adjusting for rotated content)
    pub preserve_page_size: bool,
}

impl Default for RotateOptions {
    fn default() -> Self {
        Self {
            pages: PageRange::All,
            angle: RotationAngle::Clockwise90,
            preserve_page_size: false,
        }
    }
}

/// PDF page rotator
pub struct PageRotator {
    document: PdfDocument<File>,
}

impl PageRotator {
    /// Create a new page rotator
    pub fn new(document: PdfDocument<File>) -> Self {
        Self { document }
    }

    /// Rotate pages according to options
    pub fn rotate(&mut self, options: &RotateOptions) -> OperationResult<Document> {
        let total_pages =
            self.document
                .page_count()
                .map_err(|e| OperationError::ParseError(e.to_string()))? as usize;

        let page_indices = options.pages.get_indices(total_pages)?;
        let mut output_doc = Document::new();

        // Copy metadata
        if let Ok(metadata) = self.document.metadata() {
            if let Some(title) = metadata.title {
                output_doc.set_title(&title);
            }
            if let Some(author) = metadata.author {
                output_doc.set_author(&author);
            }
            if let Some(subject) = metadata.subject {
                output_doc.set_subject(&subject);
            }
            if let Some(keywords) = metadata.keywords {
                output_doc.set_keywords(&keywords);
            }
        }

        // Process each page
        for page_idx in 0..total_pages {
            let parsed_page = self
                .document
                .get_page(page_idx as u32)
                .map_err(|e| OperationError::ParseError(e.to_string()))?;

            let should_rotate = page_indices.contains(&page_idx);

            let page = if should_rotate {
                self.create_rotated_page(&parsed_page, options.angle, options.preserve_page_size)?
            } else {
                self.create_page_copy(&parsed_page)?
            };

            output_doc.add_page(page);
        }

        Ok(output_doc)
    }

    /// Create a rotated copy of a page
    fn create_rotated_page(
        &mut self,
        parsed_page: &ParsedPage,
        angle: RotationAngle,
        preserve_size: bool,
    ) -> OperationResult<Page> {
        // Calculate the effective rotation
        let current_rotation = parsed_page.rotation;
        let _new_rotation = (current_rotation + angle.to_degrees()) % 360;

        // Get original dimensions
        let orig_width = parsed_page.media_box[2] - parsed_page.media_box[0];
        let orig_height = parsed_page.media_box[3] - parsed_page.media_box[1];

        // Calculate new dimensions based on rotation
        let (new_width, new_height) = if preserve_size {
            (orig_width, orig_height)
        } else {
            match angle {
                RotationAngle::None | RotationAngle::Rotate180 => (orig_width, orig_height),
                RotationAngle::Clockwise90 | RotationAngle::Clockwise270 => {
                    (orig_height, orig_width)
                }
            }
        };

        let mut page = Page::new(new_width, new_height);

        // Get content streams
        let content_streams = self
            .document
            .get_page_content_streams(parsed_page)
            .map_err(|e| OperationError::ParseError(e.to_string()))?;

        // Add rotation transformation
        match angle {
            RotationAngle::None => {
                // No rotation needed
            }
            RotationAngle::Clockwise90 => {
                // Rotate 90 degrees clockwise
                // Transform: x' = y, y' = width - x
                page.graphics()
                    .save_state()
                    .transform(0.0, 1.0, -1.0, 0.0, new_width, 0.0);
            }
            RotationAngle::Rotate180 => {
                // Rotate 180 degrees
                // Transform: x' = width - x, y' = height - y
                page.graphics()
                    .save_state()
                    .transform(-1.0, 0.0, 0.0, -1.0, new_width, new_height);
            }
            RotationAngle::Clockwise270 => {
                // Rotate 270 degrees clockwise (90 counter-clockwise)
                // Transform: x' = height - y, y' = x
                page.graphics()
                    .save_state()
                    .transform(0.0, -1.0, 1.0, 0.0, 0.0, new_height);
            }
        }

        // Parse and process content streams with rotation
        let mut has_content = false;
        for stream_data in &content_streams {
            match ContentParser::parse_content(stream_data) {
                Ok(operators) => {
                    // Process the operators with rotation transformation already applied
                    self.process_operators_with_rotation(&mut page, &operators)?;
                    has_content = true;
                }
                Err(e) => {
                    tracing::debug!("Warning: Failed to parse content stream: {e}");
                }
            }
        }

        // If no content was successfully processed, add a placeholder
        if !has_content {
            page.text()
                .set_font(crate::text::Font::Helvetica, 10.0)
                .at(50.0, new_height - 50.0)
                .write(&format!(
                    "[Page rotated {} degrees - content reconstruction in progress]",
                    angle.to_degrees()
                ))
                .map_err(OperationError::PdfError)?;
        }

        // Restore graphics state if we transformed
        if angle != RotationAngle::None {
            page.graphics().restore_state();
        }

        Ok(page)
    }

    /// Create a copy of a page without rotation
    fn create_page_copy(&mut self, parsed_page: &ParsedPage) -> OperationResult<Page> {
        let width = parsed_page.width();
        let height = parsed_page.height();
        let mut page = Page::new(width, height);

        // Get content streams
        let content_streams = self
            .document
            .get_page_content_streams(parsed_page)
            .map_err(|e| OperationError::ParseError(e.to_string()))?;

        // Parse and process content streams
        let mut has_content = false;
        for stream_data in content_streams {
            match ContentParser::parse_content(&stream_data) {
                Ok(operators) => {
                    self.process_operators_with_rotation(&mut page, &operators)?;
                    has_content = true;
                }
                Err(e) => {
                    tracing::debug!("Warning: Failed to parse content stream: {e}");
                }
            }
        }

        // If no content was successfully processed, add a placeholder
        if !has_content {
            page.text()
                .set_font(crate::text::Font::Helvetica, 10.0)
                .at(50.0, height - 50.0)
                .write("[Page copied - content reconstruction in progress]")
                .map_err(OperationError::PdfError)?;
        }

        Ok(page)
    }

    /// Process content operators (rotation transformation already applied via graphics state)
    fn process_operators_with_rotation(
        &self,
        page: &mut Page,
        operators: &[ContentOperation],
    ) -> OperationResult<()> {
        // Track graphics state
        let mut text_object = false;
        let mut current_font = crate::text::Font::Helvetica;
        let mut current_font_size = 12.0;
        let mut current_x = 0.0;
        let mut current_y = 0.0;

        for operator in operators {
            match operator {
                ContentOperation::BeginText => {
                    text_object = true;
                }
                ContentOperation::EndText => {
                    text_object = false;
                }
                ContentOperation::SetFont(name, size) => {
                    // Map PDF font names to our fonts
                    current_font = match name.as_str() {
                        "Times-Roman" => crate::text::Font::TimesRoman,
                        "Times-Bold" => crate::text::Font::TimesBold,
                        "Times-Italic" => crate::text::Font::TimesItalic,
                        "Times-BoldItalic" => crate::text::Font::TimesBoldItalic,
                        "Helvetica-Bold" => crate::text::Font::HelveticaBold,
                        "Helvetica-Oblique" => crate::text::Font::HelveticaOblique,
                        "Helvetica-BoldOblique" => crate::text::Font::HelveticaBoldOblique,
                        "Courier" => crate::text::Font::Courier,
                        "Courier-Bold" => crate::text::Font::CourierBold,
                        "Courier-Oblique" => crate::text::Font::CourierOblique,
                        "Courier-BoldOblique" => crate::text::Font::CourierBoldOblique,
                        _ => crate::text::Font::Helvetica,
                    };
                    current_font_size = *size;
                }
                ContentOperation::MoveText(tx, ty) => {
                    current_x += tx;
                    current_y += ty;
                }
                ContentOperation::ShowText(text_bytes) => {
                    if text_object {
                        if let Ok(text) = String::from_utf8(text_bytes.clone()) {
                            page.text()
                                .set_font(current_font.clone(), current_font_size as f64)
                                .at(current_x as f64, current_y as f64)
                                .write(&text)
                                .map_err(OperationError::PdfError)?;
                        }
                    }
                }
                ContentOperation::Rectangle(x, y, width, height) => {
                    page.graphics()
                        .rect(*x as f64, *y as f64, *width as f64, *height as f64);
                }
                ContentOperation::MoveTo(x, y) => {
                    page.graphics().move_to(*x as f64, *y as f64);
                }
                ContentOperation::LineTo(x, y) => {
                    page.graphics().line_to(*x as f64, *y as f64);
                }
                ContentOperation::Stroke => {
                    page.graphics().stroke();
                }
                ContentOperation::Fill => {
                    page.graphics().fill();
                }
                ContentOperation::SetNonStrokingRGB(r, g, b) => {
                    page.graphics().set_fill_color(crate::graphics::Color::Rgb(
                        *r as f64, *g as f64, *b as f64,
                    ));
                }
                ContentOperation::SetStrokingRGB(r, g, b) => {
                    page.graphics()
                        .set_stroke_color(crate::graphics::Color::Rgb(
                            *r as f64, *g as f64, *b as f64,
                        ));
                }
                ContentOperation::SetLineWidth(width) => {
                    page.graphics().set_line_width(*width as f64);
                }
                // Graphics state operators are important for rotation
                ContentOperation::SaveGraphicsState => {
                    page.graphics().save_state();
                }
                ContentOperation::RestoreGraphicsState => {
                    page.graphics().restore_state();
                }
                ContentOperation::SetTransformMatrix(a, b, c, d, e, f) => {
                    page.graphics().transform(
                        *a as f64, *b as f64, *c as f64, *d as f64, *e as f64, *f as f64,
                    );
                }
                _ => {
                    // Silently skip unimplemented operators for now
                }
            }
        }

        Ok(())
    }
}

/// Rotate pages in a PDF file
pub fn rotate_pdf_pages<P: AsRef<Path>, Q: AsRef<Path>>(
    input_path: P,
    output_path: Q,
    options: RotateOptions,
) -> OperationResult<()> {
    let document = PdfReader::open_document(input_path)
        .map_err(|e| OperationError::ParseError(e.to_string()))?;

    let mut rotator = PageRotator::new(document);
    let mut doc = rotator.rotate(&options)?;

    doc.save(output_path)?;
    Ok(())
}

/// Rotate all pages in a PDF file
pub fn rotate_all_pages<P: AsRef<Path>, Q: AsRef<Path>>(
    input_path: P,
    output_path: Q,
    angle: RotationAngle,
) -> OperationResult<()> {
    let options = RotateOptions {
        pages: PageRange::All,
        angle,
        preserve_page_size: false,
    };

    rotate_pdf_pages(input_path, output_path, options)
}

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

    #[test]
    fn test_rotation_angle() {
        assert_eq!(RotationAngle::from_degrees(0).unwrap(), RotationAngle::None);
        assert_eq!(
            RotationAngle::from_degrees(90).unwrap(),
            RotationAngle::Clockwise90
        );
        assert_eq!(
            RotationAngle::from_degrees(180).unwrap(),
            RotationAngle::Rotate180
        );
        assert_eq!(
            RotationAngle::from_degrees(270).unwrap(),
            RotationAngle::Clockwise270
        );

        // Test normalization
        assert_eq!(
            RotationAngle::from_degrees(360).unwrap(),
            RotationAngle::None
        );
        assert_eq!(
            RotationAngle::from_degrees(450).unwrap(),
            RotationAngle::Clockwise90
        );
        assert_eq!(
            RotationAngle::from_degrees(-90).unwrap(),
            RotationAngle::Clockwise270
        );

        // Test invalid angles
        assert!(RotationAngle::from_degrees(45).is_err());
        assert!(RotationAngle::from_degrees(135).is_err());
    }

    #[test]
    fn test_rotation_combine() {
        let r1 = RotationAngle::Clockwise90;
        let r2 = RotationAngle::Clockwise90;
        assert_eq!(r1.combine(r2), RotationAngle::Rotate180);

        let r3 = RotationAngle::Clockwise270;
        let r4 = RotationAngle::Clockwise90;
        assert_eq!(r3.combine(r4), RotationAngle::None);
    }

    // ============= Comprehensive Rotation Tests =============

    #[test]
    fn test_rotation_to_degrees() {
        assert_eq!(RotationAngle::None.to_degrees(), 0);
        assert_eq!(RotationAngle::Clockwise90.to_degrees(), 90);
        assert_eq!(RotationAngle::Rotate180.to_degrees(), 180);
        assert_eq!(RotationAngle::Clockwise270.to_degrees(), 270);
    }

    #[test]
    fn test_rotation_normalization_positive() {
        // Test positive angle normalization
        assert_eq!(
            RotationAngle::from_degrees(360).unwrap(),
            RotationAngle::None
        );
        assert_eq!(
            RotationAngle::from_degrees(450).unwrap(),
            RotationAngle::Clockwise90
        );
        assert_eq!(
            RotationAngle::from_degrees(540).unwrap(),
            RotationAngle::Rotate180
        );
        assert_eq!(
            RotationAngle::from_degrees(630).unwrap(),
            RotationAngle::Clockwise270
        );
        assert_eq!(
            RotationAngle::from_degrees(720).unwrap(),
            RotationAngle::None
        );
        assert_eq!(
            RotationAngle::from_degrees(810).unwrap(),
            RotationAngle::Clockwise90
        );
    }

    #[test]
    fn test_rotation_normalization_negative() {
        // Test negative angle normalization
        assert_eq!(
            RotationAngle::from_degrees(-90).unwrap(),
            RotationAngle::Clockwise270
        );
        assert_eq!(
            RotationAngle::from_degrees(-180).unwrap(),
            RotationAngle::Rotate180
        );
        assert_eq!(
            RotationAngle::from_degrees(-270).unwrap(),
            RotationAngle::Clockwise90
        );
        assert_eq!(
            RotationAngle::from_degrees(-360).unwrap(),
            RotationAngle::None
        );
        assert_eq!(
            RotationAngle::from_degrees(-450).unwrap(),
            RotationAngle::Clockwise270
        );
        assert_eq!(
            RotationAngle::from_degrees(-540).unwrap(),
            RotationAngle::Rotate180
        );
    }

    #[test]
    fn test_rotation_invalid_angles() {
        // Test all invalid angles that should return errors
        let invalid_angles = vec![
            1, 15, 30, 45, 60, 75, 89, 91, 105, 120, 135, 150, 165, 179, 181, 195, 210, 225, 240,
            255, 269, 271, 285, 300, 315, 330, 345, 359,
        ];

        for angle in invalid_angles {
            assert!(
                RotationAngle::from_degrees(angle).is_err(),
                "Angle {} should be invalid",
                angle
            );
            assert!(
                RotationAngle::from_degrees(-angle).is_err(),
                "Angle {} should be invalid",
                -angle
            );
        }
    }

    #[test]
    fn test_rotation_combine_all_combinations() {
        // Test all possible combinations of rotations
        let rotations = vec![
            RotationAngle::None,
            RotationAngle::Clockwise90,
            RotationAngle::Rotate180,
            RotationAngle::Clockwise270,
        ];

        // Expected results for each combination (row combines with column)
        let expected = vec![
            vec![
                RotationAngle::None,
                RotationAngle::Clockwise90,
                RotationAngle::Rotate180,
                RotationAngle::Clockwise270,
            ],
            vec![
                RotationAngle::Clockwise90,
                RotationAngle::Rotate180,
                RotationAngle::Clockwise270,
                RotationAngle::None,
            ],
            vec![
                RotationAngle::Rotate180,
                RotationAngle::Clockwise270,
                RotationAngle::None,
                RotationAngle::Clockwise90,
            ],
            vec![
                RotationAngle::Clockwise270,
                RotationAngle::None,
                RotationAngle::Clockwise90,
                RotationAngle::Rotate180,
            ],
        ];

        for (i, r1) in rotations.iter().enumerate() {
            for (j, r2) in rotations.iter().enumerate() {
                let result = r1.combine(*r2);
                assert_eq!(
                    result, expected[i][j],
                    "Combining {:?} with {:?} should give {:?}, got {:?}",
                    r1, r2, expected[i][j], result
                );
            }
        }
    }

    #[test]
    fn test_rotation_combine_chain() {
        // Test chaining multiple rotations
        let r1 = RotationAngle::Clockwise90;
        let r2 = RotationAngle::Clockwise90;
        let r3 = RotationAngle::Clockwise90;
        let r4 = RotationAngle::Clockwise90;

        let result = r1.combine(r2).combine(r3).combine(r4);
        assert_eq!(result, RotationAngle::None); // 4 * 90 = 360 = 0

        // Test another chain
        let result2 = RotationAngle::Clockwise270
            .combine(RotationAngle::Clockwise90)
            .combine(RotationAngle::Rotate180);
        assert_eq!(result2, RotationAngle::Rotate180); // 270 + 90 + 180 = 540 = 180
    }

    #[test]
    fn test_rotation_identity() {
        // Test that None is the identity element
        let rotations = vec![
            RotationAngle::None,
            RotationAngle::Clockwise90,
            RotationAngle::Rotate180,
            RotationAngle::Clockwise270,
        ];

        for rotation in rotations {
            assert_eq!(rotation.combine(RotationAngle::None), rotation);
            assert_eq!(RotationAngle::None.combine(rotation), rotation);
        }
    }

    #[test]
    fn test_rotation_inverse() {
        // Test that each rotation has an inverse
        assert_eq!(
            RotationAngle::Clockwise90.combine(RotationAngle::Clockwise270),
            RotationAngle::None
        );
        assert_eq!(
            RotationAngle::Rotate180.combine(RotationAngle::Rotate180),
            RotationAngle::None
        );
        assert_eq!(
            RotationAngle::Clockwise270.combine(RotationAngle::Clockwise90),
            RotationAngle::None
        );
        assert_eq!(
            RotationAngle::None.combine(RotationAngle::None),
            RotationAngle::None
        );
    }

    #[test]
    fn test_rotation_options_default() {
        let options = RotateOptions::default();
        assert!(matches!(options.angle, RotationAngle::Clockwise90));
        assert!(matches!(options.pages, PageRange::All));
        assert!(!options.preserve_page_size);
    }

    #[test]
    fn test_rotation_options_with_angle() {
        let options = RotateOptions {
            angle: RotationAngle::Rotate180,
            pages: PageRange::Range(5, 10),
            preserve_page_size: false,
        };

        assert_eq!(options.angle, RotationAngle::Rotate180);

        if let PageRange::Range(start, end) = options.pages {
            assert_eq!(start, 5);
            assert_eq!(end, 10);
        } else {
            panic!("Expected Range page specification");
        }
    }

    #[test]
    fn test_rotation_options_all_pages() {
        let options = RotateOptions {
            angle: RotationAngle::Clockwise270,
            pages: PageRange::All,
            preserve_page_size: true,
        };

        assert_eq!(options.angle, RotationAngle::Clockwise270);
        assert!(matches!(options.pages, PageRange::All));
        assert!(options.preserve_page_size);
    }

    #[test]
    fn test_rotation_options_single_page() {
        let options = RotateOptions {
            angle: RotationAngle::Clockwise90,
            pages: PageRange::Single(0),
            preserve_page_size: false,
        };

        assert_eq!(options.angle, RotationAngle::Clockwise90);

        if let PageRange::Single(page) = options.pages {
            assert_eq!(page, 0);
        } else {
            panic!("Expected Single page specification");
        }
    }

    #[test]
    fn test_rotation_options_page_list() {
        let pages = vec![1, 3, 5, 7, 9];
        let options = RotateOptions {
            angle: RotationAngle::Rotate180,
            pages: PageRange::List(pages.clone()),
            preserve_page_size: false,
        };

        if let PageRange::List(list) = options.pages {
            assert_eq!(list, pages);
        } else {
            panic!("Expected List page specification");
        }
    }

    #[test]
    fn test_pdf_rotator_new() {
        // This test would need actual PDF document setup
        // For now, just test that the structure is correct
        let options = RotateOptions::default();
        assert_eq!(options.angle.to_degrees(), 90);
    }

    #[test]
    fn test_rotation_edge_cases() {
        // Test edge cases with large positive numbers
        assert_eq!(
            RotationAngle::from_degrees(1080).unwrap(),
            RotationAngle::None
        ); // 3 * 360
        assert_eq!(
            RotationAngle::from_degrees(990).unwrap(),
            RotationAngle::Clockwise270
        ); // 2*360 + 270

        // Test edge cases with large negative numbers
        assert_eq!(
            RotationAngle::from_degrees(-720).unwrap(),
            RotationAngle::None
        ); // -2 * 360
        assert_eq!(
            RotationAngle::from_degrees(-810).unwrap(),
            RotationAngle::Clockwise270
        ); // -2*360 - 90
    }

    #[test]
    fn test_rotation_associativity() {
        // Test that rotation combination is associative
        let r1 = RotationAngle::Clockwise90;
        let r2 = RotationAngle::Rotate180;
        let r3 = RotationAngle::Clockwise270;

        // (r1 + r2) + r3 should equal r1 + (r2 + r3)
        let left = r1.combine(r2).combine(r3);
        let right = r1.combine(r2.combine(r3));
        assert_eq!(left, right);
    }

    #[test]
    fn test_rotation_consistency() {
        // Test that from_degrees and to_degrees are consistent
        for angle in [0, 90, 180, 270].iter() {
            let rotation = RotationAngle::from_degrees(*angle).unwrap();
            assert_eq!(rotation.to_degrees(), *angle);
        }
    }

    #[test]
    fn test_rotation_multiple_full_rotations() {
        // Test multiple full rotations
        for multiplier in 1..5 {
            let angle = 360 * multiplier;
            assert_eq!(
                RotationAngle::from_degrees(angle).unwrap(),
                RotationAngle::None,
                "Angle {} should normalize to None",
                angle
            );
            assert_eq!(
                RotationAngle::from_degrees(-angle).unwrap(),
                RotationAngle::None,
                "Angle {} should normalize to None",
                -angle
            );
        }
    }

    #[test]
    fn test_rotation_large_negative_angles() {
        // Test large negative angles (line 29-32)
        assert_eq!(
            RotationAngle::from_degrees(-720).unwrap(),
            RotationAngle::None
        );
        assert_eq!(
            RotationAngle::from_degrees(-1080).unwrap(),
            RotationAngle::None
        );
        assert_eq!(
            RotationAngle::from_degrees(-450).unwrap(),
            RotationAngle::Clockwise270
        );
        assert_eq!(
            RotationAngle::from_degrees(-630).unwrap(),
            RotationAngle::Clockwise90
        );
    }

    #[test]
    fn test_rotation_combine_overflow() {
        // Test combine that results in > 360 (line 56-57)
        let angle1 = RotationAngle::Clockwise270;
        let angle2 = RotationAngle::Rotate180;
        let combined = angle1.combine(angle2);
        assert_eq!(combined, RotationAngle::Clockwise90); // 270 + 180 = 450 % 360 = 90

        // Test multiple combines
        let angle3 = RotationAngle::Clockwise270;
        let result = angle1.combine(angle2).combine(angle3);
        assert_eq!(result, RotationAngle::None); // 90 + 270 = 360 % 360 = 0
    }

    #[test]
    fn test_rotation_extreme_values() {
        // Test with extreme i32 values (edge case for line 28-33)
        // These should not panic but might give unexpected results due to overflow
        let large_positive = 2147483647; // i32::MAX
        let result = RotationAngle::from_degrees(large_positive);
        assert!(result.is_err() || result.is_ok()); // Just ensure no panic

        let large_negative = -2147483648; // i32::MIN
        let result2 = RotationAngle::from_degrees(large_negative);
        assert!(result2.is_err() || result2.is_ok()); // Just ensure no panic

        // Test reasonable but large values
        assert_eq!(
            RotationAngle::from_degrees(3690).unwrap(),
            RotationAngle::Clockwise90 // 3690 % 360 = 90
        );
    }

    #[test]
    fn test_rotation_combine_unwrap_safety() {
        // Test that combine's unwrap is safe (line 57)
        // All valid combinations should produce valid results
        let angles = vec![
            RotationAngle::None,
            RotationAngle::Clockwise90,
            RotationAngle::Rotate180,
            RotationAngle::Clockwise270,
        ];

        for angle1 in &angles {
            for angle2 in &angles {
                // This should never panic
                let combined = angle1.combine(*angle2);

                // Verify the result is valid
                let total_degrees = (angle1.to_degrees() + angle2.to_degrees()) % 360;
                assert_eq!(combined.to_degrees(), total_degrees);
            }
        }
    }
}

#[cfg(test)]
#[path = "rotate_tests.rs"]
mod rotate_tests;