PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge PR #1679: fix(sign): render Unicode characters in visible signatures using bundled Inter font
aiongge42ccbb440f5
diff --cc crates/sign/src/pdf.rsindex 78f2ad55d,b5808cabf..bfed0d7b1--- a/crates/sign/src/pdf.rs+++ b/crates/sign/src/pdf.rs@@@ -2063,17 -1943,18 +2063,19 @@@ pub fn display_date(pdf: &str) -> Strin}/// The visible signature: the signer's name large on the left, or the graphic in its place, and- /// the details on the right (Acrobat's standard layout), in Helvetica. A graphic with no details- /// beside it fills the box. An error, before anything is drawn, when a detail it writes in- /// Helvetica (the signer's name, the certificate's subject, the reason or the location) has a- /// character Helvetica can't draw: signing invisibly, or leaving that part out, still works. A- /// graphic doesn't change this: the name it replaces on the left is still among the details.- /// A label that is drawn ([`AppearanceLabels`], the caller's words) is refused the same way.-/// the details on the right (Acrobat's standard layout), in Helvetica or the bundled Inter font-/// when non-Western-European characters are needed. A graphic with no details beside it fills the-/// box. An error, before anything is drawn, when a detail it writes has a character the fonts-/// can't draw: signing invisibly, or leaving that part out, still works. A graphic doesn't change-/// this: the name it replaces on the left is still among the details.++/// the details on the right (Acrobat's standard layout), in Helvetica, or in the bundled Inter++/// font when a detail needs characters beyond Western European. A graphic with no details beside++/// it fills the box. An error, before anything is drawn, when a detail it writes (the signer's++/// name, the certificate's subject, the reason or the location) has a character neither font can++/// draw: signing invisibly, or leaving that part out, still works. A graphic doesn't change this:++/// the name it replaces on the left is still among the details. A label that is drawn++/// ([`AppearanceLabels`], the caller's words) must be drawable in Helvetica, and is refused otherwise.fn appearance(doc: &mut Document, rect: [f64; 4], name: &str, cert: &Certificate, opts: &SignOptions) -> Result<Stream, SignError> {- use pdfcraft_fonts::{first_undrawable, helvetica_width, literal, undrawable_message, win_ansi, wrap};+ use pdfcraft_fonts::{first_undrawable, helvetica_width, inter_width, literal, undrawable_message, win_ansi, wrap, wrap_with};let (w, h) = ((rect[2] - rect[0]).max(0.0), (rect[3] - rect[1]).max(0.0));let a = &opts.appearance;let dn = cert.subject.display();- let wording = &opts.appearance_labels;+ let mut needs_unicode = false;if w > 1.0 && h > 1.0 {let shown = [(a.name, "the signer's name", Some(name)),@@@ -2082,23 -1963,29 +2084,34 @@@(a.location, "the location", opts.location.as_deref()),];for (on, what, text) in shown {- if on && let Some(c) = text.and_then(first_undrawable) {- return Err(SignError::Unsupported(format!(- "{}; sign without a visible appearance, or leave {what} out of it",- undrawable_message(&format!("{what} of the visible signature"), c)- )));+ if on+ && let Some(s) = text+ && first_undrawable(s).is_some()+ {+ for c in s.chars() {+ if matches!(c, '\n' | '\r') {+ continue;+ }+ if !pdfcraft_fonts::embedding::covers(pdfcraft_fonts::INTER_REGULAR, &c.to_string()) {+ return Err(SignError::Unsupported(format!(+ "{}; sign without a visible appearance, or leave {what} out of it",+ undrawable_message(&format!("{what} of the visible signature"), c)+ )));+ }+ }+ needs_unicode = true;}}- if !needs_unicode {- let label_texts = [&wording.signed_by, &wording.distinguished_name, &wording.reason, &wording.location, &wording.date];- if label_texts.iter().any(|l| first_undrawable(l).is_some()) {- needs_unicode = true;- }+ // The labels are the caller's words (a translation), checked as the details are: only+ // those that are drawn, as each is drawn only beside its detail.+ let has = |v: Option<&str>| v.is_some_and(|v| !v.is_empty());+ let drawn = [a.name, a.distinguished_name, a.reason && has(opts.reason.as_deref()), a.location && has(opts.location.as_deref()), a.date];+ let mut labels = opts.appearance_labels.fields().into_iter().zip(drawn).filter(|&(_, on)| a.labels && on);+ if let Some((field, c)) = labels.find_map(|((field, text), _)| first_undrawable(text).map(|c| (field, c))) {+ return Err(SignError::Unsupported(format!(+ "{}; pass that label in Western European characters, or leave the labels out of the visible signature",+ undrawable_message(&format!("the {field} label of the visible signature"), c)+ )));}}let mut lines: Vec<String> = Vec::new();diff --cc crates/sign/tests/pdf.rsindex 08872527d,8cbebf37a..931a26a99--- a/crates/sign/tests/pdf.rs+++ b/crates/sign/tests/pdf.rs@@@ -1898,58 -1816,38 +1899,90 @@@ fn visible_appearance_text_helvetica_caassert_eq!(s.reason.as_deref(), Some("同意此文件"));}+/// The labels are the caller's words (a translation), so they are checked as the details are: a+/// label Helvetica can't draw is refused with the label and the character, never drawn as `?`.+/// Only labels that are drawn count: one whose detail is hidden, or empty, or with the labels+/// turned off or the signature invisible, signs. Labels it can draw are what the stamp says.+#[test]+fn appearance_labels_helvetica_cannot_draw_are_refused() {+ use pdfcraft_sign::{Appearance, AppearanceLabels};+ let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();+ assert_eq!(AppearanceLabels::default().first_undrawable(), None, "the English labels are drawable");+ let chinese = AppearanceLabels { signed_by: "数字签名者".into(), reason: "原因:".into(), ..AppearanceLabels::default() };+ assert_eq!(chinese.first_undrawable(), Some(("signed_by", '数')));+ let sign = |labels: AppearanceLabels, appearance: Appearance, o: SignOptions| {+ pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { appearance_labels: labels, appearance, ..o })+ };++ // The name is shown with its label (the default appearance): refused, saying which and what.+ let err = sign(chinese.clone(), Appearance::default(), opts()).unwrap_err();+ let m = err.to_string();+ assert!(matches!(err, SignError::Unsupported(_)), "{err:?}");+ assert!(m.contains("\"数\" (U+6570)") && m.contains("the signed_by label") && m.contains("leave the labels out"), "{m}");+ let russian_date = AppearanceLabels { date: "Дата: ".into(), ..AppearanceLabels::default() };+ let m = sign(russian_date.clone(), Appearance::default(), opts()).unwrap_err().to_string();+ assert!(m.contains("the date label") && m.contains("U+0414"), "{m}");+ let reason_only = AppearanceLabels { reason: "原因:".into(), ..AppearanceLabels::default() };+ let shown = Appearance { reason: true, ..Appearance::default() };+ assert!(sign(reason_only.clone(), shown.clone(), opts()).unwrap_err().to_string().contains("the reason label"));++ // Not drawn: the reason hidden, or empty; the labels off; the signature invisible.+ sign(reason_only.clone(), Appearance::default(), opts()).unwrap();+ sign(reason_only.clone(), shown.clone(), SignOptions { reason: None, ..opts() }).unwrap();+ sign(reason_only, shown, SignOptions { reason: Some(String::new()), ..opts() }).unwrap();+ sign(chinese.clone(), Appearance { labels: false, ..Appearance::default() }, opts()).unwrap();+ sign(russian_date, Appearance { date: false, ..Appearance::default() }, opts()).unwrap();+ sign(chinese, Appearance::default(), SignOptions { rect: None, ..opts() }).unwrap();++ // Labels Helvetica can draw are stamped as given, in place of the English ones.+ let german = AppearanceLabels {+ signed_by: "Digital signiert von".into(),+ distinguished_name: "DN: ".into(),+ reason: "Grund: ".into(),+ location: "Ort: ".into(),+ date: "Datum: ".into(),+ };+ let all = Appearance { reason: true, location: true, ..Appearance::default() };+ let signed = sign(german, all, opts()).unwrap();+ let (content, _) = appearance_of(&signed, "Signature1");+ for word in ["(Digital", "(Grund:", "(Ort:", "(Datum:"] {+ assert!(content.contains(word), "{word}: {content}");+ }+ assert!(!content.contains("Reason") && !content.contains("Date:") && !content.contains('?'), "{content}");+}++ /// A visible signature with Central European characters (č, ć, ž, š) embeds the bundled+ /// Inter font and draws them cleanly instead of refusing or writing `?`.+ #[test]+ fn visible_appearance_draws_central_european_characters_with_embedded_font() {+ let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();+ let name = Name::build("Luka Petravić", "Oddelek", "Podjetje d.o.o.", "[email protected]", "SI");+ let cert = Certificate::self_signed(&name, &id.key, Time::from_unix(1_700_000_000), 5, &[1]).unwrap();+ let luka_id = DigitalId { key: id.key, certificate: cert, chain: Vec::new(), friendly_name: None };+ let shown =+ pdfcraft_sign::Appearance { name: true, distinguished_name: true, reason: true, location: true, ..pdfcraft_sign::Appearance::default() };+ let sl = SignOptions {+ rect: Some([150.0, 20.0, 280.0, 70.0]),+ reason: Some("Podpisano s potrdilom".into()),+ location: Some("Ljubljana, Slovenija".into()),+ appearance: shown,+ ..opts()+ };+ let signed = pdfcraft_sign::sign(&open(&fixture()), &luka_id, &sl).unwrap();+ let (content, res) = appearance_of(&signed, "Signature1");+ // Verify that the appearance stream does not write `?` in place of non-WinAnsi characters.+ assert!(!content.contains('?'), "appearance content should not write '?' for Central European characters: {content}");+ // Verify an embedded TrueType font was added to the appearance resources.+ let fonts = res.get(b"Font").and_then(|o| o.as_dict()).unwrap();+ assert!(fonts.contains(b"PCFull0"), "appearance should reference the embedded font: {fonts:?}");+ // Verify signature validation still passes.+ let doc = open(&signed);+ let trust = TrustStore { certs: vec![luka_id.certificate.clone()] };+ let s = signatures(&doc, &signed, &trust).into_iter().find(|s| s.signed).unwrap();+ assert_eq!(s.status, Status::Valid);+ assert_eq!(s.reason.as_deref(), Some("Podpisano s potrdilom"));+ }+/// Every sentence this crate says about a signature is listed in `WORDINGS`, and every sentence on/// that list is one it still says: the details are written as `Detail::plain`/`Detail::of`, the/// sentences the modules that read a signature word for themselves are pushed as notes and quirks,