Skip to content

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

M5: Custom stamps: create from a PDF page or an image under a category and name, kept in the stamp library, placed at natural size; stamp_custom tool

Brandon Thomase8bc0db811b5
diff --git a/crates/annot/src/appearance.rs b/crates/annot/src/appearance.rs
index eff0c7711..0b097a9b7 100644
--- a/crates/annot/src/appearance.rs
+++ b/crates/annot/src/appearance.rs
@@ -401,6 +401,23 @@ pub fn build(d: &Dict) -> Option<Stream> {
}
}
b"Stamp" => {
+ // A custom stamp: its picture (an image, or a form mapped to /PCPictureSize) fills
+ // the rectangle.
+ if let Some(pic) = d.get(b"PCPicture").and_then(Object::as_ref) {
+ let [x0, y0, x1, y1] = rect;
+ let (w, h) = (x1 - x0, y1 - y0);
+ let place = if matches!(d.get(b"PCPictureImage"), Some(Object::Bool(true))) {
+ format!("{} 0 0 {} {} {} cm", n(w), n(h), n(x0), n(y0))
+ } else {
+ let size = nums(d, b"PCPictureSize").filter(|s| s.len() == 2 && s[0] > 0.0 && s[1] > 0.0)?;
+ format!("{} 0 0 {} {} {} cm", n(w / size[0]), n(h / size[1]), n(x0), n(y0))
+ };
+ c.push_str(&format!("q {place} /Pic Do Q\n"));
+ let mut xo = Dict::new();
+ xo.set(b"Pic".to_vec(), Object::Ref(pic));
+ res.set(b"XObject".to_vec(), Object::Dict(xo));
+ return Some(form(rect, c.as_bytes(), res));
+ }
// Only PrintCraft's own Fill & Sign marks are drawn here.
let name = d.name(b"Name")?;
let col = stroke.unwrap_or([0.0; 3]);
diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rs
index c2186a9a2..a70cf26de 100644
--- a/crates/annot/src/lib.rs
+++ b/crates/annot/src/lib.rs
@@ -327,6 +327,15 @@ pub enum Shape {
stamp: StampKind,
by: Option<String>,
},
+ /// A custom stamp: a picture already in the document (an image XObject, or a form XObject
+ /// whose `/Matrix` maps it to `size` points) filling `rect`, named `name`.
+ CustomStamp {
+ rect: [f64; 4],
+ name: String,
+ picture: ObjRef,
+ image: bool,
+ size: (f64, f64),
+ },
/// A redaction mark (§12.5.6.23) over quadrilaterals (text) or one rectangle as a quad
/// (areas, pages). `overlay` is the text shown on the box once applied, drawn with `look`.
Redact {
@@ -408,7 +417,7 @@ impl Shape {
Shape::Line { .. } => "Line",
Shape::Ink { .. } | Shape::Signature { .. } => "Ink",
Shape::TextBox { .. } | Shape::Typewriter { .. } | Shape::Callout { .. } => "FreeText",
- Shape::Mark { .. } | Shape::Stamp { .. } => "Stamp",
+ Shape::Mark { .. } | Shape::Stamp { .. } | Shape::CustomStamp { .. } => "Stamp",
Shape::Redact { .. } => "Redact",
Shape::Polygon { .. } => "Polygon",
Shape::PolyLine { .. } => "PolyLine",
@@ -513,6 +522,7 @@ impl Style {
Shape::Mark { .. } => ([0.0, 0.0, 0.0], 1.5),
Shape::Signature { .. } => ([0.0, 0.0, 0.0], 1.5),
Shape::Stamp { stamp, .. } => (stamp.color(), 2.0),
+ Shape::CustomStamp { .. } => ([0.0, 0.0, 0.0], 0.0),
// Red outline while marked; a black box once applied.
Shape::Redact { .. } => return Self { color: [0.89, 0.13, 0.13], opacity: 1.0, width: 1.0, fill: Some([0.0, 0.0, 0.0]) },
};
@@ -704,6 +714,7 @@ fn rect_for(shape: &Shape, style: &Style) -> Result<[f64; 4], AnnotError> {
| Shape::TextBox { rect, .. }
| Shape::Typewriter { rect, .. }
| Shape::Stamp { rect, .. }
+ | Shape::CustomStamp { rect, .. }
| Shape::Mark { rect, .. } => {
let r = normalize(*rect);
if !finite(rect) || r[2] - r[0] < 1.0 || r[3] - r[1] < 1.0 {
@@ -799,6 +810,7 @@ fn subject(shape: &Shape) -> &'static str {
StampGroup::SignHere => "Sign Here",
StampGroup::StandardBusiness => "Stamp",
},
+ Shape::CustomStamp { .. } => "Stamp",
Shape::Polygon { cloud: true, .. } => "Cloud",
Shape::Polygon { .. } => "Polygon",
Shape::PolyLine { .. } => "Polygonal Line",
@@ -904,6 +916,13 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
d.set(b"PCByLine".to_vec(), PdfString::text(b));
}
}
+ Shape::CustomStamp { name, picture, image, size, .. } => {
+ let clean: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
+ d.set(b"Name".to_vec(), Object::name(&format!("PCCustom{clean}")));
+ d.set(b"PCPicture".to_vec(), Object::Ref(*picture));
+ d.set(b"PCPictureImage".to_vec(), Object::Bool(*image));
+ d.set(b"PCPictureSize".to_vec(), num_array(&[size.0, size.1]));
+ }
Shape::Ink { strokes } | Shape::Signature { strokes } => {
d.set(b"C".to_vec(), rgb(style.color));
let list = strokes.iter().filter(|s| !s.is_empty()).map(|s| num_array(&s.concat())).collect();
diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rs
index cb3b7703c..eb338ddfd 100644
--- a/crates/automation/src/comments.rs
+++ b/crates/automation/src/comments.rs
@@ -444,6 +444,33 @@ impl Automation {
}
}
+impl Automation {
+ /// A custom stamp: a picture file (PDF page or image) centred at `at`, at its natural size
+ /// (at most 200 pt) or `width` points wide.
+ pub(crate) fn stamp_custom(&mut self, a: &Args) -> Result<Value> {
+ let page = self.page(a)?;
+ let info = self.doc(a)?.info.pages[page].clone();
+ let path = self.resolve(a.str("path")?, false)?;
+ let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ let name = a.opt_str("name")?.map(str::to_owned).unwrap_or_else(|| file.rsplit_once('.').map_or(file.clone(), |(s, _)| s.to_owned()));
+ let [x, y] = a.need::<2>("at", "a stamp (its centre)")?;
+ let [ux, uy] = to_user(&info, x, y);
+ let edit = Edit::AddCustomStamp {
+ page,
+ rect: [ux, uy, ux, uy],
+ name,
+ file: printcraft_engine::MarkFile {
+ name: file,
+ bytes: std::sync::Arc::new(bytes),
+ page: a.opt_int("file_page")?.unwrap_or(1).max(1) as usize - 1,
+ },
+ author: a.opt_str("author")?.unwrap_or(DEFAULT_AUTHOR).to_string(),
+ };
+ self.apply(a, edit)
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index f24e55a17..c5dd985ca 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -323,6 +323,7 @@ impl Automation {
"fill_sign_add" => self.fill_sign_add(&a)?,
"comment_list" => self.comment_list(&a)?,
"comment_add" => self.comment_add(&a)?,
+ "stamp_custom" => self.stamp_custom(&a)?,
"comment_reply" => self.comment_reply(&a)?,
"comment_set_status" => self.comment_set_status(&a)?,
"sign_list" => self.sign_list(&a)?,
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index b0ec57451..836e935db 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -251,6 +251,20 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc", "page", "type", "rect"],
)),
+ t("stamp_custom", "Add a custom stamp", "Stamp a picture: a PDF page (file_page, default 1) or an image file, centred at at [x, y] (points from the top-left of the displayed page) at its natural size, at most 200 pt. name labels it (default: the file name). Undoable.")
+ .cmd("comment.stamp")
+ .with(schema(
+ json!({
+ "doc": doc(),
+ "page": { "type": "integer", "minimum": 1 },
+ "path": { "type": "string" },
+ "at": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
+ "file_page": { "type": "integer", "minimum": 1 },
+ "name": { "type": "string" },
+ "author": { "type": "string" },
+ }),
+ &["doc", "page", "path", "at"],
+ )),
t("form_set_image", "Set an image field's picture", "Show an image file (PNG, JPEG, TIFF, GIF or BMP) in an image field or button, scaled to fit and centred (what clicking an image field does). Undoable.")
.with(schema(json!({ "doc": doc(), "field": { "type": "string" }, "path": { "type": "string" } }), &["doc", "field", "path"])),
t(
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index 05f0c6091..ae8f2fe67 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -935,6 +935,14 @@ fn stamps_through_tools() {
a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "stamp", "stamp": "nonsense", "at": [1, 1] })),
Err(ToolError::InvalidArgs(_))
));
+ // A custom stamp from another PDF's page.
+ ok(&mut a, "stamp_custom", json!({ "doc": doc, "page": 2, "path": "b.pdf", "file_page": 2, "at": [100, 150], "name": "Logo" }));
+ let list = ok(&mut a, "comment_list", json!({ "doc": doc }));
+ assert_eq!(list["count"], 4, "{list}");
+ // Its "Page 2" is drawn over the page's own.
+ assert_eq!(page_text(&mut a, doc)[1].matches('2').count(), 2);
+ assert_eq!(ok(&mut a, "edit_undo", json!({ "doc": doc }))["undone"], "Add stamp");
+ assert!(matches!(a.call("stamp_custom", &json!({ "doc": doc, "page": 1, "path": "nope.png", "at": [1, 1] })), Err(ToolError::Failed(_))));
}
#[test]
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 0cf73ec91..b01726103 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -85,6 +85,7 @@ fn scope_of(edit: &Edit) -> Scope {
// A file attachment also changes the Attachments list.
Edit::AddAnnotation(a) if matches!(a.shape, Shape::Attachment { .. }) => Scope::Full,
Edit::AddAnnotation(_)
+ | Edit::AddCustomStamp { .. }
| Edit::DeleteAnnotation { .. }
| Edit::SetAnnotationContents { .. }
| Edit::ReplyToAnnotation { .. }
@@ -563,6 +564,15 @@ pub enum Edit {
},
/// Add a comment (sticky note, highlight, shape, drawing, text box…).
AddAnnotation(NewAnnotation),
+ /// A custom stamp from a picture file (a PDF page or an image) on `page`. A zero-size
+ /// `rect` is a point: the stamp is centred there at its natural size (at most 200 pt).
+ AddCustomStamp {
+ page: usize,
+ rect: [f64; 4],
+ name: String,
+ file: MarkFile,
+ author: String,
+ },
/// Delete the comment at `index` in the page's `/Annots`, with its pop-up and replies.
DeleteAnnotation {
page: usize,
@@ -825,6 +835,7 @@ impl Edit {
Edit::SetBookmarkPage { .. } => "Set bookmark destination".into(),
Edit::NumberPages { .. } => "Number pages".into(),
Edit::AddAnnotation(a) => format!("Add {}", annotation_noun(&a.shape)),
+ Edit::AddCustomStamp { .. } => "Add stamp".into(),
Edit::DeleteAnnotation { .. } => "Delete comment".into(),
Edit::SetAnnotationContents { .. } => "Edit comment".into(),
Edit::ReplyToAnnotation { .. } => "Reply".into(),
@@ -902,7 +913,7 @@ fn annotation_noun(s: &Shape) -> &'static str {
Shape::Mark { mark: FillMark::Line, .. } => "line",
Shape::Signature { .. } => "signature",
Shape::Redact { .. } => "redaction mark",
- Shape::Stamp { .. } => "stamp",
+ Shape::Stamp { .. } | Shape::CustomStamp { .. } => "stamp",
Shape::Polygon { cloud: true, .. } => "cloud",
Shape::Polygon { .. } => "polygon",
Shape::PolyLine { .. } => "connected lines",
@@ -944,6 +955,7 @@ fn check_permission(edit: &Edit, p: &printcraft_cos::Permissions) -> Result<(),
}
}
Edit::AddAnnotation(_)
+ | Edit::AddCustomStamp { .. }
| Edit::DeleteAnnotation { .. }
| Edit::SetAnnotationContents { .. }
| Edit::ReplyToAnnotation { .. }
@@ -1111,6 +1123,21 @@ fn run_edit(doc: &mut printcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -
Edit::AddAnnotation(a) => {
printcraft_annot::add_annotation(doc, a, &cx.meta())?;
}
+ Edit::AddCustomStamp { page, rect, name, file, author } => {
+ let src = mark_source(doc, file)?;
+ let (sw, sh) = (src.size.0.max(1.0), src.size.1.max(1.0));
+ let rect = if (rect[2] - rect[0]).abs() < 1.0 || (rect[3] - rect[1]).abs() < 1.0 {
+ let k = (200.0 / sw.max(sh)).min(1.0);
+ let (w, h) = (sw * k, sh * k);
+ [rect[0] - w / 2.0, rect[1] - h / 2.0, rect[0] + w / 2.0, rect[1] + h / 2.0]
+ } else {
+ *rect
+ };
+ let shape = Shape::CustomStamp { rect, name: name.clone(), picture: src.xobject, image: src.image, size: (sw, sh) };
+ let style = printcraft_annot::Style::default_for(&shape);
+ let new = NewAnnotation { page: *page, shape, style, contents: name.clone(), author: author.clone() };
+ printcraft_annot::add_annotation(doc, &new, &cx.meta())?;
+ }
Edit::DeleteAnnotation { page, index } => printcraft_annot::delete_annotation(doc, *page, *index)?,
Edit::SetAnnotationContents { page, index, text } => printcraft_annot::set_contents(doc, *page, *index, text, &cx.meta())?,
Edit::ReplyToAnnotation { page, index, text, author } => {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 0f4042cbd..167f2ebe2 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -942,6 +942,7 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {
| QuickTool::Field(_)
| QuickTool::AddText
| QuickTool::Stamp(_)
+ | QuickTool::CustomStamp(_)
| QuickTool::Link
| QuickTool::SignArea { .. }
| QuickTool::MarqueeZoom
@@ -959,6 +960,10 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {
let today = app.session.today();
let by_line = app.session.stamp_by_line(&author);
let mut stamp_placed = false;
+ let custom_stamp = match app.quick_tool {
+ QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),
+ _ => None,
+ };
let mut open_signature = false;
let mut hover_text: Option<(Pos2, String)> = None;
let mut clicked_link: Option<LinkTarget> = None;
@@ -1124,6 +1129,26 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {
stamp_placed = true;
}
}
+ if let Some(cs) = custom_stamp.as_ref()
+ && allowed
+ && let Some(p) = ui.input(|inp| inp.pointer.hover_pos()).filter(|p| xf.rect.contains(*p))
+ {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
+ if resp.clicked() {
+ // Centred on the click at its natural size (the engine sizes it).
+ let (vx, vy) = xf.screen_to_view(p);
+ let u = info.pages[i].view_to_user(vx, vy);
+ let (x, y) = (u[0] as f64, u[1] as f64);
+ view.pending_edit = Some(printcraft_engine::Edit::AddCustomStamp {
+ page: i,
+ rect: [x, y, x, y],
+ name: cs.name.clone(),
+ file: printcraft_engine::MarkFile { name: cs.file.clone(), bytes: cs.data.clone(), page: cs.page },
+ author: author.clone(),
+ });
+ stamp_placed = true;
+ }
+ }
if let QuickTool::Fill(ft) = tool
&& allowed
{
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 5b6456cb2..3704e5c4a 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -546,6 +546,7 @@ impl Host for crate::PrintCraftApp {
crate::QuickTool::MarqueeZoom => "marquee-zoom".to_string(),
crate::QuickTool::Snapshot => "snapshot".to_string(),
crate::QuickTool::Stamp(k) => format!("stamp-{}", k.name().trim_start_matches("PC").to_ascii_lowercase()),
+ crate::QuickTool::CustomStamp(i) => format!("custom-stamp-{i}"),
crate::QuickTool::Fill(f) => format!("fill-{}", f.command().trim_start_matches("sign.fill.")),
crate::QuickTool::Field(f) => format!("field-{}", f.command().trim_start_matches("form.add.")),
crate::QuickTool::Comment(t) => t.command().trim_start_matches("comment.").to_string(),
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 517fdcea1..2e40de825 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -51,6 +51,7 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {
let mut open_revision: Option<usize> = None;
let mut a11y_now = false;
let mut combine_now = false;
+ let mut stamp_now = false;
let t = Tokens::get(ctx);
let mut close = false;
let mut next = dialog;
@@ -758,6 +759,12 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {
close = apply || cancel;
return;
}
+ Dialog::CreateStamp => {
+ let (save, cancel) = crate::stamps_ui::create_body(ui, app, &t);
+ stamp_now = save;
+ close = save || cancel;
+ return;
+ }
Dialog::Combine => {
ui.set_width(620.0);
let (go, cancel) = crate::combine_ui::body(ui, app, &t);
@@ -1123,6 +1130,9 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {
if let Some(n) = open_revision {
app.open_revision(n);
}
+ if stamp_now {
+ app.save_custom_stamp();
+ }
if combine_now {
app.combine_staged();
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index aae9459e3..65afc082b 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -20,6 +20,7 @@ mod export_ui;
mod marks_ui;
mod optimize_ui;
mod sign_ui;
+mod stamps_ui;
mod zoom_snap;
/// Header & footer / watermark / background dialog types (tests and automation).
pub mod marks {
@@ -110,6 +111,8 @@ pub enum QuickTool {
AddText,
/// Add a stamp: click to place this stamp.
Stamp(printcraft_engine::StampKind),
+ /// A custom stamp from the library (its index).
+ CustomStamp(usize),
/// Edit a PDF ▸ Link: draw link areas, select and edit links.
Link,
/// Use a certificate ▸ Digitally sign / Certify (visible): drag the signature's rectangle.
@@ -177,6 +180,8 @@ pub enum Dialog {
AccessibilityOptions,
/// Combine files: the files, their order and pages.
Combine,
+ /// Custom stamps ▸ Create.
+ CreateStamp,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -281,6 +286,9 @@ pub struct PrintCraftApp {
pub a11y_skipped: std::collections::BTreeSet<printcraft_engine::a11y::Rule>,
/// Combine files: the files staged so far.
pub combine_draft: Vec<combine_ui::CombineFile>,
+ /// The custom stamp library, and the stamp being created.
+ pub custom_stamps: Vec<stamps_ui::CustomStamp>,
+ pub stamp_draft: stamps_ui::StampDraft,
/// PDF Optimizer choices.
pub optimize_draft: OptimizeDraft,
/// Pages copied or cut in Organize Pages, ready to paste (into any document).
@@ -404,6 +412,8 @@ impl PrintCraftApp {
a11y: a11y_ui::A11yState::default(),
a11y_skipped: Default::default(),
combine_draft: Vec::new(),
+ custom_stamps: Vec::new(),
+ stamp_draft: Default::default(),
optimize_draft: OptimizeDraft::default(),
page_clipboard: None,
last_snapshot: None,
@@ -719,8 +729,15 @@ impl PrintCraftApp {
/// Serialize the user's persistent state (recent files, theme). Local only.
pub fn persist(&self) -> String {
let trusted: Vec<String> = self.session.trusted_certificates().iter().map(printcraft_engine::sign::x509::to_pem).collect();
- serde_json::json!({ "recent": self.recent, "theme": self.theme, "signature": self.signature, "digital_ids": self.digital_ids, "trusted": trusted })
- .to_string()
+ serde_json::json!({
+ "recent": self.recent,
+ "theme": self.theme,
+ "signature": self.signature,
+ "digital_ids": self.digital_ids,
+ "trusted": trusted,
+ "custom_stamps": stamps_ui::encode(&self.custom_stamps),
+ })
+ .to_string()
}
/// Restore state written by `persist`. Unknown or malformed data is ignored.
@@ -743,6 +760,7 @@ impl PrintCraftApp {
if let Ok(ids) = serde_json::from_value::<Vec<DigitalIdEntry>>(v["digital_ids"].clone()) {
self.digital_ids = ids;
}
+ self.custom_stamps = stamps_ui::decode(&v["custom_stamps"]);
if let Ok(pems) = serde_json::from_value::<Vec<String>>(v["trusted"].clone()) {
let certs = pems.iter().filter_map(|p| printcraft_engine::sign::x509::load_certificates(p.as_bytes()).ok()).flatten().collect();
self.session.set_trusted_certificates(certs);
@@ -890,6 +908,13 @@ impl PrintCraftApp {
"marquee-zoom" => QuickTool::MarqueeZoom,
"snapshot" => QuickTool::Snapshot,
"certify" => QuickTool::SignArea { certify: true },
+ custom if custom.starts_with("custom-stamp-") => {
+ let i: usize = custom[13..].parse().map_err(|_| format!("bad stamp {custom}"))?;
+ if i >= self.custom_stamps.len() {
+ return Err(format!("there are {} custom stamps", self.custom_stamps.len()));
+ }
+ QuickTool::CustomStamp(i)
+ }
stamp if stamp.starts_with("stamp-") => QuickTool::Stamp(
printcraft_engine::StampKind::ALL
.into_iter()
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 313694055..412bae679 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -266,6 +266,7 @@ fn stamp_palette(app: &mut PrintCraftApp, ui: &mut egui::Ui, t: &Tokens) {
}
}
}
+ crate::stamps_ui::palette_section(app, ui, t);
});
}
diff --git a/crates/ui-egui/src/stamps_ui.rs b/crates/ui-egui/src/stamps_ui.rs
new file mode 100644
index 000000000..da38b352e
--- /dev/null
+++ b/crates/ui-egui/src/stamps_ui.rs
@@ -0,0 +1,187 @@
+//! Custom stamps (Add a stamp ▸ Custom stamps ▸ Create): a PDF page or an image saved in the
+//! user's stamp library under a category and a name, then placed like any stamp.
+
+use std::sync::Arc;
+
+use egui::{Align, Layout};
+use serde::{Deserialize, Serialize};
+
+use crate::theme::{self, Tokens};
+use crate::{Dialog, PrintCraftApp, QuickTool, widgets};
+
+/// Stamp files larger than this aren't kept in the library (it lives in the app's settings).
+pub const MAX_STAMP_BYTES: usize = 4 << 20;
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct CustomStamp {
+ pub category: String,
+ pub name: String,
+ /// The source file's name (its extension tells images from PDFs).
+ pub file: String,
+ /// The page of a PDF (0-based).
+ #[serde(default)]
+ pub page: usize,
+ #[serde(with = "b64")]
+ pub data: Arc<Vec<u8>>,
+}
+
+mod b64 {
+ use std::sync::Arc;
+
+ use base64::Engine as _;
+ use serde::{Deserialize, Deserializer, Serializer};
+
+ pub fn serialize<S: Serializer>(v: &Arc<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
+ s.serialize_str(&base64::engine::general_purpose::STANDARD.encode(v.as_slice()))
+ }
+
+ pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Arc<Vec<u8>>, D::Error> {
+ let s = String::deserialize(d)?;
+ base64::engine::general_purpose::STANDARD.decode(s).map(Arc::new).map_err(serde::de::Error::custom)
+ }
+}
+
+/// The Create Custom Stamp dialog: the chosen file, its category and name.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct StampDraft {
+ pub file: String,
+ pub data: Arc<Vec<u8>>,
+ pub category: String,
+ pub name: String,
+}
+
+pub(crate) fn create_body(ui: &mut egui::Ui, app: &mut PrintCraftApp, t: &Tokens) -> (bool, bool) {
+ let categories: Vec<String> = {
+ let mut c: Vec<String> = app.custom_stamps.iter().map(|s| s.category.clone()).collect();
+ c.sort();
+ c.dedup();
+ c
+ };
+ let d = &mut app.stamp_draft;
+ ui.label(egui::RichText::new("Create Custom Stamp").font(theme::semibold(18.0)));
+ ui.add_space(8.0);
+ ui.label(egui::RichText::new(format!("From {}", d.file)).color(t.text_muted));
+ ui.add_space(8.0);
+ egui::Grid::new("stamp-create").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| {
+ let l = ui.label("Category:");
+ ui.horizontal(|ui| {
+ ui.add(egui::TextEdit::singleline(&mut d.category).desired_width(200.0).hint_text("e.g. My stamps")).labelled_by(l.id);
+ if !categories.is_empty() {
+ egui::ComboBox::from_id_salt("stamp-categories").selected_text("").width(24.0).show_ui(ui, |ui| {
+ for c in &categories {
+ if ui.selectable_label(d.category == *c, c).clicked() {
+ d.category = c.clone();
+ }
+ }
+ });
+ }
+ });
+ ui.end_row();
+ let l = ui.label("Name:");
+ ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(200.0)).labelled_by(l.id);
+ ui.end_row();
+ });
+ ui.add_space(12.0);
+ let ok = !d.category.trim().is_empty() && !d.name.trim().is_empty();
+ let (mut save, mut cancel) = (false, false);
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ if ui.add_enabled_ui(ok, |ui| widgets::pill_button(ui, "OK", true)).inner.clicked() {
+ save = true;
+ }
+ if widgets::pill_button(ui, "Cancel", false).clicked() {
+ cancel = true;
+ }
+ });
+ (save, cancel)
+}
+
+/// The Custom stamps section of the stamps palette.
+pub(crate) fn palette_section(app: &mut PrintCraftApp, ui: &mut egui::Ui, t: &Tokens) {
+ widgets::section_title(ui, "Custom");
+ let mut remove = None;
+ let mut categories: Vec<String> = app.custom_stamps.iter().map(|s| s.category.clone()).collect();
+ categories.sort();
+ categories.dedup();
+ for c in categories {
+ ui.label(egui::RichText::new(&c).small().color(t.text_muted));
+ for (i, s) in app.custom_stamps.iter().enumerate().filter(|(_, s)| s.category == c) {
+ let active = app.quick_tool == QuickTool::CustomStamp(i);
+ let resp = ui.add(egui::Button::selectable(active, s.name.as_str()).min_size(egui::vec2(ui.available_width(), 28.0)));
+ if resp.clicked() {
+ app.quick_tool = QuickTool::CustomStamp(i);
+ }
+ resp.context_menu(|ui| {
+ if ui.button("Delete stamp").clicked() {
+ remove = Some(i);
+ ui.close();
+ }
+ });
+ }
+ }
+ if let Some(i) = remove {
+ app.custom_stamps.remove(i);
+ app.quick_tool = QuickTool::Select;
+ }
+ ui.add_space(4.0);
+ if widgets::pill_button(ui, "Create custom stamp…", false).on_hover_text("From a PDF page or an image").clicked() {
+ app.pick_stamp_file();
+ }
+}
+
+impl PrintCraftApp {
+ /// Create ▸ choose a PDF or an image for a new custom stamp.
+ pub(crate) fn pick_stamp_file(&mut self) {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let picked = match self.save_override.clone() {
+ Some(p) if [".png", ".jpg", ".pdf"].iter().any(|e| p.ends_with(e)) => Some(std::path::PathBuf::from(p)),
+ Some(_) => None,
+ None => rfd::FileDialog::new()
+ .add_filter("PDF or image", &["pdf", "png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp"])
+ .set_title("Select a file for the stamp")
+ .pick_file(),
+ };
+ let Some(path) = picked else { return };
+ match std::fs::read(&path) {
+ Ok(bytes) => {
+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ self.start_custom_stamp(name, bytes);
+ }
+ Err(e) => self.notify(format!("Couldn't read {}: {e}", path.display())),
+ }
+ }
+ #[cfg(target_arch = "wasm32")]
+ self.notify("Custom stamps arrive on the web with file pickers for images");
+ }
+
+ /// Open the Create Custom Stamp dialog for a file.
+ pub fn start_custom_stamp(&mut self, file: String, bytes: Vec<u8>) {
+ if bytes.len() > MAX_STAMP_BYTES {
+ self.notify(format!("{file} is too large for a stamp (at most {} MB)", MAX_STAMP_BYTES >> 20));
+ return;
+ }
+ let name = file.rsplit_once('.').map_or(file.as_str(), |(s, _)| s).to_string();
+ let category = self.custom_stamps.last().map(|s| s.category.clone()).unwrap_or_else(|| "My stamps".into());
+ self.stamp_draft = crate::stamps_ui::StampDraft { file, data: Arc::new(bytes), category, name };
+ self.dialog = Some(Dialog::CreateStamp);
+ }
+
+ /// Save the dialog's stamp in the library and choose it.
+ pub(crate) fn save_custom_stamp(&mut self) {
+ let d = std::mem::take(&mut self.stamp_draft);
+ self.custom_stamps.push(CustomStamp { category: d.category.trim().into(), name: d.name.trim().into(), file: d.file, page: 0, data: d.data });
+ self.quick_tool = QuickTool::CustomStamp(self.custom_stamps.len() - 1);
+ }
+}
+
+/// The custom stamps for `persist` (kept small: base64 of each file).
+pub(crate) fn encode(stamps: &[CustomStamp]) -> serde_json::Value {
+ serde_json::to_value(stamps).unwrap_or_default()
+}
+
+/// Read stamps back; malformed entries are dropped.
+pub(crate) fn decode(v: &serde_json::Value) -> Vec<CustomStamp> {
+ v.as_array()
+ .map(|a| a.iter().filter_map(|x| serde_json::from_value::<CustomStamp>(x.clone()).ok()).filter(|s| s.data.len() <= MAX_STAMP_BYTES).collect())
+ .unwrap_or_default()
+}
diff --git a/crates/ui-egui/tests/stamps.rs b/crates/ui-egui/tests/stamps.rs
index daafe1ba7..6fbe076d1 100644
--- a/crates/ui-egui/tests/stamps.rs
+++ b/crates/ui-egui/tests/stamps.rs
@@ -42,3 +42,54 @@ fn choosing_and_placing_stamps() {
h.render().unwrap().save(format!("{dir}/stamps.png")).unwrap();
}
}
+
+#[test]
+fn creating_placing_and_keeping_custom_stamps() {
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
+ let mut app = PrintCraftApp::new();
+ app.open_bytes("form.pdf", None, include_bytes!("data/form.pdf").to_vec()).unwrap();
+ app.set_option("zoom", "150").unwrap();
+ app
+ });
+ h.run_steps(6);
+ assert!(h.state_mut().execute("comment.stamp"));
+ h.run_steps(2);
+ // An image becomes a stamp: Create ▸ category and name.
+ let mut png = Vec::new();
+ image::RgbImage::from_pixel(60, 20, image::Rgb([20, 120, 220])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
+ h.state_mut().start_custom_stamp("logo.png".into(), png);
+ h.run_steps(2);
+ h.get_by_label("Create Custom Stamp");
+ h.state_mut().stamp_draft.category = "Company".into();
+ h.run_steps(1);
+ h.get_by_label("OK").click();
+ h.run_steps(2);
+ assert_eq!(h.state().quick_tool, QuickTool::CustomStamp(0));
+ h.get_by_label("Company");
+ h.get_by_label("logo");
+ // Place it.
+ let p = {
+ let r = h.state().views[0].page_screen_rect(0).unwrap();
+ r.min + egui::vec2(r.width() * 0.5, r.height() * 0.85)
+ };
+ h.hover_at(p);
+ h.run_steps(1);
+ h.drag_at(p);
+ h.run_steps(1);
+ h.drop_at(p);
+ h.run_steps(4);
+ let s = h.state();
+ let doc = s.session.get(s.views[0].id).unwrap();
+ let stamps: Vec<_> = doc.info.annotations.iter().filter(|a| a.subtype == "Stamp").collect();
+ assert_eq!(stamps.len(), 1);
+ let r = stamps[0].rect;
+ assert!(((r[2] - r[0]) / (r[3] - r[1]) - 3.0).abs() < 0.05, "keeps the picture's shape: {r:?}");
+ assert_eq!(doc.can_undo(), Some("Add stamp"));
+ // The library is kept with the app's settings.
+ let saved = s.persist();
+ let mut again = PrintCraftApp::new();
+ again.restore(&saved);
+ assert_eq!(again.custom_stamps.len(), 1);
+ assert_eq!((again.custom_stamps[0].category.as_str(), again.custom_stamps[0].name.as_str()), ("Company", "logo"));
+ assert_eq!(again.custom_stamps[0].data, s.custom_stamps[0].data);
+}
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index dd5ade99d..cca9455c5 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -3995,11 +3995,11 @@ title = "Custom stamps from images or PDF pages"
area = "E"
tier = "P1"
milestone = "M5"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "shipped"
+commands = ["comment.stamp"]
+tools = ["stamp_custom"]
+evidence = ["crates/ui-egui/tests/stamps.rs::creating_placing_and_keeping_custom_stamps", "crates/automation/tests/automation.rs::stamps_through_tools"]
+notes = "Create custom stamp from a PDF page or an image (category and name), kept in the app's settings; placed at natural size (at most 200 pt) keeping its shape; resizable (appearance redrawn from /PCPicture); delete from the palette"
[[feature]]
id = "comment.stamps-manage"