Fall back per glyph outside the Type1 encodings

This commit is contained in:
gloamxun committed 2026-10-25 00:03:19 +08:00
1 parent 9ae86d9c86
commit c6860b7b4a
5 files changed
+155 -74

No files matched your search

+121 -68
View File
@@ -427,12 +427,69 @@ pub struct PageOrigin {
pub v_offset: i64,
}
fn write_type0_font(
objects: &mut Vec<Vec<u8>>,
face: &'static PdfFace,
slot: usize,
used: &BTreeSet<char>,
) -> usize {
let type0_id = objects.len() + 1;
let cid_id = type0_id + 1;
let descriptor_id = type0_id + 2;
let file_id = type0_id + 3;
let tounicode_id = type0_id + 4;
let base = face.base;
objects.push(
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{base} /Encoding /Identity-H /DescendantFonts [{cid_id} 0 R] /ToUnicode {tounicode_id} 0 R >>"
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{base} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor_id} 0 R /DW 500 /W {} >>",
cid_widths(face, slot, used)
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /FontDescriptor /FontName /{base} /Flags 32 /FontBBox [-500 -300 1200 1000] /ItalicAngle {} /Ascent 900 /Descent -250 /CapHeight 700 /StemV 80 /FontFile2 {file_id} 0 R >>",
face.italic_angle
)
.into_bytes(),
);
let font_bytes = crate::subset::subset_font(face.bytes, face_font(face), used);
let compressed = deflate(&font_bytes);
let mut font_stream = format!(
"<< /Length {} /Length1 {} /Filter /FlateDecode >>\nstream\n",
compressed.len(),
font_bytes.len()
)
.into_bytes();
font_stream.extend_from_slice(&compressed);
font_stream.extend_from_slice(b"\nendstream");
objects.push(font_stream);
let cmap = tounicode_cmap(face, used);
let compressed_cmap = deflate(&cmap);
let mut cmap_object = format!(
"<< /Length {} /Filter /FlateDecode >>\nstream\n",
compressed_cmap.len()
)
.into_bytes();
cmap_object.extend_from_slice(&compressed_cmap);
cmap_object.extend_from_slice(b"\nendstream");
objects.push(cmap_object);
type0_id
}
fn page_content(
list: &DisplayList,
height: i64,
image_names: &BTreeMap<usize, String>,
faces: &'static [PdfFace; FACE_COUNT],
cm_codes: &[Option<&BTreeMap<char, u8>>],
fallback_ids: &[usize; FACE_COUNT],
origin: PageOrigin,
) -> String {
let mut content = String::from("q\n0 0 0 rg\n");
@@ -452,10 +509,12 @@ fn page_content(
text,
font,
} => {
let operand = match cm_codes
.get(*font as usize)
let slot = *font as usize;
let covered = cm_codes
.get(slot)
.and_then(|entry| entry.as_ref())
{
.filter(|codes| text.chars().all(|character| codes.contains_key(&character)));
let (operand, resource) = match covered {
Some(codes) => {
let mut literal = String::from("(");
for character in text.chars() {
@@ -464,13 +523,20 @@ fn page_content(
}
}
literal.push(')');
literal
(literal, font_resource(*font).to_string())
}
_ => format!("<{}>", glyph_hex(face(*font, faces), text)),
None if fallback_ids[slot] != 0 => (
format!("<{}>", glyph_hex(face(*font, faces), text)),
format!("T{}", slot + 1),
),
None => (
format!("<{}>", glyph_hex(face(*font, faces), text)),
font_resource(*font).to_string(),
),
};
content.push_str(&format!(
"BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n",
font_resource(*font),
resource,
pt(*size),
pt(*x),
pt(height - *y),
@@ -639,9 +705,6 @@ fn write_pdf(
.collect();
return Some((font, codes));
}
if !font.covers(used_chars[slot].iter().copied()) {
return None;
}
let codes = used_chars[slot]
.iter()
.filter_map(|character| font.code_for(*character).map(|code| (*character, code)))
@@ -653,6 +716,16 @@ fn write_pdf(
.iter()
.map(|entry| entry.as_ref().map(|(_, codes)| codes))
.collect();
let mut fallback_chars: [BTreeSet<char>; FACE_COUNT] = Default::default();
for slot in 0..FACE_COUNT {
if let Some((_, codes)) = &cm_faces[slot] {
for character in &used_chars[slot] {
if !codes.contains_key(character) {
fallback_chars[slot].insert(*character);
}
}
}
}
let minimal = pages.iter().all(|page| {
page.items.iter().all(|item| match item {
DisplayItem::Text { text, .. } => text.chars().all(minimal_text_char),
@@ -661,6 +734,7 @@ fn write_pdf(
});
let faces: &'static [PdfFace; FACE_COUNT] = if minimal { &MIN_FACES } else { &FULL_FACES };
let mut font_ids = [0usize; FACE_COUNT];
let mut fallback_font_ids = [0usize; FACE_COUNT];
for (slot, face) in faces.iter().enumerate() {
if !used_faces[slot] {
continue;
@@ -740,56 +814,13 @@ fn write_pdf(
stream.extend_from_slice(&font.program);
stream.extend_from_slice(b"\nendstream");
objects.push(stream);
if !fallback_chars[slot].is_empty() {
fallback_font_ids[slot] =
write_type0_font(&mut objects, face, slot, &fallback_chars[slot]);
}
continue;
}
let type0_id = objects.len() + 1;
let cid_id = type0_id + 1;
let descriptor_id = type0_id + 2;
let file_id = type0_id + 3;
let tounicode_id = type0_id + 4;
font_ids[slot] = type0_id;
let base = face.base;
objects.push(
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{base} /Encoding /Identity-H /DescendantFonts [{cid_id} 0 R] /ToUnicode {tounicode_id} 0 R >>"
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{base} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor_id} 0 R /DW 500 /W {} >>",
cid_widths(face, slot, &used_chars[slot])
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /FontDescriptor /FontName /{base} /Flags 32 /FontBBox [-500 -300 1200 1000] /ItalicAngle {} /Ascent 900 /Descent -250 /CapHeight 700 /StemV 80 /FontFile2 {file_id} 0 R >>",
face.italic_angle
)
.into_bytes(),
);
let font_bytes = crate::subset::subset_font(face.bytes, face_font(face), &used_chars[slot]);
let compressed = deflate(&font_bytes);
let mut font_stream = format!(
"<< /Length {} /Length1 {} /Filter /FlateDecode >>\nstream\n",
compressed.len(),
font_bytes.len()
)
.into_bytes();
font_stream.extend_from_slice(&compressed);
font_stream.extend_from_slice(b"\nendstream");
objects.push(font_stream);
let cmap = tounicode_cmap(face, &used_chars[slot]);
let compressed_cmap = deflate(&cmap);
let mut cmap_object = format!(
"<< /Length {} /Filter /FlateDecode >>\nstream\n",
compressed_cmap.len()
)
.into_bytes();
cmap_object.extend_from_slice(&compressed_cmap);
cmap_object.extend_from_slice(b"\nendstream");
objects.push(cmap_object);
font_ids[slot] = write_type0_font(&mut objects, face, slot, &used_chars[slot]);
}
let mut kids = Vec::new();
@@ -812,7 +843,16 @@ fn write_pdf(
.join(" ");
let fonts = (0..FACE_COUNT)
.filter(|slot| used_faces[*slot])
.map(|slot| format!("/F{} {} 0 R", slot + 1, font_ids[slot]))
.flat_map(|slot| {
let mut entries = Vec::new();
if font_ids[slot] != 0 {
entries.push(format!("/F{} {} 0 R", slot + 1, font_ids[slot]));
}
if fallback_font_ids[slot] != 0 {
entries.push(format!("/T{} {} 0 R", slot + 1, fallback_font_ids[slot]));
}
entries
})
.collect::<Vec<_>>()
.join(" ");
let resources = if used.is_empty() {
@@ -862,7 +902,15 @@ fn write_pdf(
for (index, slot) in &used {
names.insert(*index, format!("Im{slot}"));
}
let content = page_content(list, height, &names, faces, &cm_views, origin);
let content = page_content(
list,
height,
&names,
faces,
&cm_views,
&fallback_font_ids,
origin,
);
objects.push(
format!(
"<< /Length {} >>\nstream\n{}endstream",
@@ -1204,19 +1252,24 @@ mod type1_pdf_tests {
}
#[test]
fn type1_backend_falls_back_for_uncovered_characters() {
fn type1_backend_mixes_type1_and_fallback_fonts() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "café".to_string(),
font: FontFace::Roman,
};
list.items.clear();
for (index, character) in "café".chars().enumerate() {
list.items.push(DisplayItem::Text {
x: index as i64 * 20 * 65_536,
y: 800_000,
size: 655_360,
text: character.to_string(),
font: FontFace::Roman,
});
}
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(!text.contains("/BaseFont /CMR10"), "{text}");
assert!(text.contains("/BaseFont /CMR10"), "{text}");
assert!(text.contains("(\\143)"), "{text}");
assert!(text.contains("/Subtype /Type0"), "{text}");
assert!(text.contains("/T1 "), "{text}");
}
#[test]
+28
View File
@@ -59,6 +59,34 @@ fn paragraph(id: u64, marker: &str) -> Unit {
Unit::paragraph_with_style(id, text, body_style())
}
#[test]
fn accented_text_keeps_type1_ascii_and_falls_back_per_glyph() {
let mut document = Document::new(
1,
vec![Unit::paragraph_with_style(
1,
"caf\u{e9}".to_string(),
body_style(),
)],
);
document.page_goal = 200 * 65_536;
let engine = Engine::layout_paged(&document).expect("paged layout");
let lists: Vec<_> = engine
.pages()
.iter()
.map(|page| page.display_list())
.collect();
let pdf = display_lists_to_pdf_with_cm_type1(
&lists,
300 * 65_536,
300 * 65_536,
PageOrigin::default(),
);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMR10"), "{text}");
assert!(text.contains("/Subtype /Type0"), "{text}");
}
#[test]
fn route_d_article_exports_pdf_and_reflows_only_the_edited_page() {
let mut document = Document::new(