oxidize-pdf 2.5.1

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
//! PDF operations module
//!
//! This module provides high-level operations for manipulating PDF documents
//! such as splitting, merging, rotating pages, and reordering.

pub mod chunk_page_mapper;
pub mod extract_images;
pub mod merge;
pub mod overlay;
pub mod page_analysis;
pub mod page_extraction;
pub mod pdf_ocr_converter;
pub mod reorder;
pub mod rotate;
pub mod semantic_redactor;
pub mod source_highlighter;
pub mod split;

pub use chunk_page_mapper::ChunkPageMapper;
pub use extract_images::{
    extract_images_from_pages, extract_images_from_pdf, ExtractImagesOptions, ExtractedImage,
    ImageExtractor,
};
pub use merge::{merge_pdf_files, merge_pdfs, MergeInput, MergeOptions, PdfMerger};
pub use overlay::{overlay_pdf, OverlayOptions, OverlayPosition, PdfOverlay};
pub use page_analysis::{AnalysisOptions, ContentAnalysis, PageContentAnalyzer, PageType};
pub use page_extraction::{
    extract_page, extract_page_range, extract_page_range_to_file, extract_page_to_file,
    extract_pages, extract_pages_to_file, PageExtractionOptions, PageExtractor,
};
pub use pdf_ocr_converter::{ConversionOptions, ConversionResult, PdfOcrConverter};
pub use reorder::{
    move_pdf_page, reorder_pdf_pages, reverse_pdf_pages, swap_pdf_pages, PageReorderer,
    ReorderOptions,
};
pub use rotate::{rotate_all_pages, rotate_pdf_pages, PageRotator, RotateOptions, RotationAngle};
pub use semantic_redactor::{
    RedactionConfig, RedactionEntry, RedactionReport, RedactionStyle, SemanticRedactor,
    SemanticRedactorError, SemanticRedactorResult,
};
pub use source_highlighter::{
    fragment_to_highlight_rect, HighlightStyle, IndexedFragment, SourceHighlighter,
    SourceHighlighterError, SourceHighlighterResult, TextPositionIndex,
};
pub use split::{split_into_pages, split_pdf, PdfSplitter, SplitMode, SplitOptions};

use crate::error::PdfError;

/// Result type for operations
pub type OperationResult<T> = Result<T, OperationError>;

/// Operation-specific errors
#[derive(Debug, thiserror::Error)]
pub enum OperationError {
    /// Page index out of bounds
    #[error("Page index {0} out of bounds (document has {1} pages)")]
    PageIndexOutOfBounds(usize, usize),

    /// Invalid page range
    #[error("Invalid page range: {0}")]
    InvalidPageRange(String),

    /// No pages to process
    #[error("No pages to process")]
    NoPagesToProcess,

    /// Resource conflict during merge
    #[error("Resource conflict: {0}")]
    ResourceConflict(String),

    /// Invalid rotation angle
    #[error("Invalid rotation angle: {0} (must be 0, 90, 180, or 270)")]
    InvalidRotation(i32),

    /// Parse error
    #[error("Parse error: {0}")]
    ParseError(String),

    /// Invalid file path
    #[error("Invalid file path: {reason}")]
    InvalidPath { reason: String },

