//! Page operations (reorder, rotate, delete, insert blank, extract, split) with lopdf, in place, so the form, //! bookmarks and everything else of the document stay; merge with pdfium's page import; images → PDF with lopdf //! (a JPEG goes in as it is, without re-encoding); PDF → images with pdfium. use crate::{Engine, PdfError, lopdf_load, lopdf_save, reader::render_doc_page}; use image::{DynamicImage, GenericImageView}; use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary}; use serde::{Deserialize, Serialize}; use std::collections::HashSet; /// One page of the new order. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum PageSpec { /// Page `index` (0-based) of the document, turned by `rotate` degrees clockwise (a multiple of 90). Existing { index: usize, #[serde(default)] rotate: i32, }, /// A blank page of this size in points. Blank { width: f32, height: f32 }, } const INHERITABLE: [&[u8]; 4] = [b"Resources", b"MediaBox", b"CropBox", b"Rotate"]; /// Copies inherited attributes down onto each page, so pages can be moved freely. fn materialise_inherited(doc: &mut Document, pages: &[ObjectId]) { for &page in pages { for key in INHERITABLE { if doc.get_dictionary(page).map(|d| d.has(key)).unwrap_or(true) { continue; } let mut current = doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok()); let mut depth = 0; let mut value = None; while let Some(id) = current { depth += 1; if depth > 64 { break; } let Ok(d) = doc.get_dictionary(id) else { break }; if let Ok(v) = d.get(key) { value = Some(v.clone()); break; } current = d.get(b"Parent").ok().and_then(|p| p.as_reference().ok()); } if let (Some(v), Ok(d)) = (value, doc.get_dictionary_mut(page)) { d.set(key, v); } } } } fn pages_root(doc: &Document) -> Result { doc.catalog() .ok() .and_then(|c| c.get(b"Pages").ok()) .and_then(|p| p.as_reference().ok()) .ok_or_else(|| PdfError::Damaged("it has no page tree".into())) } /// Builds the new page order. Pages left out are deleted, together with their annotations and the form fields /// that only lived on them. pub fn reorganise(bytes: &[u8], password: Option<&str>, specs: &[PageSpec]) -> Result, PdfError> { let mut doc = lopdf_load(bytes, password)?; reorganise_doc(&mut doc, specs)?; doc.prune_objects(); lopdf_save(&mut doc) } pub(crate) fn reorganise_doc(doc: &mut Document, specs: &[PageSpec]) -> Result<(), PdfError> { if specs.is_empty() { return Err(PdfError::Invalid("A PDF needs at least one page.".into())); } let pages: Vec = doc.get_pages().values().copied().collect(); materialise_inherited(doc, &pages); let root = pages_root(doc)?; let mut used = HashSet::new(); let mut kids = Vec::new(); for spec in specs { match *spec { PageSpec::Existing { index, rotate } => { let &src = pages.get(index).ok_or(PdfError::NoSuchPage(index + 1))?; if rotate % 90 != 0 { return Err(PdfError::Invalid("Pages turn in steps of 90 degrees.".into())); } // The same page twice: the second is a shallow copy (its content and resources are shared). let id = if used.insert(src) { src } else { let copy = doc.get_dictionary(src).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); let mut copy = copy; copy.remove(b"Annots"); doc.add_object(copy) }; let d = doc.get_dictionary_mut(id).map_err(|e| PdfError::Damaged(e.to_string()))?; let current = d.get(b"Rotate").and_then(Object::as_i64).unwrap_or(0); d.set("Rotate", crate::geometry::normalise_rotate(current + rotate as i64) as i64); d.set("Parent", root); kids.push(Object::Reference(id)); } PageSpec::Blank { width, height } => { if !(width >= 3.0 && height >= 3.0 && width <= 14_400.0 && height <= 14_400.0) { return Err(PdfError::Invalid("A page must be between 3 and 14,400 points on each side.".into())); } let content = doc.add_object(Stream::new(dictionary! {}, Vec::new())); let id = doc.add_object(dictionary! { "Type" => "Page", "Parent" => root, "Contents" => content, "Resources" => dictionary! {}, "MediaBox" => vec![0.into(), 0.into(), Object::Real(width), Object::Real(height)], }); kids.push(Object::Reference(id)); } } } // Annotations of deleted pages, and the fields that only lived there. let mut removed = HashSet::new(); for p in pages.iter().filter(|p| !used.contains(*p)) { if let Ok(Object::Array(a)) = doc.get_dictionary(*p).and_then(|d| d.get(b"Annots")) { removed.extend(a.iter().filter_map(|o| o.as_reference().ok())); } } crate::redact::prune_form_pub(doc, &removed); // Deleted pages go even if a bookmark, a link or the struct tree still points at them (those links then lead // nowhere, which every viewer tolerates); so do their annotations. for p in pages.iter().filter(|p| !used.contains(*p)) { doc.objects.remove(p); } for a in &removed { doc.objects.remove(a); } let count = kids.len() as i64; let mut root_dict = doc.get_dictionary(root).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); for key in INHERITABLE { root_dict.remove(key); } root_dict.set("Kids", kids); root_dict.set("Count", count); root_dict.remove(b"Parent"); doc.objects.insert(root, Object::Dictionary(root_dict)); Ok(()) } /// One document per range; `ranges` are 0-based inclusive page index pairs. pub fn split(bytes: &[u8], password: Option<&str>, ranges: &[(usize, usize)]) -> Result>, PdfError> { let mut out = Vec::new(); for &(a, b) in ranges { if a > b { return Err(PdfError::Invalid(format!("The range {}–{} runs backwards.", a + 1, b + 1))); } let specs: Vec = (a..=b).map(|index| PageSpec::Existing { index, rotate: 0 }).collect(); out.push(reorganise(bytes, password, &specs)?); } Ok(out) } /// Parses "1-3, 5, 8-" style ranges (1-based, as the user types them) for a document of `pages` pages. pub fn parse_ranges(text: &str, pages: usize) -> Result, PdfError> { let bad = || PdfError::Invalid(format!("\"{text}\" is not a page range like 1-3, 5, 8-.")); let mut out = Vec::new(); for part in text.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) { let (a, b) = match part.split_once(['-', '–']) { Some((a, b)) => { let a: usize = if a.trim().is_empty() { 1 } else { a.trim().parse().map_err(|_| bad())? }; let b: usize = if b.trim().is_empty() { pages } else { b.trim().parse().map_err(|_| bad())? }; (a, b) } None => { let n: usize = part.parse().map_err(|_| bad())?; (n, n) } }; if a == 0 || b == 0 || a > pages || b > pages { return Err(PdfError::Invalid(format!("This PDF has pages 1 to {pages}; \"{part}\" is outside them."))); } if a > b { return Err(bad()); } out.push((a - 1, b - 1)); } if out.is_empty() { return Err(bad()); } Ok(out) } /// Merges documents in order. Each input is `(bytes, password)`. Form fields of merged documents keep their look /// but are no longer fillable (pdfium imports pages, not forms); bookmarks are not carried over. pub fn merge(engine: &Engine, inputs: &[(&[u8], Option<&str>)]) -> Result, PdfError> { if inputs.len() < 2 { return Err(PdfError::Invalid("Choose at least two PDFs to merge.".into())); } let mut target = engine.new_document()?; for (i, (bytes, password)) in inputs.iter().enumerate() { let source = engine.open(bytes, *password).map_err(|e| match e { PdfError::NeedsPassword => PdfError::Invalid(format!("PDF number {} needs its password first.", i + 1)), other => other, })?; target.pages_mut().append(&source).map_err(PdfError::from_pdfium)?; } crate::engine::pdfium_save(&target) } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PageFit { /// Each page is the image's own size (at 96 dpi, or the image's resolution if it has one). Image, /// A4 portrait or landscape (whichever suits the image), with a margin. A4, Letter, } /// One page per image. JPEGs are embedded as they are (no quality loss); other images are stored losslessly. pub fn images_to_pdf(images: &[(Vec, DynamicImage)], fit: PageFit, margin_pt: f32) -> Result, PdfError> { if images.is_empty() { return Err(PdfError::Invalid("Choose at least one image.".into())); } let mut doc = Document::with_version("1.7"); let pages_id = doc.new_object_id(); let mut kids = Vec::new(); for (bytes, img) in images { let (w, h) = img.dimensions(); let is_jpeg = bytes.starts_with(&[0xFF, 0xD8, 0xFF]); let image_id = if is_jpeg && matches!(img.color().channel_count(), 1 | 3) { let cs = if img.color().channel_count() == 1 { "DeviceGray" } else { "DeviceRGB" }; let mut s = Stream::new( dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, "ColorSpace" => cs, "BitsPerComponent" => 8, "Filter" => "DCTDecode"}, bytes.clone(), ); s.allows_compression = false; doc.add_object(s) } else { let rgba = img.to_rgba8(); let has_alpha = rgba.pixels().any(|p| p.0[3] != 255); let rgb: Vec = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect(); let mut dict = dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8}; if has_alpha { let alpha: Vec = rgba.pixels().map(|p| p.0[3]).collect(); let mut smask = Stream::new( dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8}, alpha, ); let _ = smask.compress(); dict.set("SMask", doc.add_object(smask)); } let mut s = Stream::new(dict, rgb); let _ = s.compress(); doc.add_object(s) }; let (iw, ih) = (w as f32 * 0.75, h as f32 * 0.75); let (pw, ph) = match fit { PageFit::Image => (iw, ih), PageFit::A4 | PageFit::Letter => { let (a, b) = if fit == PageFit::A4 { (595.28, 841.89) } else { (612.0, 792.0) }; if w > h { (b, a) } else { (a, b) } } }; let margin = if fit == PageFit::Image { 0.0 } else { margin_pt.clamp(0.0, pw.min(ph) / 3.0) }; let scale = ((pw - 2.0 * margin) / iw).min((ph - 2.0 * margin) / ih).min(if fit == PageFit::Image { 1.0 } else { f32::MAX }); let (dw, dh) = (iw * scale, ih * scale); let (x, y) = ((pw - dw) / 2.0, (ph - dh) / 2.0); let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q").into_bytes(); let content_id = doc.add_object(Stream::new(dictionary! {}, content)); let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id, "Contents" => content_id, "MediaBox" => vec![0.into(), 0.into(), Object::Real(pw), Object::Real(ph)], "Resources" => dictionary! {"XObject" => Dictionary::from_iter([(b"Im0".to_vec(), Object::Reference(image_id))])}, }); kids.push(Object::Reference(page)); } let count = kids.len() as i64; doc.objects.insert(pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count})); let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id}); doc.trailer.set("Root", catalog); lopdf_save(&mut doc) } /// Renders the chosen pages (0-based) at `dpi`. pub fn pages_to_images( engine: &Engine, bytes: &[u8], password: Option<&str>, pages: &[usize], dpi: u32, ) -> Result, PdfError> { let doc = engine.open(bytes, password)?; let mut out = Vec::new(); for &i in pages { let page = doc.pages().get(i as i32).map_err(|_| PdfError::NoSuchPage(i + 1))?; let width = (page.width().value * dpi.clamp(36, 600) as f32 / 72.0).round().max(1.0) as u32; drop(page); out.push(render_doc_page(&doc, i, width, true)?); } Ok(out) }