From a90d53c992f8e916d637ab640cc81781d60c76d9 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Thu, 26 Nov 2026 15:39:14 +0800 Subject: [PATCH] Remap Type1C fonts in imported pdfTeX pages --- .../src/pdf_image/imported_fonts.rs | 109 ++++++++++++------ crates/texrra-tex-core/src/type1_outline.rs | 65 ++++++++--- docs/P2_M1_PROGRESS.md | 35 ++++++ 3 files changed, 162 insertions(+), 47 deletions(-) diff --git a/crates/texrra-tex-core/src/pdf_image/imported_fonts.rs b/crates/texrra-tex-core/src/pdf_image/imported_fonts.rs index b13833f..32c6925 100644 --- a/crates/texrra-tex-core/src/pdf_image/imported_fonts.rs +++ b/crates/texrra-tex-core/src/pdf_image/imported_fonts.rs @@ -1,8 +1,9 @@ //! Replacement of fonts in the root resources of an included pdfTeX page. use super::{Graph, Part, PdfImage, number, pdf_name, resolved}; -use crate::type1::{Type1Font, builtin_encoding}; +use crate::type1::{Type1Font, builtin_encoding, standard_encoding}; use lopdf::{Dictionary, Document, Object, Stream}; -use std::collections::BTreeSet; +use read_fonts::ps::cff::CffFontRef; +use std::{borrow::Cow, collections::BTreeSet}; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub(super) struct ImportedType1 { @@ -71,10 +72,7 @@ pub(super) fn capture( let Ok(descriptor) = resolved(doc, descriptor)?.as_dict() else { continue; }; - let Ok(file) = descriptor.get(b"FontFile") else { - continue; - }; - let Ok(file) = resolved(doc, file)?.as_stream() else { + let Some(file) = EmbeddedType1::from_descriptor(doc, descriptor)? else { continue; }; let stem_v = descriptor @@ -94,10 +92,76 @@ pub(super) fn capture( Ok(captured) } +enum EmbeddedType1<'a> { + Type1(&'a Stream), + Type1C(&'a Stream), +} + +impl<'a> EmbeddedType1<'a> { + fn from_descriptor(doc: &'a Document, descriptor: &'a Dictionary) -> Result, String> { + if let Ok(file) = descriptor.get(b"FontFile") + && let Ok(stream) = resolved(doc, file)?.as_stream() + { + return Ok(Some(Self::Type1(stream))); + } + if let Ok(file) = descriptor.get(b"FontFile3") + && let Ok(stream) = resolved(doc, file)?.as_stream() + && let Ok(subtype) = stream.dict.get(b"Subtype") + && resolved(doc, subtype)?.as_name().ok() == Some(b"Type1C") + { + return Ok(Some(Self::Type1C(stream))); + } + Ok(None) + } + + fn glyph_names(&self, doc: &Document) -> Result>, String> { + let stream = match self { + Self::Type1(stream) | Self::Type1C(stream) => *stream, + }; + let bytes = if stream.dict.has(b"Filter") { + Cow::Owned(stream.decompressed_content().map_err(|error| error.to_string())?) + } else { + Cow::Borrowed(stream.content.as_slice()) + }; + match self { + Self::Type1(_) => { + let length = stream.dict.get(b"Length1").map_err(|error| error.to_string())?; + let length = resolved(doc, length)? + .as_i64() + .ok() + .and_then(|n| usize::try_from(n).ok()) + .ok_or("invalid included Type1 Length1")?; + let header = bytes.get(..length).ok_or("included Type1 header is truncated")?; + Ok(builtin_encoding(header)?.into_iter().map(String::into_bytes).collect()) + } + Self::Type1C(_) => { + let cff = CffFontRef::new_cff(&bytes, 0, None) + .map_err(|error| format!("invalid included Type1C program: {error:?}"))?; + if cff.is_cid() { + return Err("expected a name-keyed Type1C font in included PDF".into()); + } + let encoding = cff.encoding().ok_or("invalid encoding in included Type1C program")?; + Ok((0..=255) + .map(|code| { + // The PDF reader fills gaps in the embedded CFF encoding + // before applying the PDF font dictionary's Differences. + encoding.map(code) + .and_then(|glyph| encoding.charset().string_id(glyph)) + .and_then(|sid| cff.string(sid)) + .or_else(|| standard_encoding(code).map(str::as_bytes)) + .unwrap_or(b".notdef") + .to_vec() + }) + .collect()) + } + } + } +} + fn font_template( graph: &mut Graph<'_>, dict: &Dictionary, - file: &Stream, + file: EmbeddedType1<'_>, ) -> Result, String> { let doc = graph.doc; let mut replacement = dict.clone(); @@ -118,7 +182,7 @@ fn font_template( fn replace_implicit_encoding( doc: &Document, font: &Dictionary, - program: &Stream, + program: EmbeddedType1<'_>, ) -> Result, String> { let encoding = font .get(b"Encoding") @@ -132,30 +196,7 @@ fn replace_implicit_encoding( None | Some(Object::Null) => None, _ => return Err("invalid Type1 encoding in included PDF".into()), }; - let length = program - .dict - .get(b"Length1") - .map_err(|error| error.to_string())?; - let length = resolved(doc, length)? - .as_i64() - .ok() - .and_then(|n| usize::try_from(n).ok()) - .ok_or("invalid included Type1 Length1")?; - let bytes = if program.dict.has(b"Filter") { - program - .decompressed_content() - .map_err(|error| error.to_string())? - } else { - program.content.clone() - }; - let mut names: Vec> = builtin_encoding( - bytes - .get(..length) - .ok_or("included Type1 header is truncated")?, - )? - .into_iter() - .map(String::into_bytes) - .collect(); + let mut names = program.glyph_names(doc)?; if let Some(differences) = differences { let differences = resolved(doc, differences)? .as_array() @@ -232,12 +273,12 @@ impl PdfImage { let [left, bottom, right, top] = program.bbox; let angle = &program.italic_angle; + let stem_v = crate::type1_outline::pdftex_stem_v(&program)?.unwrap_or(entry.stem_v); let mut body = b"<< /Type /FontDescriptor /FontName ".to_vec(); body.extend(pdf_name(program.name.as_bytes())); body.extend(format!( " /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} \ - /Ascent {top} /Descent {bottom} /CapHeight {top} /StemV {} /FontFile ", - entry.stem_v, + /Ascent {top} /Descent {bottom} /CapHeight {top} /StemV {stem_v} /FontFile ", ).into_bytes()); image.objects.push(vec![ Part::Bytes(body), diff --git a/crates/texrra-tex-core/src/type1_outline.rs b/crates/texrra-tex-core/src/type1_outline.rs index ae1f254..af40f9e 100644 --- a/crates/texrra-tex-core/src/type1_outline.rs +++ b/crates/texrra-tex-core/src/type1_outline.rs @@ -101,6 +101,10 @@ impl<'a> Tokens<'a> { if !matches!(op.as_str(), "RD" | "-|") { return Err(format!("unsupported Type1 binary reader: {op}")); } + Ok(self.binary_data(n)?.to_vec()) + } + + fn binary_data(&mut self, n: usize) -> Result<&'a [u8], String> { let whitespace = *self .data .get(self.at) @@ -119,8 +123,7 @@ impl<'a> Tokens<'a> { let bytes = self .data .get(self.at..end) - .ok_or("truncated Type1 binary program")? - .to_vec(); + .ok_or("truncated Type1 binary program")?; self.at = end; Ok(bytes) } @@ -145,19 +148,55 @@ pub struct Type1Outlines { std_vw: Option, force_bold: bool, } +fn private_dictionary(font: &Type1Font) -> Result, String> { + let encrypted = font + .program + .get( + font.length1 + ..font + .length1 + .checked_add(font.length2) + .ok_or("Type1 length overflow")?, + ) + .ok_or("Type1 segment lengths outside program")?; + decrypt(encrypted, 55665, 4) +} + +pub(crate) fn pdftex_stem_v(font: &Type1Font) -> Result, String> { + fn scan(data: &[u8]) -> Result, String> { + let mut tokens = Tokens::new(data); + let mut stem_v = None; + let mut length = None; + while let Some(token) = tokens.next()? { + match token.as_str() { + "/StdVW" => { + let mut width = tokens.required()?; + if matches!(width.as_str(), "[" | "{") { + width = tokens.required()?; + } + let width: f32 = width.parse().map_err(|_| "invalid Type1 StdVW")?; + if !width.is_finite() { + return Err("nonfinite Type1 StdVW".into()); + } + stem_v = Some(width as i32); + length = None; + } + "RD" | "-|" if length.is_some() => { + tokens.binary_data(length.take().unwrap())?; + } + "/CharStrings" => break, + _ => length = token.parse::().ok(), + } + } + Ok(stem_v) + } + let header = font.program.get(..font.length1).ok_or("invalid Type1 header")?; + Ok(scan(&private_dictionary(font)?)?.or(scan(header)?)) +} + impl Type1Outlines { pub fn parse(font: &Type1Font) -> Result { - let encrypted = font - .program - .get( - font.length1 - ..font - .length1 - .checked_add(font.length2) - .ok_or("Type1 length overflow")?, - ) - .ok_or("Type1 segment lengths outside program")?; - let private = decrypt(encrypted, 55665, 4)?; + let private = private_dictionary(font)?; let mut tokens = Tokens { data: &private, at: 0, diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index c8b9382..416fd55 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,41 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### pdfTeX 导入页面的 Type1C 编码和实际笔画宽度 + +根资源中的间接 Type1 字体可以从 FontFile3 的 Type1C 流进入 +现有 PostScript 映射流程。命中时使用作业实际读取的 PFB,保留源字宽 +和 ToUnicode。隐式编码从源 CFF 的真实编码和字符集恢复槽位字形名, +按参考用 StandardEncoding 填补空槽,再应用 PDF 的 Differences。 +显式编码按源字典保留。选择复制、未命中映射或 FontFile3 使用 +OpenType 子类型时保留源程序。 +[参考字体替换](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftoepdf.cc#L377-L412) +[参考 Xpdf 编码合并](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/libs/xpdf/xpdf-src/xpdf/GfxFont.cc#L1111-L1177) + +实际 PFB 的 StdVW 优先进入导入字体的 StemV。原始程序无此值时 +沿用源 PDF 值。复用既有 Type1 解密和词法读取,按长度越过二进制 +子程序。旧 Type1 导入也使用这条路径。 +[pdfTeX 的度量键](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/ptexlib.h#L320-L332) +[pdfTeX 读取实际 Type1 参数](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writet1.c#L685-L710) + +九种配置覆盖由真实 CMR10 生成的 Type1C 图像、Latin Modern +标准编码 CFF、压缩流、原有 Type1 导入、保留原字体及无 StdVW +分支。字体类别、描述符度量、词框和 144 DPI 灰度一致,核对实际 +读取的 PFB 指纹与嵌入程序。CMR10 与 Latin Modern 的映射 PFB +都给出 StemV 69。去掉实际 PFB 中的 StdVW 定义时,输出取原 CMR +图的 108。四项既有 Type1 字形回归通过。 + +四次修订依次更改图像编码、移除映射、恢复映射和更换同一路径的 +物理 PFB。每次复用 99 步,只替换第二页,PDF、SVG、来源映射及 +生成文件与同初始状态的独立全量一致。 + +保留两项下一入口。Latin Modern 请求 A/V 子集时,两端词框与 +光栅相同,参考嵌入 15554 字节的字体子集,原生嵌入 119215 字节 +的完整程序。同一 CMR10 用于正文和导入页时,参考只写出一个共享 +描述符,原生写出两个。后续需汇总实际字形范围,写出子集并共享 +描述符。回执 target/p3-imported-type1c/receipt.json 的 SHA-256 +为 74e8a4acb9ff02aff5675efadfdccaeb25345c4410b6c03e4eb4979b14c4b9de。 + ### pdfTeX 颜色栈的文字游标与 CAS 双栏正文 内置栈和 direct 模式仅提交已积累的文字串,保留当前 PDF 文字对象、