    /// IO error
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// Core PDF error
    #[error("PDF error: {0}")]
    PdfError(#[from] PdfError),

    /// General processing error
    #[error("Processing error: {0}")]
    ProcessingError(String),
}

/// Page range specification
#[derive(Debug, Clone)]
pub enum PageRange {
    /// All pages
    All,
    /// Single page (0-based index)
    Single(usize),
    /// Range of pages (inclusive, 0-based)
    Range(usize, usize),
    /// List of specific pages (0-based indices)
    List(Vec<usize>),
}

impl PageRange {
    /// Parse a page range from a string
    ///
    /// Examples:
    /// - "all" -> All pages
    /// - "1" -> Single page (converts to 0-based)
    /// - "1-5" -> Range of pages (converts to 0-based)
    /// - "1,3,5" -> List of pages (converts to 0-based)
    pub fn parse(s: &str) -> Result<Self, OperationError> {
        let s = s.trim();

        if s.eq_ignore_ascii_case("all") {
            return Ok(PageRange::All);
        }

        // Try single page
        if let Ok(page) = s.parse::<usize>() {
            if page == 0 {
                return Err(OperationError::InvalidPageRange(
                    "Page numbers start at 1".to_string(),
                ));
            }
            return Ok(PageRange::Single(page - 1));
        }

        // Try range (e.g., "1-5")
        if let Some((start, end)) = s.split_once('-') {
            let start = start
                .trim()
                .parse::<usize>()
                .map_err(|_| OperationError::InvalidPageRange(format!("Invalid start: {start}")))?;
            let end = end
                .trim()
                .parse::<usize>()
                .map_err(|_| OperationError::InvalidPageRange(format!("Invalid end: {end}")))?;

            if start == 0 || end == 0 {
                return Err(OperationError::InvalidPageRange(
                    "Page numbers start at 1".to_string(),
                ));
            }

            if start > end {
                return Err(OperationError::InvalidPageRange(format!(
                    "Start {start} is greater than end {end}"
                )));
            }

            return Ok(PageRange::Range(start - 1, end - 1));
        }

        // Try list (e.g., "1,3,5")
        if s.contains(',') {
            let pages: Result<Vec<usize>, _> = s
                .split(',')
                .map(|p| {
                    let page = p.trim().parse::<usize>().map_err(|_| {
                        OperationError::InvalidPageRange(format!("Invalid page: {p}"))
                    })?;
                    if page == 0 {
                        return Err(OperationError::InvalidPageRange(
                            "Page numbers start at 1".to_string(),
                        ));
                    }
                    Ok(page - 1)
                })
                .collect();

            return Ok(PageRange::List(pages?));
        }

        Err(OperationError::InvalidPageRange(format!(
            "Invalid format: {s}"
        )))
    }

    /// Get the page indices for this range
    pub fn get_indices(&self, total_pages: usize) -> Result<Vec<usize>, OperationError> {
        match self {
            PageRange::All => Ok((0..total_pages).collect()),
            PageRange::Single(idx) => {
                if *idx >= total_pages {
                    Err(OperationError::PageIndexOutOfBounds(*idx, total_pages))
                } else {
                    Ok(vec![*idx])
                }
            }
            PageRange::Range(start, end) => {
                if *start >= total_pages {
                    Err(OperationError::PageIndexOutOfBounds(*start, total_pages))
                } else if *end >= total_pages {
                    Err(OperationError::PageIndexOutOfBounds(*end, total_pages))
                } else {
                    Ok((*start..=*end).collect())
                }
            }
            PageRange::List(pages) => {
                for &page in pages {
                    if page >= total_pages {
                        return Err(OperationError::PageIndexOutOfBounds(page, total_pages));
                    }
                }
                Ok(pages.clone())
            }
        }
    }
}

#[cfg(test)]
mod error_tests;

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

    #[test]
    fn test_page_range_parsing() {
        assert!(matches!(PageRange::parse("all").unwrap(), PageRange::All));
        assert!(matches!(PageRange::parse("ALL").unwrap(), PageRange::All));

        match PageRange::parse("5").unwrap() {
            PageRange::Single(idx) => assert_eq!(idx, 4),
            _ => panic!("Expected Single"),
        }

        match PageRange::parse("2-5").unwrap() {
            PageRange::Range(start, end) => {
                assert_eq!(start, 1);
                assert_eq!(end, 4);
            }
            _ => panic!("Expected Range"),
        }

        match PageRange::parse("1,3,5,7").unwrap() {
            PageRange::List(pages) => {
                assert_eq!(pages, vec![0, 2, 4, 6]);
            }
            _ => panic!("Expected List"),
        }

        assert!(PageRange::parse("0").is_err());
        assert!(PageRange::parse("5-2").is_err());
        assert!(PageRange::parse("invalid").is_err());
    }

