Skip to main content

rust_pdf_box/manipulation/
page_ops.rs

1use crate::error::{PdfError, PdfResult};
2use crate::pd::document::PDDocument;
3
4/// Common page operations (rotation, duplicate, reorder, delete).
5pub struct PageOps;
6
7impl PageOps {
8    /// Rotates a page by 90, 180, or 270 degrees clockwise.
9    pub fn rotate_page(doc: &mut PDDocument, page_index: usize, degrees: i32) -> PdfResult<()> {
10        let page = doc.get_page_mut(page_index)?;
11        let current_rotation = page.rotation();
12        page.set_rotation(current_rotation + degrees);
13        Ok(())
14    }
15
16    /// Duplicates a page at `page_index` and appends it to the end of the document.
17    pub fn duplicate_page(doc: &mut PDDocument, page_index: usize) -> PdfResult<()> {
18        let page = doc.get_page(page_index)?.clone();
19        doc.add_page(page);
20        Ok(())
21    }
22
23    /// Moves a page from `from_index` to `to_index`.
24    pub fn move_page(doc: &mut PDDocument, from_index: usize, to_index: usize) -> PdfResult<()> {
25        let total = doc.page_count();
26        if from_index >= total || to_index >= total {
27            return Err(PdfError::PageOperation(format!(
28                "Invalid move page bounds: from {from_index} to {to_index}, total {total}"
29            )));
30        }
31
32        let page = doc.pages.remove(from_index);
33        doc.pages.insert(to_index, page);
34        doc.sync();
35        Ok(())
36    }
37}