Shape and render explicit OpenType fonts in native Unicode jobs

This commit is contained in:
gloamxun committed 2026-11-21 10:35:03 +08:00
1 parent 3caf1eced2
commit 70822cbd94
33 files changed
+1255 -80

No files matched your search

+45 -11
View File
@@ -25,6 +25,8 @@ pub(crate) mod native_text;
pub(crate) mod objects;
#[path = "pdf_pk.rs"]
mod pk_fonts;
#[path = "pdf_opentype.rs"]
mod opentype_fonts;
const FACE_COUNT: usize = 17;
@@ -356,14 +358,19 @@ fn type1_tounicode_texts(by_code: &BTreeMap<u8, String>) -> Vec<u8> {
type1_tounicode_hex(&hex)
}
fn type1_tounicode_hex(by_code: &BTreeMap<u8, String>) -> Vec<u8> {
let mut map = String::from(
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<00> <FF>\nendcodespacerange\n",
to_unicode_map(by_code, 2)
}
fn to_unicode_map<T: Ord + std::fmt::UpperHex>(by_code: &BTreeMap<T, String>, digits: usize) -> Vec<u8> {
let max_code = "F".repeat(digits);
let min_code = "0".repeat(digits);
let mut map = format!(
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<{min_code}> <{max_code}>\nendcodespacerange\n",
);
let entries: Vec<_> = by_code.iter().collect();
for chunk in entries.chunks(100) {
map.push_str(&format!("{} beginbfchar\n", chunk.len()));
for (slot, text) in chunk {
map.push_str(&format!("<{slot:02X}> <{text}>\n"));
map.push_str(&format!("<{slot:0digits$X}> <{text}>\n"));
}
map.push_str("endbfchar\n");
}
@@ -687,6 +694,7 @@ fn page_content(
cm_codes: &[Option<&BTreeMap<char, u8>>],
fallback_ids: &[usize; FACE_COUNT],
origin: PageOrigin,
opentype: &BTreeMap<crate::execution::FontId, opentype_fonts::EmbeddedFont>,
) -> Vec<u8> {
let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits);
let pt = |n: i64| {
@@ -724,7 +732,11 @@ fn page_content(
}
let mut native_text: Option<NativeTextRun> = None;
let mut tex_text: Option<native_text::NativeText> = None;
let mut opentype_text = None;
for (index, item) in list.items.iter().enumerate() {
if opentype_text.is_some() && !matches!(item, DisplayItem::OpenTypeGlyph { .. }) {
opentype_fonts::TextRun::finish(&mut opentype_text, &mut content);
}
if let DisplayItem::PdfTextSpace { x, y, operation } = item {
if let Some(dedicated) = list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref())
&& *operation == crate::pdf_device::text_spaces::SpaceOperation::Explicit
@@ -815,6 +827,12 @@ fn page_content(
let px = |x| pt(x - h);
let py = |y| pt(height - y - v);
match item {
DisplayItem::OpenTypeGlyph { x, y, size, font, glyph, text, .. } => {
opentype[&font.id].paint(
&mut opentype_text, &mut content, font.id, *glyph, text,
*size, *x - h, height - *y - v, list.units.bp(1),
);
}
DisplayItem::NativeGlyph {
x,
y,
@@ -1090,6 +1108,7 @@ fn page_content(
}
}
}
opentype_fonts::TextRun::finish(&mut opentype_text, &mut content);
NativeTextRun::flush(&mut native_text, &mut content);
native_text::NativeText::finish(&mut tex_text, &mut content);
content.push_str("Q\n");
@@ -1231,7 +1250,7 @@ pub fn display_lists_to_pdf_with_paper(
None,
None,
&mut Vec::new(),
)
).expect("valid PDF display lists")
}
fn descendant_count(children: &HashMap<usize, Vec<usize>>, node: usize) -> usize {
@@ -1264,7 +1283,7 @@ pub fn display_lists_to_pdf_with_cm_type1(
None,
None,
&mut Vec::new(),
)
).expect("valid PDF display lists")
}
/// Strict token-kernel output: every glyph has its measured native resource
@@ -1424,7 +1443,7 @@ fn native_pdf(
unicode,
resources,
&mut diagnostics,
);
)?;
Ok(NativePdfDocument { bytes, diagnostics })
}
@@ -1447,7 +1466,7 @@ pub fn display_lists_to_pdf_with_truetype_and_metadata(
None,
None,
&mut Vec::new(),
)
).expect("valid PDF display lists")
}
/// Write PDFs with Computer Modern Type1 outlines and a document Info dictionary.
@@ -1469,7 +1488,7 @@ pub fn display_lists_to_pdf_with_cm_type1_and_metadata(
None,
None,
&mut Vec::new(),
)
).expect("valid PDF display lists")
}
fn write_math_font(
@@ -1947,13 +1966,14 @@ fn write_pdf(
unicode: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
resources: Option<crate::pdf_device::page_resources::ResourceOutput>,
diagnostics: &mut Vec<String>,
) -> Vec<u8> {
) -> Result<Vec<u8>, String> {
let width = page_width;
let height = page_height;
let mut objects: Vec<Vec<u8>> = Vec::new();
objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec());
objects.push(Vec::new()); // pages object filled below
// Native math uses exact slots and optical masters, independent of the
// document's Times/Liberation text backend and Unicode face remapping.
let mut math_used: BTreeMap<crate::math_font::MathFontId, BTreeMap<u8, char>> = BTreeMap::new();
@@ -1980,6 +2000,7 @@ fn write_pdf(
let mut native_used = BTreeMap::new();
let mut type1_names = HashSet::new();
let mut type1_descriptors = HashMap::new();
let mut opentype_used = opentype_fonts::UsedFonts::default();
for page in pages {
for item in &page.items {
if let DisplayItem::NativeGlyph {
@@ -2013,9 +2034,12 @@ fn write_pdf(
"native font ids from different jobs cannot share a PDF"
);
entry.2.insert(*slot, *character);
} else if let DisplayItem::OpenTypeGlyph { font, glyph, text, .. } = item {
opentype_used.observe(font, *glyph, text)?;
}
}
}
let opentype = opentype_used.write(&mut objects, final_compression.unwrap_or(0).clamp(0, 9) as u8)?;
for plan in pages.iter().filter_map(|page| page.pdf_space_plan.as_ref()) {
for id in &plan.in_font {
native_used.get_mut(id).expect("painted space font").2.insert(b' ', ' ');
@@ -2333,6 +2357,15 @@ fn write_pdf(
for (face, id) in &native_font_ids {
fonts.push_str(&format!(" /N{} {id} 0 R", face.index()));
}
if !opentype.is_empty() {
let open_fonts: BTreeSet<_> = list.items.iter().filter_map(|item| match item {
DisplayItem::OpenTypeGlyph { font, .. } => Some(font.id),
_ => None,
}).collect();
for id in open_fonts {
fonts.push_str(&format!(" /U{} {} 0 R", id.index(), opentype[&id].object));
}
}
let resources = if xobjects.is_empty() {
format!("<< /Font << {fonts} >> >>")
} else {
@@ -2421,6 +2454,7 @@ fn write_pdf(
&cm_views,
&fallback_font_ids,
origin,
&opentype,
);
objects.push(objects::stream(
"",
@@ -2717,7 +2751,7 @@ fn write_pdf(
.as_ref()
.expect("validated native PDF options")
.file;
return objects::serialize(&objects, Some(objects.len()), options, level.max(0).min(9) as u8);
return Ok(objects::serialize(&objects, Some(objects.len()), options, level.max(0).min(9) as u8));
}
let info_ref = match metadata_object(metadata) {
@@ -2751,7 +2785,7 @@ fn write_pdf(
)
.as_bytes(),
);
pdf
Ok(pdf)
}
/// Write one page; kept for the single-page spike and tests.