    #[test]
    fn test_page_range_indices() {
        let total = 10;

        assert_eq!(
            PageRange::All.get_indices(total).unwrap(),
            vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        );

        assert_eq!(PageRange::Single(5).get_indices(total).unwrap(), vec![5]);

        assert_eq!(
            PageRange::Range(2, 5).get_indices(total).unwrap(),
            vec![2, 3, 4, 5]
        );

        assert_eq!(
            PageRange::List(vec![1, 3, 5]).get_indices(total).unwrap(),
            vec![1, 3, 5]
        );

        assert!(PageRange::Single(10).get_indices(total).is_err());
        assert!(PageRange::Range(8, 15).get_indices(total).is_err());
    }

    #[test]
    fn test_page_range_empty_list() {
        // Test parsing an empty list of pages
        let result = PageRange::parse("");
        assert!(result.is_err());

        // Test list with only commas
        let result2 = PageRange::parse(",,");
        assert!(result2.is_err());
    }

    #[test]
    fn test_page_range_list_with_zero() {
        // Test that 0 in a list causes error (line 148-151)
        let result = PageRange::parse("1,0,3");
        assert!(result.is_err());
        if let Err(e) = result {
            match e {
                OperationError::InvalidPageRange(msg) => {
                    assert!(msg.contains("Page numbers start at 1"));
                }
                _ => panic!("Expected InvalidPageRange error"),
            }
        }
    }

    #[test]
    fn test_page_range_with_extra_spaces() {
        // Test parsing with extra spaces in list (line 143-144)
        match PageRange::parse(" 1 , 3 , 5 ").unwrap() {
            PageRange::List(pages) => {
                assert_eq!(pages, vec![0, 2, 4]);
            }
            _ => panic!("Expected List"),
        }

        // Test range with spaces
        match PageRange::parse(" 2 - 5 ").unwrap() {
            PageRange::Range(start, end) => {
                assert_eq!(start, 1);
                assert_eq!(end, 4);
            }
            _ => panic!("Expected Range"),
        }
    }

    #[test]
    fn test_page_range_equal_start_end() {
        // Test range where start == end (should work)
        match PageRange::parse("5-5").unwrap() {
            PageRange::Range(start, end) => {
                assert_eq!(start, 4);
                assert_eq!(end, 4);
            }
            _ => panic!("Expected Range"),
        }

        // Verify get_indices works correctly
        let range = PageRange::Range(4, 4);
        assert_eq!(range.get_indices(10).unwrap(), vec![4]);
    }

    #[test]
    fn test_page_range_list_out_of_bounds() {
        // Test List variant with out of bounds indices (line 186-190)
        let pages = PageRange::List(vec![2, 5, 15]);
        let result = pages.get_indices(10);
        assert!(result.is_err());
        if let Err(e) = result {
            match e {
                OperationError::PageIndexOutOfBounds(idx, total) => {
                    assert_eq!(idx, 15);
                    assert_eq!(total, 10);
                }
                _ => panic!("Expected PageIndexOutOfBounds error"),
            }
        }
    }

    #[test]
    fn test_page_range_empty_document() {
        // Test get_indices with 0 total pages
        let total = 0;

        // All should return empty vector
        assert_eq!(
            PageRange::All.get_indices(total).unwrap(),
            Vec::<usize>::new()
        );

        // Single should fail
        assert!(PageRange::Single(0).get_indices(total).is_err());

        // Range should fail
        assert!(PageRange::Range(0, 1).get_indices(total).is_err());

        // Empty list should work
        assert_eq!(
            PageRange::List(vec![]).get_indices(total).unwrap(),
            Vec::<usize>::new()
        );
    }

    #[test]
    fn test_page_range_additional_invalid_formats() {
        // Test various invalid formats (line 160-162)
        assert!(PageRange::parse("1-2-3").is_err()); // Multiple dashes
        assert!(PageRange::parse("abc").is_err()); // Non-numeric
        assert!(PageRange::parse("1.5").is_err()); // Decimal
        assert!(PageRange::parse("-5").is_err()); // Negative without start
        assert!(PageRange::parse("1-").is_err()); // Missing end
        assert!(PageRange::parse("-").is_err()); // Only dash
    }

