Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
fix: a placed signature takes the colour you pick (#44)
Josh87a99813a90c
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex b339459..af558c5 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -2649,6 +2649,9 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->Edit::ResizeAnnotation { page, index, rect } => pdfcraft_annot::set_rect(doc, *page, *index, *rect, &cx.meta())?,Edit::StyleAnnotation { page, index, color, opacity, width, endings } => {pdfcraft_annot::set_style(doc, *page, *index, *color, *opacity, *width, endings.as_deref(), &cx.meta())?;+ if let Some(c) = color {+ recolor_signature_picture(doc, *page, *index, *c)?;+ }}Edit::FillAnnotation { page, index, fill } => pdfcraft_annot::set_fill(doc, *page, *index, *fill, &cx.meta())?,Edit::FontSizeAnnotation { page, index, size } => pdfcraft_annot::set_font_size(doc, *page, *index, *size, &cx.meta())?,@@ -5451,6 +5454,28 @@ fn fit_picture(rect: [f64; 4], w: f64, h: f64) -> [f64; 4] {}/// Bring a mark's picture into `doc`: a PDF page as a form XObject, or an image.+/// A Fill & Sign image signature or initials (0-based target) drawn in `color`. Its appearance+/// shows a picture of the ink, which `/C` doesn't change, so the picture is redrawn: the ink keeps+/// its shape (the picture's alpha) in the new colour. A picture with no transparency (a photo)+/// is left as it is, as are all other comments, whose appearance already draws `/C`.+fn recolor_signature_picture(doc: &mut pdfcraft_cos::Document, page: usize, index: usize, color: pdfcraft_annot::Rgb) -> Result<(), EditError> {+ let Some(picture) = pdfcraft_annot::signature_image(doc, page, index)? else { return Ok(()) };+ let (_, bytes) = pdfcraft_create::image_file(doc, picture).map_err(EditError::Source)?;+ let image = SignatureImage::from_bytes(&bytes).map_err(|e| EditError::Source(e.to_string()))?;+ if !image.has_transparency() {+ return Ok(());+ }+ // finite: set_style refuses any other colour+ let rgb = color.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);+ let inked = image.in_color(rgb).map_err(|e| EditError::Source(e.to_string()))?;+ // the new picture takes the old one's place, so the appearance and /PCPicture still find it+ let (fresh, _) = pdfcraft_create::image_xobject(doc, "signature.png", inked.bytes())?;+ let obj = doc.get(fresh);+ doc.set(picture, obj.as_ref().clone());+ doc.free(fresh);+ Ok(())+}+fn mark_source(doc: &mut pdfcraft_cos::Document, f: &MarkFile) -> Result<pdfcraft_edit::MarkSource, EditError> {let head = &f.bytes[..f.bytes.len().min(1024)];if head.windows(5).any(|w| w == b"%PDF-") {diff --git a/crates/engine/src/signature_image.rs b/crates/engine/src/signature_image.rsindex daff674..b1e94d2 100644--- a/crates/engine/src/signature_image.rs+++ b/crates/engine/src/signature_image.rs@@ -195,6 +195,24 @@ impl SignatureImage {pdfcraft_sign::Graphic::Image { width: side(self.size[0]), height: side(self.size[1]), rgba: self.rgba.clone() }}+ /// Whether some of the image is see-through: ink on a transparent background, not a photo.+ pub fn has_transparency(&self) -> bool {+ self.rgba.as_chunks::<4>().0.iter().any(|[.., a]| *a < u8::MAX)+ }++ /// The ink drawn in `rgb`: every pixel takes that colour and keeps its own alpha.+ pub fn in_color(&self, rgb: [u8; 3]) -> Result<Self, SignatureImageError> {+ let [w, h] = self.size;+ let mut rgba = self.rgba.as_ref().clone();+ for [r, g, b, _] in rgba.as_chunks_mut::<4>().0 {+ [*r, *g, *b] = rgb;+ }+ let image = image::RgbaImage::from_raw(w as u32, h as u32, rgba).ok_or(SignatureImageError::Size)?;+ let mut png = Cursor::new(Vec::new());+ DynamicImage::ImageRgba8(image).write_to(&mut png, ImageFormat::Png)?;+ Self::from_bytes(&png.into_inner())+ }+/// Make near-white paper transparent, keeping darker ink.pub fn remove_white_background(&self, cutoff: u8, feather: u8) -> Result<Self, SignatureImageError> {let [w, h] = self.size;diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex ee9dc47..3843883 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -3350,6 +3350,44 @@ fn flattening_fill_and_sign_keeps_other_comments_fields_and_undoes() {assert_eq!(again.get(id2).unwrap().form.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["email"]);}+/// The colour of a Fill & Sign image signature's picture, read back from the document: each+/// pixel's red, green, blue and alpha.+fn signature_pixels(s: &Session, id: DocId) -> Vec<u8> {+ let cos = &s.get(id).unwrap().editor.as_ref().unwrap().cos;+ let picture = pdfcraft_annot::signature_image(cos, 0, 0).unwrap().unwrap();+ let (_, bytes) = pdfcraft_create::image_file(cos, picture).unwrap();+ SignatureImage::from_bytes(&bytes).unwrap().rgba().to_vec()+}++/// A saved signature placed with Fill & Sign is a picture of the ink, so a new colour has to+/// redraw the picture: the ink keeps its shape (its alpha) in the new colour, and Undo brings the+/// old colour back.+#[test]+fn an_image_signature_takes_a_new_colour() {+ let (mut s, id) = session_with(1);+ let mut png = Vec::new();+ {+ let mut enc = png::Encoder::new(&mut png, 2, 1);+ enc.set_color(png::ColorType::Rgba);+ // dark ink and its soft edge+ enc.write_header().unwrap().write_image_data(&[20, 20, 20, 255, 20, 20, 20, 128]).unwrap();+ }+ let image = SignatureImage::from_bytes(&png).unwrap();+ let info = s.get(id).unwrap().info.pages[0].clone();+ s.apply(id, image.edit(0, &info, [20.0, 120.0], false, "Ada").unwrap()).unwrap();+ assert_eq!(signature_pixels(&s, id), [20, 20, 20, 255, 20, 20, 20, 128]);++ s.apply(id, Edit::StyleAnnotation { page: 0, index: 0, color: Some([0.0, 0.0, 1.0]), opacity: None, width: None, endings: None }).unwrap();+ assert_eq!(signature_pixels(&s, id), [0, 0, 255, 255, 0, 0, 255, 128]);+ let saved = s.save_bytes(id).unwrap();+ let mut again = Session::new();+ let id2 = again.open("saved.pdf", None, saved, None).unwrap();+ assert_eq!(signature_pixels(&again, id2), [0, 0, 255, 255, 0, 0, 255, 128], "the new colour is saved");++ s.undo(id).unwrap();+ assert_eq!(signature_pixels(&s, id), [20, 20, 20, 255, 20, 20, 20, 128]);+}+#[test]fn flattening_fill_and_sign_does_nothing_when_there_are_none() {let (mut s, id) = session_with(1);