Remap Type1C fonts in imported pdfTeX pages

This commit is contained in:
gloamxun committed 2026-11-26 15:39:14 +08:00
1 parent f88a16d101
commit a90d53c992
3 files changed
+162 -47

No files matched your search

@@ -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<Option<Self>, 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<Vec<Vec<u8>>, 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<Vec<Part>, 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<Option<Dictionary>, 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<Vec<u8>> = 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),
+52 -13
View File
@@ -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<f64>,
force_bold: bool,
}
fn private_dictionary(font: &Type1Font) -> Result<Vec<u8>, 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<Option<i32>, String> {
fn scan(data: &[u8]) -> Result<Option<i32>, 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::<usize>().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<Self, 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")?;
let private = decrypt(encrypted, 55665, 4)?;
let private = private_dictionary(font)?;
let mut tokens = Tokens {
data: &private,
at: 0,