Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Edit images: moving or resizing a clipped image moves its own clip too (#1022) (#1049)

MarekSpodBiedry1c18510b4a7f
diff --git a/crates/edit/src/images.rs b/crates/edit/src/images.rs
index c6c0cb5d9..134211bdd 100644
--- a/crates/edit/src/images.rs
+++ b/crates/edit/src/images.rs
@@ -248,6 +248,34 @@ pub fn turn_about_centre(rect: [f64; 4], quarters: i32, flip_h: bool, flip_v: bo
[a, b, c, d, cx - a * cx - c * cy, cy - b * cx - d * cy]
}
+/// For a `Do` at `op` that sits alone in `q re W n cm Do Q`: the index of the `re` and the `cm` matrix.
+/// That clip belongs to this image only, so it may move with it. A `cm` this move put before the
+/// `re` earlier (`q cm re W n cm Do Q`) keeps the pattern, so the image can be moved again.
+fn exclusive_clip(ops: &[Op], op: usize) -> Option<(usize, Matrix)> {
+ let at = op.checked_sub(4)?;
+ let mut q = at.checked_sub(1)?;
+ while ops.get(q)?.is("cm") {
+ q = q.checked_sub(1)?;
+ }
+ let ok = ops.get(q)?.is("q")
+ && ops.get(at)?.is("re")
+ && (ops.get(at + 1)?.is("W") || ops.get(at + 1)?.is("W*"))
+ && ops.get(at + 2)?.is("n")
+ && ops.get(at + 3)?.is("cm")
+ && ops.get(op + 1)?.is("Q");
+ if !ok {
+ return None;
+ }
+ Some((at, Matrix(ops.get(at + 3)?.nums::<6>()?)))
+}
+
+/// The `cm` to put before the clip so that user-space transform `t` also moves the clip:
+/// the clip is drawn in the CTM before the image's own `cm` (`cm` · that = `draw`).
+fn clip_matrix(draw: Matrix, cm: Matrix, t: Matrix) -> Option<Matrix> {
+ let outer = cm.invert()?.then(&draw);
+ Some(outer.then(&t).then(&outer.invert()?))
+}
+
/// Change image `index` (from [`page_images`]) on `page`.
pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &ImageChange) -> Result<(), EditError> {
let images = page_images(doc, page)?;
@@ -258,6 +286,7 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag
let mut ops = parse(&data).ops;
let original = ops.get(img.op).cloned().ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
let mut resources = None;
+ let mut clip_move = None;
let replacement: Vec<Op> = match change {
ImageChange::Delete => Vec::new(),
ImageChange::Transform(t) => {
@@ -271,7 +300,17 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag
if !m.0.iter().all(|v| v.is_finite()) {
return Err(EditError::Invalid("the image transform is too large".into()));
}
- vec![Op::new("q", vec![]), Op::new("cm", m.0.iter().map(|v| pdfcraft_content::num(*v)).collect()), original, Op::new("Q", vec![])]
+ // `q re W n cm Do Q` clips only this image: move the clip with it instead of leaving it behind.
+ if let Some((at, cm)) = exclusive_clip(&ops, img.op) {
+ if let Some(c) = clip_matrix(Matrix(img.draw_matrix), cm, Matrix(*t)).filter(|c| c.0.iter().all(|v| v.is_finite())) {
+ clip_move = Some((at, Op::new("cm", c.0.iter().map(|v| pdfcraft_content::num(*v)).collect())));
+ vec![original]
+ } else {
+ return Err(EditError::Invalid("the image transform is too large".into()));
+ }
+ } else {
+ vec![Op::new("q", vec![]), Op::new("cm", m.0.iter().map(|v| pdfcraft_content::num(*v)).collect()), original, Op::new("Q", vec![])]
+ }
}
ImageChange::Replace(r) => {
if img.is_form {
@@ -289,6 +328,9 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag
}
};
ops.splice(img.op..=img.op, replacement);
+ if let Some((at, cm)) = clip_move {
+ ops.insert(at, cm);
+ }
let mut dict = match &*doc.resolve(&obj) {
Object::Stream(s) => s.dict.clone(),
_ => Dict::new(),
@@ -339,7 +381,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
if !movement.0.iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
return Err(EditError::Invalid("the image move is too large".into()));
}
- plans.insert((image.stream, image.op), movement);
+ plans.insert((image.stream, image.op), (movement, placement, offset));
}
let mut data = Vec::with_capacity(all.len());
let mut inside_text = false;
@@ -355,8 +397,23 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
return Err(EditError::Invalid("an image inside a text object cannot be moved in a group".into()));
}
}
+ // Images alone in their own `q re W n cm Do Q` take the clip with them.
+ let mut clips = std::collections::BTreeMap::new();
+ for index in 0..ops.len() {
+ let Some(&(_, placement, offset)) = plans.get(&(stream, index)) else { continue };
+ let Some((at, cm)) = exclusive_clip(&ops, index) else { continue };
+ let translation = Matrix([1.0, 0.0, 0.0, 1.0, offset[0], offset[1]]);
+ let Some(c) = clip_matrix(placement, cm, translation).filter(|c| c.0.iter().all(|v| v.is_finite() && v.abs() <= 1e12)) else {
+ return Err(EditError::Invalid("the image move is too large".into()));
+ };
+ plans.remove(&(stream, index));
+ clips.insert((stream, at), c);
+ }
let changed = crate::text::splice(&pieces, &ops, |index| {
- let Some(matrix) = plans.remove(&(stream, index)) else { return (Vec::new(), true) };
+ if let Some(c) = clips.remove(&(stream, index)) {
+ return (vec![Op::new("cm", c.0.map(Object::Real).to_vec())], true);
+ }
+ let Some((matrix, _, _)) = plans.remove(&(stream, index)) else { return (Vec::new(), true) };
let original = ops.get(index).cloned().into_iter();
// Local translations can be tiny under a large CTM. Preserve their precision
// rather than rounding them to zero or amplifying an error on the page.
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs
index f6b5ab7c9..616929e72 100644
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@ -1023,7 +1023,10 @@ fn page_content_bytes(doc: &Document, page: usize) -> Vec<u8> {
/// A page drawing image XObject /Im0 at 100,100 size 200 × 100 (pixels 4 × 2).
fn image_page() -> Document {
- let content = "q 200 0 0 100 100 100 cm /Im0 Do Q BT /F1 12 Tf 72 700 Td (Caption) Tj ET";
+ image_page_with("q 200 0 0 100 100 100 cm /Im0 Do Q BT /F1 12 Tf 72 700 Td (Caption) Tj ET")
+}
+
+fn image_page_with(content: &str) -> Document {
let objs: Vec<String> = vec![
"<< /Type /Catalog /Pages 2 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
@@ -1047,6 +1050,49 @@ fn image_page() -> Document {
Document::open(Arc::new(out)).unwrap()
}
+/// The box of the first `re` on the page in user space, after the `cm`s before it.
+fn first_rect_in_user_space(doc: &Document) -> [f64; 4] {
+ let mut ctm = pdfcraft_content::Matrix::IDENTITY;
+ for op in pdfcraft_content::parse(&page_content_bytes(doc, 0)).ops {
+ if op.is("cm") {
+ ctm = pdfcraft_content::Matrix(op.nums::<6>().unwrap()).then(&ctm);
+ } else if op.is("re") {
+ let [x, y, w, h] = op.nums::<4>().unwrap();
+ return ctm.bbox([x, y, x + w, y + h]);
+ }
+ }
+ panic!("no clip rectangle");
+}
+
+#[test]
+fn moving_an_image_moves_its_own_clip_too() {
+ let content = "q 100 100 200 100 re W* n 200 0 0 100 100 100 cm /Im0 Do Q BT /F1 12 Tf 72 700 Td (Caption) Tj ET";
+ let target = [50.0, 400.0, 350.0, 600.0];
+ let mut doc = image_page_with(content);
+ let before = images::page_images(&doc, 0).unwrap()[0].rect;
+ images::change_image(&mut doc, 0, 0, &images::ImageChange::Transform(images::rect_to_rect(before, target))).unwrap();
+ let mut doc = reopen(&doc);
+ assert!(close(images::page_images(&doc, 0).unwrap()[0].rect, target));
+ assert!(close(first_rect_in_user_space(&doc), target), "{:?}", first_rect_in_user_space(&doc));
+ // A second edit still finds the clip, now behind the `cm` the first one put before it.
+ let moved = [80.0, 420.0, 380.0, 620.0];
+ images::change_image(&mut doc, 0, 0, &images::ImageChange::Transform(images::rect_to_rect(target, moved))).unwrap();
+ assert!(close(first_rect_in_user_space(&doc), moved));
+ images::translate_images(&mut doc, 0, &[0], [10.0, 0.0]).unwrap();
+ assert!(close(images::page_images(&doc, 0).unwrap()[0].rect, [90.0, 420.0, 390.0, 620.0]));
+ assert!(close(first_rect_in_user_space(&doc), [90.0, 420.0, 390.0, 620.0]));
+ // Moving it with the group move helper takes the clip along as well.
+ let mut doc = image_page_with(content);
+ images::translate_images(&mut doc, 0, &[0], [30.0, -20.0]).unwrap();
+ assert!(close(images::page_images(&doc, 0).unwrap()[0].rect, [130.0, 80.0, 330.0, 180.0]));
+ assert!(close(first_rect_in_user_space(&doc), [130.0, 80.0, 330.0, 180.0]));
+ // A clip shared with other drawing is left where it is.
+ let shared = "q 100 100 200 100 re W n q 200 0 0 100 100 100 cm /Im0 Do Q 0 0 10 10 re f Q";
+ let mut doc = image_page_with(shared);
+ images::change_image(&mut doc, 0, 0, &images::ImageChange::Transform(images::rect_to_rect(before, target))).unwrap();
+ assert!(close(first_rect_in_user_space(&doc), [100.0, 100.0, 300.0, 200.0]));
+}
+
fn close(a: [f64; 4], b: [f64; 4]) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6)
}
diff --git a/docs/editing-images.md b/docs/editing-images.md
index 86a01c724..fde18518f 100644
--- a/docs/editing-images.md
+++ b/docs/editing-images.md
@@ -3,7 +3,9 @@
In **Edit a PDF → Edit text and images**, click a figure to select it. Drag the selected
figure to move it, drag a corner to resize it proportionally, or press Delete to remove
that placement. The context menu also rotates or flips it. Changes support undo and
-survive saving/reopening.
+survive saving/reopening. An image painted inside its own rectangular clip
+(`q … re W n … cm Do Q`, as PowerPoint exports it) moves and resizes together with that
+clip; a clip shared with other content stays where it is.
PDF figures are not always bitmap images. Imported diagrams often use a **Form XObject**,
which packages text, vector paths, and nested images into one object. PdfCraft selects