Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

fix: draw Turkish, Polish, Greek and Cyrillic text instead of ? (#21)

Joshab961ef853a0
diff --git a/crates/annot/README.md b/crates/annot/README.md
index 67285f8..5d8adb3 100644
--- a/crates/annot/README.md
+++ b/crates/annot/README.md
@@ -10,8 +10,11 @@ Comments (annotations), ISO 32000-2 §12.5. Layer L3, depends on `pdfcraft-cos`,
- **Appearance streams** (`appearance::build`) generated from the annotation dictionary, so new
and restyled comments look the same in every viewer. Highlights multiply (`/BM /Multiply`).
Note icons are PdfCraft's own drawings. Text boxes use standard Helvetica (WinAnsi), with
- line breaking by approximate Helvetica proportions (no font program is bundled). Text it can't
- draw (in a text box, callout, Fill & Sign text, measurement label or dynamic stamp's by-line;
+ line breaking by approximate Helvetica proportions (no font program is bundled); a text box,
+ callout or Fill & Sign text with letters WinAnsi can't hold but the bundled Inter can (Turkish,
+ Polish, Greek, Cyrillic, …) is drawn as Inter's outlines and measured by Inter
+ (`appearance::text_measure`). Text neither can draw (in a text box, callout, Fill & Sign text,
+ measurement label or dynamic stamp's by-line;
`appearance::undrawable_text`) is kept as typed and drawn as `?`, and the comment is marked with
the first such character (`pdfcraft_fonts::UNDRAWN_MARK`) so the engine reports the edit and
flattening refuses to make it permanent. Two refusals (`AnnotError::Undrawable`): a redaction
diff --git a/crates/annot/src/appearance.rs b/crates/annot/src/appearance.rs
index 1137cc6..301c9e7 100644
--- a/crates/annot/src/appearance.rs
+++ b/crates/annot/src/appearance.rs
@@ -8,12 +8,20 @@
//!
//! The note icons are PdfCraft's own drawings (AGENTS.md §1). Text boxes use the standard
//! Helvetica font with WinAnsi encoding; line breaking uses [`text_width`], an approximation of
-//! Helvetica's proportions by character class (no font program or metrics file is bundled).
+//! Helvetica's proportions by character class (no font program or metrics file is bundled). A text
+//! box whose text that encoding can't hold (Turkish ş, Polish ł, Greek, Cyrillic, …) is drawn as
+//! the outlines of the bundled Inter instead ([`pdfcraft_fonts::needs_inter`], [`text_measure`]).
use pdfcraft_cos::{Dict, Object, PdfString, Stream};
-use pdfcraft_fonts::{first_undrawable, literal, win_ansi};
+use pdfcraft_fonts::{first_undrawable, first_undrawable_inter, helvetica_width, inter_path, inter_width, literal, needs_inter, win_ansi, wrap_with};
pub use pdfcraft_fonts::{helvetica_width as text_width, wrap};
+/// How [`build`] measures the lines of a text box holding `text`: in Inter when it draws the box in
+/// Inter (text the standard fonts can't hold), else as Helvetica ([`text_width`]).
+pub fn text_measure(text: &str) -> fn(&str, f64) -> f64 {
+ if needs_inter(text) { inter_width } else { helvetica_width }
+}
+
use crate::{NOTE_SIZE, Rgb, n};
/// Length of an arrowhead for a line of width `w`.
@@ -266,13 +274,13 @@ pub(crate) fn picture_turn(d: &Dict) -> i64 {
/// The first text [`build`] would draw in the standard fonts (Helvetica, WinAnsiEncoding) that
/// they can't, which would come out as `?`: what it is (for the message) and the character. The
-/// text of a text box, callout or Fill & Sign text, a measurement's label, a dynamic stamp's
-/// "By …" line, and a redaction mark's overlay text (drawn when it is applied). `None` when all of
-/// it can be drawn.
+/// text of a text box, callout or Fill & Sign text (drawn in Inter when Inter has every such
+/// character), a measurement's label, a dynamic stamp's "By …" line, and a redaction mark's overlay
+/// text (drawn when it is applied). `None` when all of it can be drawn.
pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text);
let (what, text) = match d.name(b"Subtype")? {
- b"FreeText" => ("the comment's text", text(b"Contents")?),
+ b"FreeText" => return text(b"Contents").and_then(|t| first_undrawable_inter(&t)).map(|c| ("the comment's text", c)),
b"Line" | b"PolyLine" | b"Polygon" => ("the measurement label", text(b"PCMeasureValue")?),
b"Stamp" if matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) => ("the stamp's \"By\" line", text(b"PCByLine")?),
// Drawn in Helvetica when the redaction is applied: refused when it is marked.
@@ -697,32 +705,45 @@ pub fn build(d: &Dict) -> Option<Stream> {
let pad = 2.0 + bw;
let width = (rect[2] - rect[0] - 2.0 * pad).max(1.0);
let q = d.int(b"Q").unwrap_or(0);
- c.push_str(&format!(
- "{} {} {} {} re W n\nBT\n/Helv {} Tf\n{}",
- n(rect[0]),
- n(rect[1]),
- n(rect[2] - rect[0]),
- n(rect[3] - rect[1]),
- n(size),
- rg(text_color)
- ));
+ // Text the standard fonts can't hold is drawn as Inter's outlines, in the text colour.
+ let inter = needs_inter(&text);
+ let measure = text_measure(&text);
+ c.push_str(&format!("{} {} {} {} re W n\n", n(rect[0]), n(rect[1]), n(rect[2] - rect[0]), n(rect[3] - rect[1])));
+ if inter {
+ c.push_str(&rg(text_color));
+ } else {
+ c.push_str(&format!("BT\n/Helv {} Tf\n{}", n(size), rg(text_color)));
+ }
let mut out = c.into_bytes();
let mut y = rect[3] - pad - size * 0.9;
- for line in wrap(&text, size, width) {
+ for line in wrap_with(&text, size, width, measure) {
if y < rect[1] - size {
break;
}
- let lw = text_width(&line, size);
+ let lw = measure(&line, size);
let x = match q {
1 => rect[0] + pad + (width - lw) / 2.0,
2 => rect[2] - pad - lw,
_ => rect[0] + pad,
};
- out.extend(format!("1 0 0 1 {} {} Tm ", n(x), n(y)).bytes());
- out.extend(literal(&win_ansi(&line)));
- out.extend_from_slice(b" Tj\n");
+ if inter {
+ // A line of spaces has no outline, and `f` needs a path.
+ let path = inter_path(&line, size, x, y);
+ if !path.is_empty() {
+ out.extend(path.bytes());
+ out.extend_from_slice(b"f\n");
+ }
+ } else {
+ out.extend(format!("1 0 0 1 {} {} Tm ", n(x), n(y)).bytes());
+ out.extend(literal(&win_ansi(&line)));
+ out.extend_from_slice(b" Tj\n");
+ }
y -= size * 1.2;
}
+ if inter {
+ // No font: the text is paths.
+ return Some(form(full, &out, res));
+ }
out.extend_from_slice(b"ET\n");
let mut font = Dict::new();
font.set(b"Type".to_vec(), Object::name("Font"));
diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rs
index 1755cd7..75a1c44 100644
--- a/crates/annot/src/lib.rs
+++ b/crates/annot/src/lib.rs
@@ -1589,14 +1589,16 @@ fn fitted_box(doc: &Document, r: ObjRef, text: &str) -> Option<[f64; 4]> {
};
let (x0, top) = (tb[0].min(tb[2]), tb[1].max(tb[3]));
let w = tb[2] - tb[0];
+ // Measured the way the appearance lays it out (in Inter for text the standard fonts can't hold).
+ let measure = appearance::text_measure(text);
let w = if w.is_finite() && w >= 1.0 {
w
} else {
// No usable old width: fall back to the creation-time width (at most 300 pt).
- let longest = text.lines().map(|l| appearance::text_width(l, size)).fold(0.0, f64::max);
+ let longest = text.lines().map(|l| measure(l, size)).fold(0.0, f64::max);
(longest + 2.0 * pad + 4.0).clamp(40.0, 300.0)
};
- let lines = appearance::wrap(text, size, (w - 2.0 * pad).max(1.0)).len().max(1) as f64;
+ let lines = pdfcraft_fonts::wrap_with(text, size, (w - 2.0 * pad).max(1.0), measure).len().max(1) as f64;
Some([x0, top - lines * size * 1.2 - 2.0 * pad - 2.0, x0 + w, top])
}
diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rs
index 9c02d9e..a706748 100644
--- a/crates/annot/src/tests.rs
+++ b/crates/annot/src/tests.rs
@@ -1246,6 +1246,41 @@ fn comment_text_the_standard_fonts_cannot_draw_is_kept_and_marked() {
assert_eq!(text(&list(&doc, 0)[t], b"Contents"), "签名");
}
+/// Text box and Fill & Sign text beyond Western European (Turkish ş, Polish ł, Greek, Cyrillic) is
+/// drawn as the bundled Inter's outlines instead of `?`, so nothing is marked; the box is sized and
+/// wrapped by Inter's measure. Text Inter can't draw either is still drawn in Helvetica and marked.
+#[test]
+fn comment_text_beyond_western_european_is_drawn_in_inter() {
+ let mut doc = fixture();
+ let mark = |doc: &Document, i: usize| pdfcraft_fonts::undrawn_mark(&list(doc, 0)[i]);
+ let typed = Shape::Typewriter { rect: [100.0, 700.0, 300.0, 716.0], font_size: 11.0 };
+ let f = add_annotation(
+ &mut doc,
+ &NewAnnotation { page: 0, style: Style::default_for(&typed), shape: typed, contents: "Mustafa çokyaşar".into(), author: "Ada".into() },
+ &meta("x"),
+ )
+ .unwrap();
+ let ap = ap_content(&doc, &list(&doc, 0)[f]);
+ assert!(!ap.contains('?') && !ap.contains("Tj") && !ap.contains("/Helv"), "{ap}");
+ assert!(ap.contains(" c\n") && ap.contains("f\n"), "drawn as filled outlines: {ap}");
+ assert_eq!((text(&list(&doc, 0)[f], b"Contents").as_str(), mark(&doc, f)), ("Mustafa çokyaşar", None));
+ // A text box with Greek and Cyrillic, the same way; Western European text goes back to Helvetica.
+ let mut boxed = new(0, Shape::TextBox { rect: [100.0, 600.0, 300.0, 650.0], font_size: 12.0 });
+ boxed.contents = "Ελληνικά\nПривет".into();
+ let t = add_annotation(&mut doc, &boxed, &meta("t")).unwrap();
+ assert_eq!(mark(&doc, t), None);
+ assert!(!ap_content(&doc, &list(&doc, 0)[t]).contains("Tj"));
+ set_contents(&mut doc, 0, t, "Zürich", &meta("")).unwrap();
+ assert!(ap_content(&doc, &list(&doc, 0)[t]).contains("/Helv"));
+ // With a character Inter lacks too, Helvetica draws it all and the first `?` is marked.
+ set_contents(&mut doc, 0, t, "ş 中", &meta("")).unwrap();
+ assert_eq!(mark(&doc, t), Some('ş'));
+ // Measured as drawn: Inter's widths, not Helvetica's estimate.
+ let measure = appearance::text_measure("çokyaşar");
+ assert_eq!(measure("çokyaşar", 10.0), pdfcraft_fonts::inter_width("çokyaşar", 10.0));
+ assert_eq!(appearance::text_measure("Zürich")("Zürich", 10.0), appearance::text_width("Zürich", 10.0));
+}
+
/// Content edits rebuild the display copy on every commit but leave annotations alone: the
/// cached appearance is drawn once and reused after that, byte-identical.
#[test]
diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rs
index 2ea66d0..c3a5c53 100644
--- a/crates/automation/src/comments.rs
+++ b/crates/automation/src/comments.rs
@@ -509,7 +509,8 @@ impl Automation {
}
let size = 10.0;
let text_at = |t: &str| {
- let w = (pdfcraft_engine::annot_text::text_width(t, size) + 8.0).clamp(20.0, 600.0);
+ // Measured as the appearance draws it (in Inter when the standard fonts can't hold it).
+ let w = (pdfcraft_engine::annot_text::text_measure(t)(t, size) + 8.0).clamp(20.0, 600.0);
let h = size * 1.2 + 6.0;
Shape::Typewriter { rect: [at[0], at[1] - h, at[0] + w, at[1]], font_size: size }
};
diff --git a/crates/edit/src/added.rs b/crates/edit/src/added.rs
index 67b2059..4cc8705 100644
--- a/crates/edit/src/added.rs
+++ b/crates/edit/src/added.rs
@@ -12,7 +12,7 @@ use std::collections::{HashMap, HashSet};
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};
use pdfcraft_fonts::{
- GlyphError, GlyphOutline, ShapedCluster, ShapedScript, helvetica_width, literal, shape_arabic, shape_thai, shaped_glyph, win_ansi,
+ GlyphError, GlyphOutline, ShapedCluster, ShapedScript, helvetica_width, literal, shape_arabic, shape_inter, shape_thai, shaped_glyph, win_ansi,
};
use unicode_bidi::{Level, ParagraphBidiInfo};
@@ -224,6 +224,7 @@ pub fn lines(t: &AddedText) -> Vec<String> {
/// does).
fn wrapped(t: &AddedText) -> Vec<(String, bool)> {
let width = (t.rect[2] - t.rect[0]).max(t.size);
+ let inter = uses_inter(t);
let mut out = Vec::new();
for para in t.text.split('\n') {
let arabic = para.chars().any(is_arabic);
@@ -236,17 +237,18 @@ fn wrapped(t: &AddedText) -> Vec<(String, bool)> {
continue;
}
let rtl = arabic && unicode_bidi::get_base_direction(para) == unicode_bidi::Direction::Rtl;
+ // Inter text is measured as shaped, like Arabic and Thai.
+ let shaped = arabic || thai || inter;
// Arabic words are shaped one by one (joining stops at spaces), so a line's width is the
// sum of its words' and shaping stays linear in the paragraph's length. The space is the
// paragraph's; a space between Latin words is drawn in the item's font, a few hundredths
// of an em apart.
- let measure = |s: &str| if arabic || thai { shaped_width(t, s, rtl) } else { t.family.width(s, t.size, t.bold) };
+ let measure = |s: &str| if shaped { shaped_width(t, s, rtl) } else { t.family.width(s, t.size, t.bold) };
let space = measure(" ");
let (mut line, mut line_w) = (String::new(), 0.0);
for word in para.split(' ') {
let candidate = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
- let candidate_w =
- if arabic || thai { if line.is_empty() { measure(word) } else { line_w + space + measure(word) } } else { measure(&candidate) };
+ let candidate_w = if shaped { if line.is_empty() { measure(word) } else { line_w + space + measure(word) } } else { measure(&candidate) };
if !line.is_empty() && candidate_w > width {
out.push((std::mem::take(&mut line), rtl));
line = word.to_string();
@@ -294,15 +296,38 @@ fn is_thai(c: char) -> bool {
matches!(u32::from(c), 0x0E00..=0x0E7F)
}
+/// Whether the item's text other than Arabic and Thai is drawn in Inter: some of it is beyond
+/// WinAnsiEncoding (Turkish ş, Polish ł, Greek, Cyrillic, …) and Inter has all of that. All of it,
+/// not just those letters, so a word never mixes two fonts.
+fn uses_inter(t: &AddedText) -> bool {
+ let mut any = false;
+ for c in t.text.chars().filter(|c| !matches!(c, '\n' | '\r') && !is_arabic(*c) && !is_thai(*c) && !is_bidi_control(*c)) {
+ if pdfcraft_fonts::win_ansi_encodable(c) {
+ continue;
+ }
+ if !pdfcraft_fonts::inter_has(c) {
+ return false;
+ }
+ any = true;
+ }
+ any
+}
+
+/// The first character of `s` neither the standard fonts nor Inter can draw.
+fn first_undrawable_inter(s: &str) -> Option<char> {
+ s.chars().find(|c| !pdfcraft_fonts::win_ansi_encodable(*c) && !pdfcraft_fonts::inter_has(*c))
+}
+
/// Arabic letters, marks, digits and punctuation: an item with any of them is shaped with the
/// craft-fonts Arabic face.
fn is_arabic(c: char) -> bool {
matches!(u32::from(c), 0x0600..=0x06FF | 0x0750..=0x077F | 0x0870..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFC)
}
-/// The first character of `t` that would be drawn as `?`: outside WinAnsiEncoding and not drawn
-/// with the craft-fonts Arabic face (#125), or Arabic that the face can't draw (or that has no
-/// face to draw it). Page-content tools refuse such text; the Add-text editor keeps it open.
+/// The first character of `t` that would be drawn as `?`: outside WinAnsiEncoding, not in Inter
+/// ([`uses_inter`]) and not drawn with the craft-fonts Arabic face (#125), or Arabic that the face
+/// can't draw (or that has no face to draw it). Page-content tools refuse such text; the Add-text
+/// editor keeps it open.
pub fn first_undrawable(t: &AddedText) -> Option<char> {
if t.text.chars().any(is_thai) {
if let Some(c) = t.text.chars().find(|c| is_thai(*c) && !pdfcraft_fonts::thai_has(*c)) {
@@ -316,9 +341,9 @@ pub fn first_undrawable(t: &AddedText) -> Option<char> {
return Some(c);
}
if pdfcraft_fonts::document_arabic_font().is_none() || !t.text.chars().any(is_arabic) {
- // Drawn line by line in the item's standard font (`\n` splits lines). Without the face
- // that is also how `draw` redraws an existing item, so it's checked that way.
- return t.text.split('\n').find_map(pdfcraft_fonts::first_non_win_ansi);
+ // Drawn line by line in the item's standard font (`\n` splits lines), or all in Inter.
+ // Without the face that is also how `draw` redraws an existing item, so it's checked that way.
+ return t.text.split('\n').find_map(first_undrawable_inter);
}
// What `shaped_layout` leaves to the standard font, exactly as `draw_shaped` splits it.
wrapped(t).into_iter().find_map(|(line, rtl)| {
@@ -373,19 +398,23 @@ fn shaped_layout(t: &AddedText, line: &str, rtl: bool) -> Result<(Vec<Piece>, f6
let base = if rtl { Level::rtl() } else { Level::ltr() };
let info = ParagraphBidiInfo::new(line, Some(base));
let (levels, runs) = info.visual_runs(0..line.len());
+ let inter = uses_inter(t);
let mut pieces = Vec::new();
for run in runs {
let run_rtl = levels.get(run.start).is_some_and(Level::is_rtl);
// Runs lie on character boundaries; a missing slice is skipped, never a panic.
let Some(text) = line.get(run) else { continue };
// Arabic letters take the Arabic face; so do spaces and punctuation between them, which the
- // shaper then mirrors. Latin text (and what the face lacks) keeps the item's font.
+ // shaper then mirrors. Latin text (and what the face lacks) keeps the item's font, or takes
+ // Inter when the item has letters beyond WinAnsiEncoding ([`uses_inter`]).
let mut segments: Vec<(Option<ShapedScript>, String)> = Vec::new();
for c in text.chars().filter(|c| !is_bidi_control(*c)) {
let script = if is_thai(c) {
Some(ShapedScript::Thai)
} else if is_arabic(c) || (run_rtl && !c.is_alphanumeric() && pdfcraft_fonts::arabic_has(c)) {
Some(ShapedScript::Arabic)
+ } else if inter {
+ Some(ShapedScript::Inter)
} else {
None
};
@@ -402,6 +431,7 @@ fn shaped_layout(t: &AddedText, line: &str, rtl: bool) -> Result<(Vec<Piece>, f6
let shaped = match script {
ShapedScript::Arabic => shape_arabic(&s, run_rtl).map_err(|e| arabic_error(e, &s))?,
ShapedScript::Thai => shape_thai(&s).map_err(|e| thai_error(e, &s))?,
+ ShapedScript::Inter => shape_inter(&s, run_rtl).map_err(|e| inter_error(e, &s))?,
};
Piece::Shaped(shaped)
} else if run_rtl {
@@ -437,6 +467,13 @@ fn arabic_error(e: GlyphError, text: &str) -> EditError {
})
}
+fn inter_error(e: GlyphError, text: &str) -> EditError {
+ EditError::Invalid(match e {
+ GlyphError::NoFont | GlyphError::Missing => format!("the Inter font can't show \"{text}\""),
+ GlyphError::TooComplex => format!("the Inter glyphs for \"{text}\" are too complex"),
+ })
+}
+
fn thai_error(e: GlyphError, text: &str) -> EditError {
EditError::Invalid(match e {
GlyphError::NoFont => {
@@ -512,6 +549,7 @@ fn draw_laid_shaped(
entry.insert(outline(c.script, *id).map_err(|e| match c.script {
ShapedScript::Arabic => arabic_error(e, &c.text),
ShapedScript::Thai => thai_error(e, &c.text),
+ ShapedScript::Inter => inter_error(e, &c.text),
})?);
}
}
@@ -646,6 +684,7 @@ fn type3_shaped(doc: &mut Document, clusters: &[&ShapedCluster], outlines: &Hash
match script {
ShapedScript::Arabic => "Arabic",
ShapedScript::Thai => "Thai",
+ ShapedScript::Inter => "Inter",
},
|f| f.family,
),
@@ -697,7 +736,10 @@ fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing:
}
let mut fonts = Dict::new();
fonts.set(name.clone().into_bytes(), Object::Dict(font));
- if t.text.chars().any(is_thai) || (t.text.chars().any(is_arabic) && (pdfcraft_fonts::document_arabic_font().is_some() || !existing)) {
+ let arabic = t.text.chars().any(is_arabic);
+ let arabic_face = pdfcraft_fonts::document_arabic_font().is_some();
+ // Inter text is shaped too, unless Arabic in it is kept as `?` (an existing item, no face).
+ if t.text.chars().any(is_thai) || (arabic && (arabic_face || !existing)) || (uses_inter(t) && (arabic_face || !arabic)) {
draw_shaped(doc, t, taken, &mut fonts, &mut out)?;
res.set(b"Font".to_vec(), Object::Dict(fonts));
out.extend_from_slice(b"Q\n");
@@ -934,8 +976,12 @@ fn validate(c: &Content) -> Result<(), EditError> {
// Everything else in it is drawn in the standard font, so it still has to fit.
let undrawable = if t.text.chars().any(shaped_arabic) && pdfcraft_fonts::document_arabic_font().is_none() {
t.text.split('\n').find_map(|line| {
- line.chars()
- .find(|c| !shaped_arabic(*c) && !(is_thai(*c) && pdfcraft_fonts::thai_has(*c)) && !pdfcraft_fonts::win_ansi_encodable(*c))
+ line.chars().find(|c| {
+ !shaped_arabic(*c)
+ && !(is_thai(*c) && pdfcraft_fonts::thai_has(*c))
+ && !pdfcraft_fonts::win_ansi_encodable(*c)
+ && !pdfcraft_fonts::inter_has(*c)
+ })
})
} else {
first_undrawable(t)
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs
index d6c50e9..ed9125a 100644
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@ -761,7 +761,9 @@ fn fallback_paths(doc: &Document) -> Vec<Vec<u8>> {
let p = pdfcraft_model::pages(doc).swap_remove(0);
let res = doc.resolve(p.dict.get(b"Resources").unwrap());
let fonts = doc.resolve(res.as_dict().unwrap().get(b"Font").unwrap());
- let font = doc.resolve(fonts.as_dict().unwrap().get(b"PCJp").unwrap());
+ // The Japanese fallback, or Inter's for Latin, Greek and Cyrillic.
+ let fonts = fonts.as_dict().unwrap();
+ let font = doc.resolve(fonts.get(b"PCJp").or_else(|| fonts.get(b"PCIn")).unwrap());
let procs = doc.resolve(font.as_dict().unwrap().get(b"CharProcs").unwrap());
procs
.as_dict()
@@ -858,17 +860,11 @@ fn japanese_fallback_reports_the_face_after_save_and_reopen() {
}
}
+/// Cyrillic replacement text in a serif line comes from Inter, which every build has (the serif
+/// Japanese fallback has no Cyrillic).
#[test]
fn cyrillic_in_a_serif_line_falls_back_to_a_face_that_has_it() {
- if without_craft_fonts("cyrillic_in_a_serif_line_falls_back_to_a_face_that_has_it") {
- return;
- }
let replacement = "Привет, world";
- let has_all = |f: &pdfcraft_fonts::CraftFont| replacement.chars().all(|ch| pdfcraft_fonts::japanese_glyph_from(f, ch).is_ok());
- if !pdfcraft_fonts::CRAFT_FONTS.iter().any(|f| f.covers("Jpan") && has_all(f)) {
- eprintln!("skipping: no Japanese fallback face has Cyrillic");
- return;
- }
for paragraph in [false, true] {
let mut doc = styled_text_page("Times-Roman");
if paragraph {
@@ -1074,7 +1070,7 @@ fn type3_fallback_glyphs_declare_a_well_formed_d1() {
if without_craft_fonts("type3_fallback_glyphs_declare_a_well_formed_d1") {
return;
}
- // Cyrillic is respaced (shifted by its side bearing), and its box must move with it.
+ // Japanese from the craft-fonts face, Cyrillic from Inter: every box encloses its glyph.
let mut glyphs = Vec::new();
for replacement in ["見本商会 御中", "София 2027"] {
let mut doc = text_page("BT /F2 12 Tf 72 700 Td (ab) Tj ET");
@@ -1099,12 +1095,10 @@ fn type3_fallback_glyphs_declare_a_well_formed_d1() {
}
/// Shippori Mincho, the serif fallback, has no Cyrillic: Bulgarian replacement text in a serif
-/// line takes a fallback face that has every letter instead of failing on the first one.
+/// line takes a fallback face that has every letter (Inter, in every build) instead of failing on
+/// the first one.
#[test]
fn cyrillic_replacement_in_a_serif_line_uses_a_face_with_the_letters() {
- if without_craft_fonts("cyrillic_replacement_in_a_serif_line_uses_a_face_with_the_letters") {
- return;
- }
let replacement = "София 2027";
for paragraph in [false, true] {
let mut doc = styled_text_page("ABCDEF+Garamond");
@@ -1122,12 +1116,54 @@ fn cyrillic_replacement_in_a_serif_line_uses_a_face_with_the_letters() {
}
}
+/// Replacement text with letters beyond Western European (Turkish ş, Polish ł, Romanian ț) in a
+/// line whose font can't show them is drawn from Inter, which every build has, instead of being
+/// refused (it used to need the craft-fonts Japanese faces), and reads back as typed. Text Inter
+/// lacks too still needs those faces: refused without them, never written as `?`.
+#[test]
+fn replacement_text_beyond_western_european_is_drawn_in_inter() {
+ for replacement in ["Mustafa çokyaşar", "Zażółć gęślą jaźń", "Țară și"] {
+ for paragraph in [false, true] {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Mustafa cokyasar) Tj ET");
+ let edit = if paragraph { text::replace_block(&mut doc, 0, 0, replacement) } else { text::replace_line(&mut doc, 0, 0, replacement) };
+ assert_eq!(edit.unwrap().substituted.as_deref(), Some("Inter Type3"), "{replacement}");
+ assert_eq!(text::text_lines(&reopen(&doc), 0).unwrap()[0].text, replacement);
+ assert!(!fallback_paths(&reopen(&doc)).is_empty());
+ }
+ }
+ if pdfcraft_fonts::document_japanese_font().is_none() {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (ab) Tj ET");
+ assert!(text::replace_line(&mut doc, 0, 0, "ş 中").is_err());
+ }
+}
+
+/// Added text beyond Western European is drawn in Inter (shaped, every glyph of the item from it so
+/// a word never mixes fonts) instead of being refused, and reads back as typed. Text Inter can't
+/// draw either is refused as before.
+#[test]
+fn added_text_beyond_western_european_is_drawn_in_inter() {
+ let mut doc = fixture();
+ let text =
+ AddedText { rect: [72.0, 600.0, 400.0, 700.0], text: "Mustafa çokyaşar\nΕλληνικά Привет".into(), ..AddedText::default() };
+ add_content(&mut doc, 0, &Content::Text(text.clone())).unwrap();
+ let reopened = reopen(&doc);
+ let lines: Vec<String> = text::text_lines(&reopened, 0).unwrap().into_iter().map(|l| l.text).collect();
+ assert!(lines.iter().any(|l| l == "Mustafa çokyaşar"), "{lines:?}");
+ assert!(lines.iter().any(|l| l == "Ελληνικά Привет"), "{lines:?}");
+ let Content::Text(back) = &list_added(&reopened)[0].content else { panic!("text") };
+ assert_eq!(back.text, text.text);
+ // Retyped to Western European text: the standard font again.
+ add_content(&mut doc, 0, &Content::Text(AddedText { text: "Café".into(), ..text.clone() })).unwrap();
+ let cjk = AddedText { text: "ş 中".into(), ..text };
+ assert!(add_content(&mut doc, 0, &Content::Text(cjk)).unwrap_err().to_string().contains("U+4E2D"));
+}
+
/// The `/Widths` of the page's Type 3 fallback font, for its Cyrillic letters.
fn fallback_widths(doc: &Document) -> Vec<f64> {
let p = pdfcraft_model::pages(doc).swap_remove(0);
let res = doc.resolve(p.dict.get(b"Resources").unwrap());
let fonts = doc.resolve(res.as_dict().unwrap().get(b"Font").unwrap());
- let font = doc.resolve(fonts.as_dict().unwrap().get(b"PCJp").unwrap());
+ let font = doc.resolve(fonts.as_dict().unwrap().get(b"PCIn").unwrap());
let font = font.as_dict().unwrap();
let widths = doc.resolve(font.get(b"Widths").unwrap()).as_array().unwrap().iter().filter_map(|w| w.as_f64()).collect::<Vec<_>>();
// "София 2027": the first five codes are the letters.
diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs
index 16a2b51..c56355c 100644
--- a/crates/edit/src/text.rs
+++ b/crates/edit/src/text.rs
@@ -1196,12 +1196,20 @@ fn needs_type3(text: &str) -> bool {
const JAPANESE_FONT_NAME: &str = "PCJapanese";
/// The `/Name` of the Type 3 fonts generated for Hebrew text.
const HEBREW_FONT_NAME: &str = "PCHebrew";
+/// The `/Name` of the Type 3 fonts generated from Inter, for Latin, Greek and Cyrillic text the
+/// standard fonts can't hold (Turkish ş, Polish ł, …).
+const INTER_FONT_NAME: &str = "PCInter";
-/// Whether `font` is one of those generated fonts (Japanese or Hebrew): a replacement longer than
-/// one of them is split across several, which read back as one line (see [`same_font`]).
+/// Whether `font` is one of those generated fonts (Japanese, Hebrew or Inter): a replacement longer
+/// than one of them is split across several, which read back as one line (see [`same_font`]).
fn is_type3_fallback(font: &Dict) -> bool {
font.name(b"Subtype") == Some(b"Type3")
- && font.name(b"Name").is_some_and(|n| n == JAPANESE_FONT_NAME.as_bytes() || n == HEBREW_FONT_NAME.as_bytes())
+ && font.name(b"Name").is_some_and(|n| [JAPANESE_FONT_NAME, HEBREW_FONT_NAME, INTER_FONT_NAME].iter().any(|name| n == name.as_bytes()))
+}
+
+/// Whether `face` is the bundled Inter rather than a craft-fonts face.
+fn is_inter(face: &CraftFont) -> bool {
+ std::ptr::eq(face, &pdfcraft_fonts::INTER)
}
/// Whether a run shown in `font` (a resource name, and the Japanese or Hebrew fallback face it subsets, if
@@ -1259,7 +1267,8 @@ fn type3_path(face: &CraftFont, ch: char) -> Result<(Vec<u8>, f64), EditError> {
GlyphError::Missing => EditError::Invalid(format!("the {} fallback font has no glyph for U+{:04X}", face.family, ch as u32)),
GlyphError::TooComplex => EditError::Invalid(format!("the {} fallback glyph U+{:04X} is too complex", face.family, ch as u32)),
})?;
- let (dx, width) = proportional(ch, &glyph);
+ // Inter's Greek and Cyrillic are proportional already.
+ let (dx, width) = if is_inter(face) { (0.0, glyph.width) } else { proportional(ch, &glyph) };
let scale = 1000.0;
// d1 is `wx wy llx lly urx ury` (ISO 32000-2 §9.6.4) with a box enclosing the glyph;
// Acrobat draws a bullet in place of a glyph whose d1 is malformed.
@@ -1332,10 +1341,14 @@ fn no_hebrew_font() -> EditError {
/// The faces a Type 3 replacement may draw `text` with, best first. Text with Hebrew takes the
/// Hebrew face first (its Latin and digits too, so a line keeps one look), then the Japanese
-/// faces for anything it lacks; other text takes the Japanese faces, as before.
+/// faces for anything it lacks. Text Inter can draw all of (Turkish ş, Polish ł, Greek, Cyrillic, …)
+/// takes Inter, which every build has; other text takes the Japanese faces, as before.
fn type3_faces(text: &str, family: crate::added::Family, bold: bool) -> Result<(Vec<&'static CraftFont>, bool), EditError> {
let japanese = pdfcraft_fonts::document_japanese_fonts_for_style(family == crate::added::Family::Times, bold);
if !text.chars().any(crate::bidi::is_hebrew) {
+ if text.chars().all(|c| is_win_ansi_char(c) || pdfcraft_fonts::inter_has(c)) {
+ return Ok((std::iter::once(&pdfcraft_fonts::INTER).chain(japanese).collect(), false));
+ }
return Ok((japanese, false));
}
// Points are drawn on their letter with the font's positioning, which a one-glyph-per-
@@ -1431,10 +1444,17 @@ fn add_type3_font(doc: &mut Document, fonts_res: &mut Dict, face: &CraftFont, he
let mut encoding = Dict::new();
encoding.set(b"Type".to_vec(), Object::name("Encoding"));
encoding.set(b"Differences".to_vec(), Object::Array(differences));
+ let (font_name, prefix) = if hebrew {
+ (HEBREW_FONT_NAME, "PCHe")
+ } else if is_inter(face) {
+ (INTER_FONT_NAME, "PCIn")
+ } else {
+ (JAPANESE_FONT_NAME, "PCJp")
+ };
let mut font = Dict::new();
font.set(b"Type".to_vec(), Object::name("Font"));
font.set(b"Subtype".to_vec(), Object::name("Type3"));
- font.set(b"Name".to_vec(), Object::name(if hebrew { HEBREW_FONT_NAME } else { JAPANESE_FONT_NAME }));
+ font.set(b"Name".to_vec(), Object::name(font_name));
let mut descriptor = Dict::new();
descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor"));
descriptor.set(b"FontName".to_vec(), Object::name(&format!("{}-{}", face.family, face.style).replace(' ', "")));
@@ -1454,7 +1474,6 @@ fn add_type3_font(doc: &mut Document, fonts_res: &mut Dict, face: &CraftFont, he
font.set(b"Encoding".to_vec(), Object::Dict(encoding));
font.set(b"CharProcs".to_vec(), Object::Dict(charprocs));
font.set(b"ToUnicode".to_vec(), Object::Ref(cmap_ref));
- let prefix = if hebrew { "PCHe" } else { "PCJp" };
let mut name = String::from(prefix);
let mut suffix = 0usize;
while fonts_res.contains(name.as_bytes()) {
diff --git a/crates/fonts/README.md b/crates/fonts/README.md
index e2785fc..8496bf4 100644
--- a/crates/fonts/README.md
+++ b/crates/fonts/README.md
@@ -16,6 +16,14 @@ Today it holds what generated appearances need without a font program:
value or a comment's text, which is stored as typed, draw the `?` and mark the annotation with
`set_undrawn_mark` (`UNDRAWN_MARK`, read back by `undrawn_mark`) so the edit is reported and
flattening refuses. `script_missing` names what the typed-signature script font and its Inter fallback both lack.
+- Inter (`INTER_REGULAR`, bundled in every build) stands in for text WinAnsiEncoding can't hold
+ but Inter can (Turkish ş, Polish ł, Czech ř, Romanian ț, Greek, Cyrillic, …): `needs_inter` says
+ when, and `first_undrawable_inter` is `first_undrawable` for paths that do so. Generated
+ appearances (text boxes, Fill & Sign text, form fields) draw it as Inter's outlines
+ (`inter_path`, measured with `inter_width`), so they need no font resource; page content gets
+ Type 3 fonts drawn from the same face (`INTER` as a `CraftFont` for the editor's fallback, and
+ `ShapedScript::Inter` / `shape_inter` for added text). Text Inter lacks too keeps the behaviour
+ above.
It also holds the fonts of the optional [craft-fonts](https://github.com/storytold/craft-fonts)
build input. `build.rs` embeds them as `CRAFT_FONTS` when the build sets
diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs
index 19d0d1d..8289225 100644
--- a/crates/fonts/src/lib.rs
+++ b/crates/fonts/src/lib.rs
@@ -18,9 +18,10 @@ pub use craft::{
ui_telugu_fonts, ui_thai_fonts,
};
pub use script::{
- GlyphError, GlyphOutline, INTER_REGULAR, MAX_SIGNATURE_CHARS, ScriptOutline, japanese_glyph, japanese_glyph_from, script_missing, script_outline,
+ GlyphError, GlyphOutline, INTER, INTER_REGULAR, MAX_SIGNATURE_CHARS, ScriptOutline, inter_has, inter_path, inter_width, japanese_glyph,
+ japanese_glyph_from, script_missing, script_outline,
};
-pub use shaping::{ShapedCluster, ShapedScript, arabic_glyph, arabic_has, shape_arabic, shape_thai, shaped_glyph, thai_has};
+pub use shaping::{ShapedCluster, ShapedScript, arabic_glyph, arabic_has, shape_arabic, shape_inter, shape_thai, shaped_glyph, thai_has};
/// Approximate advance of `s` in Helvetica (or Arial) at `size` points.
pub fn helvetica_width(s: &str, size: f64) -> f64 {
@@ -209,6 +210,26 @@ pub fn first_undrawable(s: &str) -> Option<char> {
s.chars().find(|c| !matches!(c, '\n' | '\r') && !win_ansi_encodable(*c))
}
+/// Whether PdfCraft draws `s` in Inter instead of the standard fonts: they can't draw one of its
+/// characters (Turkish ş, Polish ł, Greek, Cyrillic, …) and Inter, which every build has, can draw
+/// every one of those. Line breaks don't count.
+pub fn needs_inter(s: &str) -> bool {
+ let mut any = false;
+ for c in s.chars().filter(|c| !matches!(c, '\n' | '\r') && !win_ansi_encodable(*c)) {
+ if !inter_has(c) {
+ return false;
+ }
+ any = true;
+ }
+ any
+}
+
+/// [`first_undrawable`] where text the standard fonts can't draw is drawn in Inter instead
+/// ([`needs_inter`]): the first character that would still come out as `?`, or `None`.
+pub fn first_undrawable_inter(s: &str) -> Option<char> {
+ if needs_inter(s) { None } else { first_undrawable(s) }
+}
+
/// The error for text the standard fonts can't draw ([`first_undrawable`]): which character, in
/// what (`"the comment"`, `"the reason"`), and what can be written instead. One wording for every
/// path that writes text in the standard fonts, so agents and users can act on it the same way.
@@ -283,6 +304,37 @@ mod tests {
assert!(undrawable_message("x", '𠀋').contains("(U+2000B)"));
}
+ /// Text beyond Western European (Turkish, Polish, Czech, Romanian, Greek, Cyrillic) is drawn in
+ /// the bundled Inter instead of as `?`; text Inter can't draw either keeps the old behaviour.
+ #[test]
+ fn inter_draws_what_the_standard_fonts_cannot() {
+ for s in ["Mustafa çokyaşar", "ÇçĞğİıÖöŞşÜü", "Zażółć gęślą jaźń", "Příliš žluťoučký kůň", "Țară și", "Ελληνικά", "Привет, Їжак"]
+ {
+ assert!(needs_inter(s), "{s}");
+ assert_eq!(first_undrawable_inter(s), None, "{s}");
+ for c in s.chars().filter(|c| !win_ansi_encodable(*c)) {
+ assert!(inter_has(c), "{s}: {c}");
+ }
+ }
+ // Western European text stays in the standard fonts.
+ assert!(!needs_inter("Café — 5€\r\n™"));
+ assert_eq!(first_undrawable_inter("Café"), None);
+ // Inter can't draw 中, so the text stays in Helvetica, where ş is the first `?`.
+ assert!(!needs_inter("ş 中"));
+ assert_eq!(first_undrawable_inter("ş 中"), Some('ş'));
+ assert_eq!(first_undrawable_inter("签名"), Some('签'));
+ // A line as paths: curves, closed, at the given place and size.
+ let path = inter_path("ş", 10.0, 5.0, 7.0);
+ assert!(path.contains(" m\n") && path.contains(" c\n") && path.ends_with("h\n"), "{path}");
+ let xs: Vec<f64> = path.lines().filter_map(|l| l.split(' ').next()?.parse().ok()).collect();
+ assert!(xs.iter().all(|x| (5.0..=11.0).contains(x)), "{xs:?}");
+ assert!(inter_path(" \t", 10.0, 0.0, 0.0).is_empty(), "spaces have no outline");
+ // Inter's advances, close to Helvetica's estimate for the same letters.
+ let (inter, helvetica) = (inter_width("Mustafa çokyaşar", 10.0), helvetica_width("Mustafa cokyasar", 10.0));
+ assert!(inter > helvetica * 0.8 && inter < helvetica * 1.3, "{inter} vs {helvetica}");
+ assert_eq!(inter_width("a\tb", 10.0), inter_width("a b", 10.0));
+ }
+
#[test]
fn the_undrawn_mark_records_one_character_and_clears() {
let mut d = pdfcraft_cos::Dict::new();
diff --git a/crates/fonts/src/script.rs b/crates/fonts/src/script.rs
index 70fc6ce..8e5bdd3 100644
--- a/crates/fonts/src/script.rs
+++ b/crates/fonts/src/script.rs
@@ -1,5 +1,7 @@
//! Typed signatures and bounded glyph outlines from approved fonts (bundled, or craft-fonts).
+use std::sync::OnceLock;
+
use skrifa::instance::{LocationRef, Size};
use skrifa::outline::{DrawSettings, OutlinePen};
use skrifa::{FontRef, GlyphId, MetadataProvider};
@@ -10,6 +12,120 @@ static FONT: &[u8] = include_bytes!("../../../assets/fonts/DancingScript.ttf");
/// the script font lacks (Dancing Script is Latin and Vietnamese only: no Cyrillic or Greek).
pub static INTER_REGULAR: &[u8] = include_bytes!("../../../assets/fonts/Inter-Regular.ttf");
+/// Inter as a face the generated Type 3 fonts draw from ([`japanese_glyph_from`]): the stand-in
+/// for Latin, Greek and Cyrillic text the standard fonts' WinAnsiEncoding can't hold (Turkish ş,
+/// Polish ł, Czech ř, …). Unlike the craft-fonts faces, every build has it.
+pub static INTER: crate::CraftFont = crate::CraftFont { family: "Inter", style: "Regular", scripts: &["Latn", "Grek", "Cyrl"], bytes: INTER_REGULAR };
+
+fn inter() -> Option<&'static FontRef<'static>> {
+ static FACE: OnceLock<Option<FontRef<'static>>> = OnceLock::new();
+ FACE.get_or_init(|| FontRef::new(INTER_REGULAR).ok()).as_ref()
+}
+
+/// Whether Inter has a glyph for `c`.
+pub fn inter_has(c: char) -> bool {
+ inter().is_some_and(|f| f.charmap().map(c).is_some())
+}
+
+/// The advance of `s` in Inter at `size` points (no kerning). A tab counts as a space; a character
+/// Inter lacks counts as Helvetica's estimate for it.
+pub fn inter_width(s: &str, size: f64) -> f64 {
+ let Some(font) = inter() else { return crate::helvetica_width(s, size) };
+ let loc = LocationRef::default();
+ let em = f64::from(font.metrics(Size::unscaled(), loc).units_per_em.max(1));
+ let (charmap, advances) = (font.charmap(), font.glyph_metrics(Size::unscaled(), loc));
+ let mut buf = [0u8; 4];
+ s.chars()
+ .map(|c| if c == '\t' { ' ' } else { c })
+ .map(|c| match charmap.map(c).and_then(|g| advances.advance_width(g)) {
+ Some(w) => f64::from(w) * size / em,
+ None => crate::helvetica_width(c.encode_utf8(&mut buf), size),
+ })
+ .sum()
+}
+
+/// PDF path operators (`m`, `l`, `c`, `h`) that draw one line of `s` in Inter at `size` points with
+/// its baseline starting at (`x`, `y`); fill them (`f`) to show the text. Generated appearances
+/// draw text the standard fonts can't hold this way, so they need no font resource. A tab is a
+/// space; characters Inter lacks are skipped, so check [`crate::needs_inter`] first.
+pub fn inter_path(s: &str, size: f64, x: f64, y: f64) -> String {
+ let Some(font) = inter() else { return String::new() };
+ let loc = LocationRef::default();
+ let scale = size / f64::from(font.metrics(Size::unscaled(), loc).units_per_em.max(1));
+ let (charmap, glyphs, advances) = (font.charmap(), font.outline_glyphs(), font.glyph_metrics(Size::unscaled(), loc));
+ let mut pen = PathPen { out: String::new(), scale, x, y, last: (0.0, 0.0) };
+ for c in s.chars().map(|c| if c == '\t' { ' ' } else { c }) {
+ let Some(gid) = charmap.map(c) else { continue };
+ if let Some(g) = glyphs.get(gid) {
+ let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), loc), &mut pen);
+ }
+ pen.x += f64::from(advances.advance_width(gid).unwrap_or(0.0)) * scale;
+ }
+ pen.out
+}
+
+/// Writes outlines as PDF path operators, quadratic curves as their exact cubic equivalents.
+struct PathPen {
+ out: String,
+ scale: f64,
+ /// Where the current glyph's origin is, in the output's space.
+ x: f64,
+ y: f64,
+ /// The current point in font units, for converting quadratic curves.
+ last: (f32, f32),
+}
+
+impl PathPen {
+ fn point(&mut self, x: f32, y: f32) {
+ let fmt = |v: f64| {
+ let s = format!("{v:.2}");
+ let s = s.trim_end_matches('0').trim_end_matches('.');
+ if s == "-0" { "0".to_string() } else { s.to_string() }
+ };
+ let (px, py) = (self.x + f64::from(x) * self.scale, self.y + f64::from(y) * self.scale);
+ self.out.push_str(&fmt(px));
+ self.out.push(' ');
+ self.out.push_str(&fmt(py));
+ self.out.push(' ');
+ }
+}
+
+impl OutlinePen for PathPen {
+ fn move_to(&mut self, x: f32, y: f32) {
+ self.point(x, y);
+ self.out.push_str("m\n");
+ self.last = (x, y);
+ }
+
+ fn line_to(&mut self, x: f32, y: f32) {
+ self.point(x, y);
+ self.out.push_str("l\n");
+ self.last = (x, y);
+ }
+
+ fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
+ // The cubic with control points two thirds of the way to the quadratic's.
+ let (x0, y0) = self.last;
+ self.point(x0 + (cx - x0) * 2.0 / 3.0, y0 + (cy - y0) * 2.0 / 3.0);
+ self.point(x + (cx - x) * 2.0 / 3.0, y + (cy - y) * 2.0 / 3.0);
+ self.point(x, y);
+ self.out.push_str("c\n");
+ self.last = (x, y);
+ }
+
+ fn curve_to(&mut self, c0x: f32, c0y: f32, c1x: f32, c1y: f32, x: f32, y: f32) {
+ self.point(c0x, c0y);
+ self.point(c1x, c1y);
+ self.point(x, y);
+ self.out.push_str("c\n");
+ self.last = (x, y);
+ }
+
+ fn close(&mut self) {
+ self.out.push_str("h\n");
+ }
+}
+
/// Forward slant of fallback glyphs in a typed signature (about 12°), so they lean like the script.
const FALLBACK_SLANT: f64 = 0.21;
diff --git a/crates/fonts/src/shaping.rs b/crates/fonts/src/shaping.rs
index 75b6321..18515b1 100644
--- a/crates/fonts/src/shaping.rs
+++ b/crates/fonts/src/shaping.rs
@@ -1,4 +1,5 @@
-//! Arabic and Thai text shaping with the matching craft-fonts face and bounded glyph outlines.
+//! Arabic and Thai text shaping with the matching craft-fonts face, Latin, Greek and Cyrillic
+//! beyond WinAnsiEncoding with the bundled Inter, and bounded glyph outlines.
use std::sync::OnceLock;
@@ -27,6 +28,8 @@ pub struct ShapedCluster {
pub enum ShapedScript {
Arabic,
Thai,
+ /// Latin, Greek and Cyrillic in Inter ([`crate::INTER`]), for text the standard fonts can't draw.
+ Inter,
}
impl ShapedScript {
@@ -34,6 +37,7 @@ impl ShapedScript {
match self {
Self::Arabic => crate::document_arabic_font(),
Self::Thai => crate::document_thai_font(),
+ Self::Inter => Some(&crate::INTER),
}
}
}
@@ -41,9 +45,11 @@ impl ShapedScript {
fn face(script: ShapedScript) -> Option<&'static (FontRef<'static>, ShaperData)> {
static FACE: OnceLock<Option<(FontRef<'static>, ShaperData)>> = OnceLock::new();
static THAI: OnceLock<Option<(FontRef<'static>, ShaperData)>> = OnceLock::new();
+ static INTER: OnceLock<Option<(FontRef<'static>, ShaperData)>> = OnceLock::new();
let cache = match script {
ShapedScript::Arabic => &FACE,
ShapedScript::Thai => &THAI,
+ ShapedScript::Inter => &INTER,
};
cache
.get_or_init(|| {
@@ -76,6 +82,12 @@ pub fn shape_thai(text: &str) -> Result<Vec<ShapedCluster>, GlyphError> {
shape_script(text, false, ShapedScript::Thai)
}
+/// Shape one directional run of Latin, Greek or Cyrillic text with Inter, clusters in drawing
+/// order. [`GlyphError::Missing`] when Inter lacks a character.
+pub fn shape_inter(text: &str, rtl: bool) -> Result<Vec<ShapedCluster>, GlyphError> {
+ shape_script(text, rtl, ShapedScript::Inter)
+}
+
fn shape_script(text: &str, rtl: bool, kind: ShapedScript) -> Result<Vec<ShapedCluster>, GlyphError> {
let (font, data) = face(kind).ok_or(GlyphError::NoFont)?;
let shaper = data.shaper(font).build();
@@ -83,13 +95,16 @@ fn shape_script(text: &str, rtl: bool, kind: ShapedScript) -> Result<Vec<ShapedC
let mut buffer = UnicodeBuffer::new();
buffer.push_str(text);
buffer.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
- buffer.set_script(match kind {
- ShapedScript::Arabic => script::ARABIC,
- ShapedScript::Thai => script::THAI,
- });
- // Preserve the historical Arabic per-character mapping; Thai marks stay with their base.
+ match kind {
+ ShapedScript::Arabic => buffer.set_script(script::ARABIC),
+ ShapedScript::Thai => buffer.set_script(script::THAI),
+ // Latin, Greek or Cyrillic, from the text itself.
+ ShapedScript::Inter => buffer.guess_segment_properties(),
+ }
+ // Preserve the historical Arabic per-character mapping (Inter's text gets the same); Thai
+ // marks stay with their base.
buffer.set_cluster_level(match kind {
- ShapedScript::Arabic => BufferClusterLevel::Characters,
+ ShapedScript::Arabic | ShapedScript::Inter => BufferClusterLevel::Characters,
ShapedScript::Thai => BufferClusterLevel::MonotoneGraphemes,
});
let shaped = shaper.shape(buffer, ShapeOptions::new());
diff --git a/crates/forms/README.md b/crates/forms/README.md
index 3280cc2..bc9f4f3 100644
--- a/crates/forms/README.md
+++ b/crates/forms/README.md
@@ -34,7 +34,9 @@ delete_field(&mut doc, "email")?;
- Text and choice fields get new appearance streams (`/Tx BMC … EMC`): auto-size (`0 Tf`), comb,
multiline wrapping, password masking, quadding, `/MK` background and border, list-box selection.
The `/DA` font is used when `/DR` has it as a simple font or a composite font with a predefined
- Unicode CMap; otherwise Helvetica (WinAnsi). A value or button caption the font can't hold
+ Unicode CMap; otherwise Helvetica (WinAnsi), or, for a value WinAnsi can't hold but the bundled
+ Inter can (Turkish, Polish, Greek, Cyrillic, …), Inter's outlines with no font at all. A value or
+ button caption the font can't hold
(Chinese in a Helvetica field, a character beyond U+FFFF in a UCS-2 CMap) is kept, as Acrobat
keeps it: `/V` is stored as typed, the appearance draws `?` for those characters, the widget is
marked with the first one (`pdfcraft_fonts::UNDRAWN_MARK`, cleared once all of it can be drawn)
diff --git a/crates/forms/src/appearance.rs b/crates/forms/src/appearance.rs
index dc5ffce..9bc6879 100644
--- a/crates/forms/src/appearance.rs
+++ b/crates/forms/src/appearance.rs
@@ -124,6 +124,9 @@ enum FontText {
Simple(Box<Metrics>),
/// A composite font with a predefined Unicode CMap.
Unicode(UnicodeCMap),
+ /// No font: text the standard fonts can't hold (Turkish ş, Polish ł, Greek, Cyrillic, …) drawn
+ /// as the outlines of the bundled Inter ([`pdfcraft_fonts::inter_path`]).
+ Inter,
}
impl FontText {
@@ -133,6 +136,8 @@ impl FontText {
// Selection checks every displayed string first; wrapping only removes line breaks.
Self::Simple(metrics) => metrics.encode(&s.replace('\t', " ")).unwrap_or_default(),
Self::Unicode(cmap) => cmap.encode(s),
+ // Drawn as paths (see `field_appearance_drawn`), never shown as a string.
+ Self::Inter => Vec::new(),
}
}
@@ -153,6 +158,8 @@ impl FontText {
s.chars().map(|c| if c == '\t' { ' ' } else { c }).find(|c| metrics.encode(c.encode_utf8(&mut [0; 4])).is_none())
}
Self::Unicode(cmap) => cmap.first_unencodable(s),
+ // Chosen only when Inter draws every character the standard fonts can't.
+ Self::Inter => pdfcraft_fonts::first_undrawable_inter(s),
}
}
@@ -160,6 +167,7 @@ impl FontText {
match self {
Self::WinAnsi | Self::Simple(_) => helvetica_width(s, size),
Self::Unicode(_) => cjk_width(s, size),
+ Self::Inter => pdfcraft_fonts::inter_width(s, size),
}
}
}
@@ -334,10 +342,16 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
enc.can_encode(&text)
}
};
+ // What is shown: every option of a list box, else the text.
+ let shown =
+ if f.kind == FieldKind::List { f.options.iter().map(|(_, display)| display.as_str()).collect::<Vec<_>>().join("\n") } else { text.clone() };
let (font_name, font_obj, enc) = match dr_font(doc, &da.font).filter(|(_, enc)| can_show(enc)) {
Some((o, enc)) => (da.font.clone(), o, enc),
+ // Helvetica can't hold it but Inter draws it all: paths, no font.
+ None if pdfcraft_fonts::needs_inter(&shown) => (String::new(), Object::Null, FontText::Inter),
None => ("Helv".to_string(), helvetica(), FontText::WinAnsi),
};
+ let inter = enc == FontText::Inter;
let width_of = |text: &str, size: f64| enc.width(text, size);
let (mut c, bw) = frame(doc, &wd, width, height);
let pad = 2.0 + bw;
@@ -346,12 +360,21 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
let mut body: Vec<u8> = Vec::new();
// The first character drawn that the font can't hold (drawn as `?`), for the caller to report.
let mut unencodable: Option<char> = None;
- let mut show = |body: &mut Vec<u8>, x: f64, y: f64, text: &str| {
+ let mut show = |body: &mut Vec<u8>, x: f64, y: f64, text: &str, size: f64| {
// A line break in a single-line value is a space, as in viewers (multiline text is split).
let text: String = text.chars().map(|c| if matches!(c, '\n' | '\r') { ' ' } else { c }).collect();
if unencodable.is_none() {
unencodable = enc.first_unencodable(&text);
}
+ if inter {
+ // A string of spaces has no outline, and `f` needs a path.
+ let path = pdfcraft_fonts::inter_path(&text, size, x, y);
+ if !path.is_empty() {
+ body.extend(path.bytes());
+ body.extend_from_slice(b"f\n");
+ }
+ return;
+ }
body.extend(format!("1 0 0 1 {} {} Tm ", n(x), n(y)).bytes());
body.extend(literal(&enc.encode(&text)));
body.extend_from_slice(b" Tj\n");
@@ -381,7 +404,7 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
if values.contains(export) {
c.push_str(&format!("0.6 0.75 0.86 rg\n{} {} {} {} re f\n", n(bw), n(y - line), n(width - 2.0 * bw), n(line)));
}
- show(&mut body, pad, y - line + size * 0.25, display);
+ show(&mut body, pad, y - line + size * 0.25, display, size);
y -= line;
}
}
@@ -400,7 +423,7 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
if y < -size {
break;
}
- show(&mut body, x_for(&line, size), y, &line);
+ show(&mut body, x_for(&line, size), y, &line, size);
y -= size * 1.15;
}
} else {
@@ -418,34 +441,30 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
let cell = width / cells as f64;
for (i, ch) in text.chars().take(cells).enumerate() {
let s = ch.to_string();
- show(&mut body, cell * i as f64 + (cell - width_of(&s, size)) / 2.0, y, &s);
+ show(&mut body, cell * i as f64 + (cell - width_of(&s, size)) / 2.0, y, &s, size);
}
} else {
- show(&mut body, x_for(&text, size), y, &text);
+ show(&mut body, x_for(&text, size), y, &text, size);
}
}
}
}
let mut content = c.into_bytes();
- content.extend(
- format!(
- "/Tx BMC\nq\n{} {} {} {} re W n\nBT\n/{} {} Tf\n{}\n",
- n(bw),
- n(bw),
- n(width - 2.0 * bw),
- n(height - 2.0 * bw),
- font_name,
- n(size),
- da.color
- )
- .bytes(),
- );
- content.extend(body);
- content.extend_from_slice(b"ET\nQ\nEMC\n");
- let mut fonts = Dict::new();
- fonts.set(font_name.into_bytes(), font_obj);
+ let clip = format!("/Tx BMC\nq\n{} {} {} {} re W n\n", n(bw), n(bw), n(width - 2.0 * bw), n(height - 2.0 * bw));
let mut res = Dict::new();
- res.set(b"Font".to_vec(), Object::Dict(fonts));
+ if inter {
+ // Paths in the text colour: no text object, no font.
+ content.extend(format!("{clip}{}\n", da.color).bytes());
+ content.extend(body);
+ content.extend_from_slice(b"Q\nEMC\n");
+ } else {
+ content.extend(format!("{clip}BT\n/{} {} Tf\n{}\n", font_name, n(size), da.color).bytes());
+ content.extend(body);
+ content.extend_from_slice(b"ET\nQ\nEMC\n");
+ let mut fonts = Dict::new();
+ fonts.set(font_name.into_bytes(), font_obj);
+ res.set(b"Font".to_vec(), Object::Dict(fonts));
+ }
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("XObject"));
d.set(b"Subtype".to_vec(), Object::name("Form"));
diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs
index 45e8501..da47439 100644
--- a/crates/forms/src/tests.rs
+++ b/crates/forms/src/tests.rs
@@ -460,6 +460,43 @@ fn text_a_field_font_cannot_hold_is_kept_marked_and_redrawn_elsewhere() {
assert!(need_appearances(&doc));
}
+/// A field value beyond Western European (Turkish ş, Polish ł, Greek, Cyrillic) is drawn as the
+/// bundled Inter's outlines instead of `?`, in the field's text colour, and nothing is marked.
+#[test]
+fn field_text_beyond_western_european_is_drawn_in_inter() {
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>".into(),
+ "<< /Fields [6 0 R 7 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /DA (/Helv 10 Tf 0 0 1 rg) /V (Ada) /Rect [50 700 200 715] /P 3 0 R >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (notes) /Ff 4096 /DA (/Helv 0 Tf 0 g) /Rect [50 500 200 560] /P 3 0 R >>".into(),
+ ];
+ let mut doc = document(&objs);
+ let shown = |doc: &Document, name: &str| {
+ let all = fields(doc);
+ let w = &field(&all, name).widgets[0];
+ let n = doc.get(w.obj).as_dict().unwrap().get(b"AP").unwrap().as_dict().unwrap().reference(b"N").unwrap();
+ let Object::Stream(s) = &*doc.get(n) else { panic!() };
+ let mark = doc.get(w.obj).as_dict().and_then(pdfcraft_fonts::undrawn_mark);
+ (String::from_utf8_lossy(&s.decoded().unwrap()).into_owned(), mark)
+ };
+ set_value(&mut doc, "name", &FieldValue::Text("Mustafa Çokyaşar".into())).unwrap();
+ assert_eq!(field(&fields(&doc), "name").value, ["Mustafa Çokyaşar"]);
+ let (ap, mark) = shown(&doc, "name");
+ assert_eq!(mark, None);
+ assert!(!ap.contains('?') && !ap.contains("Tj") && !ap.contains("BT"), "{ap}");
+ assert!(ap.contains("0 0 1 rg") && ap.contains(" c\n") && ap.contains("f\n"), "filled outlines in the field's colour: {ap}");
+ // A multiline field wraps by Inter's widths; Greek and Cyrillic the same way.
+ set_value(&mut doc, "notes", &FieldValue::Text("Zażółć gęślą jaźń. Ελληνικά, Привет".into())).unwrap();
+ assert_eq!(shown(&doc, "notes").1, None);
+ // Western European text is Helvetica text again.
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ assert!(shown(&doc, "name").0.contains("(Ada) Tj"));
+ assert!(undrawn_fields(&doc).is_empty());
+}
+
/// A document that declares PDF/A can't ask other viewers to redraw its fields (PDF/A forbids
/// `/NeedAppearances`): the value is still kept and its widget marked, and the flag stays off.
#[test]