    #[test]
    fn test_module_exports() {
        // Verify that all operation types are exported correctly
        // This test just ensures the module structure is correct

        // We can create these types through their modules
        use super::extract_images::ExtractImagesOptions;
        use super::merge::MergeOptions;
        use super::page_analysis::{AnalysisOptions, PageType};
        use super::page_extraction::PageExtractionOptions;
        use super::rotate::{RotateOptions, RotationAngle};
        use super::split::{SplitMode, SplitOptions};

        // Just verify we can access these types
        let _extract: ExtractImagesOptions;
        let _merge: MergeOptions;
        let _analysis: AnalysisOptions;
        let _extraction: PageExtractionOptions;
        let _rotate: RotateOptions;
        let _split: SplitOptions;
        let _angle: RotationAngle;
        let _page_type: PageType;
        let _mode: SplitMode;
    }

    #[test]
    fn test_operation_error_variants() {
        let errors = vec![
            OperationError::PageIndexOutOfBounds(5, 3),
            OperationError::InvalidPageRange("test".to_string()),
            OperationError::NoPagesToProcess,
            OperationError::ResourceConflict("test".to_string()),
            OperationError::InvalidRotation(45),
            OperationError::ParseError("test".to_string()),
            OperationError::ProcessingError("test".to_string()),
        ];

        for error in errors {
            let message = error.to_string();
            assert!(!message.is_empty());
        }
    }

    #[test]
    fn test_page_range_edge_cases() {
        // Test whitespace handling
        assert!(matches!(
            PageRange::parse("  all  ").unwrap(),
            PageRange::All
        ));
        assert!(matches!(
            PageRange::parse(" 5 ").unwrap(),
            PageRange::Single(4)
        ));

        // Test various list formats
        match PageRange::parse(" 1 , 3 , 5 ").unwrap() {
            PageRange::List(pages) => assert_eq!(pages, vec![0, 2, 4]),
            _ => panic!("Expected List"),
        }

        // Test range with spaces
        match PageRange::parse(" 2 - 5 ").unwrap() {
            PageRange::Range(start, end) => {
                assert_eq!(start, 1);
                assert_eq!(end, 4);
            }
            _ => panic!("Expected Range"),
        }
    }

    #[test]
    fn test_page_range_invalid_formats() {
        // Test various invalid formats
        assert!(PageRange::parse("").is_err());
        assert!(PageRange::parse("abc").is_err());
        assert!(PageRange::parse("1-").is_err());
        assert!(PageRange::parse("-5").is_err());
        assert!(PageRange::parse("1-2-3").is_err());
        assert!(PageRange::parse("1,0,3").is_err());
        assert!(PageRange::parse("0-5").is_err());
        assert!(PageRange::parse("5-0").is_err());
        assert!(PageRange::parse("1,,3").is_err());
        assert!(PageRange::parse("1.5").is_err());
    }

    #[test]
    fn test_page_range_get_indices_empty_document() {
        let total = 0;

        assert_eq!(
            PageRange::All.get_indices(total).unwrap(),
            vec![] as Vec<usize>
        );
        assert!(PageRange::Single(0).get_indices(total).is_err());
        assert!(PageRange::Range(0, 1).get_indices(total).is_err());
        assert!(PageRange::List(vec![0]).get_indices(total).is_err());
    }

    #[test]
    fn test_page_range_get_indices_single_page_document() {
        let total = 1;

        assert_eq!(PageRange::All.get_indices(total).unwrap(), vec![0]);
        assert_eq!(PageRange::Single(0).get_indices(total).unwrap(), vec![0]);
        assert!(PageRange::Single(1).get_indices(total).is_err());
        assert_eq!(PageRange::Range(0, 0).get_indices(total).unwrap(), vec![0]);
        assert!(PageRange::Range(0, 1).get_indices(total).is_err());
    }

    #[test]
    fn test_page_range_list_duplicates() {
        // Lists can have duplicates in our implementation
        match PageRange::parse("1,1,2,2,3").unwrap() {
            PageRange::List(pages) => {
                assert_eq!(pages, vec![0, 0, 1, 1, 2]);
            }
            _ => panic!("Expected List"),
        }
    }

    #[test]
    fn test_page_range_list_unordered() {
        // Lists don't need to be ordered
        match PageRange::parse("5,2,8,1,3").unwrap() {
            PageRange::List(pages) => {
                assert_eq!(pages, vec![4, 1, 7, 0, 2]);
            }
            _ => panic!("Expected List"),
        }
    }

    #[test]
    fn test_operation_error_display() {
        let error = OperationError::PageIndexOutOfBounds(10, 5);
        assert_eq!(
            error.to_string(),
            "Page index 10 out of bounds (document has 5 pages)"
        );

        let error = OperationError::InvalidRotation(45);
        assert_eq!(
            error.to_string(),
            "Invalid rotation angle: 45 (must be 0, 90, 180, or 270)"
        );

        let error = OperationError::NoPagesToProcess;
        assert_eq!(error.to_string(), "No pages to process");
    }

    #[test]
    fn test_page_range_large_document() {
        let total = 1000;

        // Test all pages
        let indices = PageRange::All.get_indices(total).unwrap();
        assert_eq!(indices.len(), 1000);
        assert_eq!(indices[0], 0);
        assert_eq!(indices[999], 999);

        // Test large range
        let indices = PageRange::Range(100, 200).get_indices(total).unwrap();
        assert_eq!(indices.len(), 101);
        assert_eq!(indices[0], 100);
        assert_eq!(indices[100], 200);
    }

    #[test]
    fn test_page_range_parse_case_insensitive() {
        assert!(matches!(PageRange::parse("all").unwrap(), PageRange::All));
        assert!(matches!(PageRange::parse("ALL").unwrap(), PageRange::All));
        assert!(matches!(PageRange::parse("All").unwrap(), PageRange::All));
        assert!(matches!(PageRange::parse("aLL").unwrap(), PageRange::All));
    }

    #[test]
    fn test_operation_result_type() {
        // Test that OperationResult works correctly
        fn test_function() -> OperationResult<usize> {
            Ok(42)
        }

        fn test_error_function() -> OperationResult<usize> {
            Err(OperationError::NoPagesToProcess)
        }

        assert_eq!(test_function().unwrap(), 42);
        assert!(test_error_function().is_err());
    }

    #[test]
    fn test_page_range_boundary_values() {
        // Test maximum safe values
        let large_page = usize::MAX / 2;

        match PageRange::parse(&large_page.to_string()).unwrap() {
            PageRange::Single(idx) => assert_eq!(idx, large_page - 1),
            _ => panic!("Expected Single"),
        }

        // Test with actual document
        let indices = PageRange::Single(5).get_indices(10).unwrap();
        assert_eq!(indices, vec![5]);

        // Test range boundary
        let indices = PageRange::Range(0, 9).get_indices(10).unwrap();
        assert_eq!(indices.len(), 10);
    }

    #[test]
    fn test_error_from_io() {
        use std::io;

        let io_error = io::Error::new(io::ErrorKind::NotFound, "File not found");
        let op_error: OperationError = io_error.into();

        match op_error {
            OperationError::Io(_) => {}
            _ => panic!("Expected Io variant"),
        }
    }

    #[test]
    fn test_page_range_fmt_debug() {
        // Test Debug implementation
        let range = PageRange::All;
        let debug_str = format!("{:?}", range);
        assert!(debug_str.contains("All"));

        let range = PageRange::Single(5);
        let debug_str = format!("{:?}", range);
        assert!(debug_str.contains("Single"));
        assert!(debug_str.contains("5"));

        let range = PageRange::Range(1, 10);
        let debug_str = format!("{:?}", range);
        assert!(debug_str.contains("Range"));

        let range = PageRange::List(vec![1, 2, 3]);
        let debug_str = format!("{:?}", range);
        assert!(debug_str.contains("List"));
    }

    #[test]
    fn test_page_range_clone() {
        let original = PageRange::List(vec![1, 2, 3]);
        let cloned = original.clone();

        match (original, cloned) {
            (PageRange::List(orig), PageRange::List(clone)) => {
                assert_eq!(orig, clone);
            }
            _ => panic!("Clone failed"),
        }
    }
}