Write physical Type 1 subsets for imported PDF fonts
This commit is contained in:
1 parent
a90d53c992
commit
5edd4ae4ec
8 files changed
+384
-22
No files matched your search
@@ -16,6 +16,8 @@ pub(super) struct MapEntry {
|
||||
pub from: PathBuf,
|
||||
pub version: Option<ResourceVersion>,
|
||||
file: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
subset: bool,
|
||||
pub encoding: Option<String>,
|
||||
postscript_name: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -91,6 +93,7 @@ fn parse_map_line(
|
||||
from: from.to_path_buf(),
|
||||
version: version.cloned(),
|
||||
file: None,
|
||||
subset: false,
|
||||
encoding: None,
|
||||
postscript_name: false,
|
||||
ps_name: None,
|
||||
@@ -124,6 +127,7 @@ fn parse_map_line(
|
||||
entry.encoding = Some(path.to_owned());
|
||||
} else if !path.is_empty() {
|
||||
entry.file = Some(path.to_owned());
|
||||
entry.subset = !value.starts_with("<<");
|
||||
}
|
||||
} else if index == 0 && !value.as_bytes()[0].is_ascii_digit() {
|
||||
entry.postscript_name = true;
|
||||
@@ -264,7 +268,7 @@ impl JobFontMap {
|
||||
|
||||
pub(super) fn imported_type1_program(
|
||||
&mut self, name: &str, from: &Path, files: &mut impl SourceProvider,
|
||||
) -> Result<Option<(crate::type1::Type1Font, i32)>, String> {
|
||||
) -> Result<Option<(crate::type1::Type1Font, i32, bool)>, String> {
|
||||
let (name, transform) = imported_postscript_name(name);
|
||||
if self.bindings.is_none() {
|
||||
self.initialize(true, from, files)?;
|
||||
@@ -282,7 +286,7 @@ impl JobFontMap {
|
||||
self.used_names.insert(tfm.clone());
|
||||
}
|
||||
self.used_postscript.insert(key);
|
||||
Ok(Some((font, entry.descriptor_flags.unwrap_or(4))))
|
||||
Ok(Some((font, entry.descriptor_flags.unwrap_or(4), entry.subset)))
|
||||
}
|
||||
|
||||
pub(super) fn command(
|
||||
@@ -471,5 +475,6 @@ pub(super) fn dedicated_space_map(font: &NativeFont) -> MapEntry {
|
||||
ps_name: None,
|
||||
descriptor_flags: None,
|
||||
transform: Type1Transform::default(),
|
||||
subset: false,
|
||||
}
|
||||
}
|
||||
@@ -408,7 +408,7 @@ impl JobVirtualFonts {
|
||||
|
||||
pub(crate) fn imported_type1_program(
|
||||
&mut self, name: &str, from: &std::path::Path, files: &mut impl SourceProvider,
|
||||
) -> Result<Option<(crate::type1::Type1Font, i32)>, String> {
|
||||
) -> Result<Option<(crate::type1::Type1Font, i32, bool)>, String> {
|
||||
self.font_map.imported_type1_program(name, from, files)
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ pub(super) struct ImportedType1 {
|
||||
index: usize,
|
||||
postscript_name: String,
|
||||
stem_v: i32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
charset: Option<Vec<u8>>,
|
||||
dictionary: Result<Vec<Part>, String>,
|
||||
}
|
||||
|
||||
@@ -81,11 +83,19 @@ pub(super) fn capture(
|
||||
.and_then(|value| number(doc, value).ok())
|
||||
.unwrap_or(0.0)
|
||||
.round() as i32;
|
||||
let charset = descriptor
|
||||
.get(b"CharSet")
|
||||
.ok()
|
||||
.map(|value| resolved(doc, value))
|
||||
.transpose()?
|
||||
.and_then(|value| value.as_str().ok())
|
||||
.map(<[u8]>::to_vec);
|
||||
let dictionary = font_template(graph, dict, file);
|
||||
captured.push(ImportedType1 {
|
||||
index,
|
||||
postscript_name: postscript_name.to_owned(),
|
||||
stem_v,
|
||||
charset,
|
||||
dictionary,
|
||||
});
|
||||
}
|
||||
@@ -253,16 +263,25 @@ impl PdfImage {
|
||||
|
||||
pub(crate) fn resolve_imported_fonts(
|
||||
&self,
|
||||
mut load: impl FnMut(&str) -> Result<Option<(Type1Font, i32)>, String>,
|
||||
mut load: impl FnMut(&str) -> Result<Option<(Type1Font, i32, bool)>, String>,
|
||||
) -> Result<Option<Self>, String> {
|
||||
let mut result: Option<Self> = None;
|
||||
for entry in &self.imported_fonts {
|
||||
let Some((program, flags)) = load(&entry.postscript_name)? else {
|
||||
let Some((program, flags, allow_subset)) = load(&entry.postscript_name)? else {
|
||||
continue;
|
||||
};
|
||||
let subset = entry.charset.as_deref().filter(|_| allow_subset)
|
||||
.map(|bytes| {
|
||||
let charset = std::str::from_utf8(bytes)
|
||||
.map_err(|_| "invalid glyph name in imported Type1 CharSet")?;
|
||||
let glyphs = charset.split('/').filter(|name| !name.is_empty()).map(str::to_owned).collect();
|
||||
crate::type1_outline::write_subset(&program, &glyphs)
|
||||
})
|
||||
.transpose()?;
|
||||
let font_name = subset.as_ref().map_or(program.name.as_str(), |subset| subset.name.as_str());
|
||||
let mut dictionary = entry.dictionary.clone()?;
|
||||
let mut name = b" /BaseFont ".to_vec();
|
||||
name.extend(pdf_name(program.name.as_bytes()));
|
||||
name.extend(pdf_name(font_name.as_bytes()));
|
||||
name.extend(b" /FontDescriptor ");
|
||||
let image = result.get_or_insert_with(|| self.clone());
|
||||
let descriptor = image.objects.len();
|
||||
@@ -275,25 +294,39 @@ impl PdfImage {
|
||||
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(pdf_name(font_name.as_bytes()));
|
||||
body.extend(format!(
|
||||
" /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} \
|
||||
/Ascent {top} /Descent {bottom} /CapHeight {top} /StemV {stem_v} /FontFile ",
|
||||
/Ascent {top} /Descent {bottom} /CapHeight {top} /StemV {stem_v}",
|
||||
).into_bytes());
|
||||
if let Some(subset) = &subset {
|
||||
use std::fmt::Write as _;
|
||||
let mut charset = String::from(" /CharSet <");
|
||||
for glyph in &subset.glyphs {
|
||||
charset.push_str("2F");
|
||||
for byte in glyph.bytes() {
|
||||
write!(charset, "{byte:02X}").unwrap();
|
||||
}
|
||||
}
|
||||
charset.push('>');
|
||||
body.extend(charset.bytes());
|
||||
}
|
||||
body.extend_from_slice(b" /FontFile ");
|
||||
image.objects.push(vec![
|
||||
Part::Bytes(body),
|
||||
Part::Ref(descriptor + 1),
|
||||
Part::Bytes(b">>".to_vec()),
|
||||
]);
|
||||
let keys = format!(
|
||||
"/Length1 {} /Length2 {} /Length3 {}",
|
||||
program.length1, program.length2, program.length3
|
||||
let ([header, private, trailer], bytes) = subset.as_ref().map_or(
|
||||
([program.length1, program.length2, program.length3], program.program.as_slice()),
|
||||
|subset| ([subset.length1, subset.program.len() - subset.length1, 0], subset.program.as_slice()),
|
||||
);
|
||||
let keys = format!("/Length1 {header} /Length2 {private} /Length3 {trailer}");
|
||||
image
|
||||
.objects
|
||||
.push(vec![Part::Bytes(crate::pdf::objects::stream(
|
||||
&keys,
|
||||
&program.program,
|
||||
bytes,
|
||||
0,
|
||||
))]);
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ pub(crate) fn font_matrix(header: &str) -> Result<(Range<usize>, [f64; 6]), Stri
|
||||
Ok((start..start + text.len(), matrix))
|
||||
}
|
||||
|
||||
fn header_field(header: &str, key: &str) -> Option<Range<usize>> {
|
||||
pub(super) fn header_field(header: &str, key: &str) -> Option<Range<usize>> {
|
||||
let rest = header.split_once(key)?.1.trim_start();
|
||||
let value = rest.split_whitespace().next()?;
|
||||
let start = header.len() - rest.len();
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
//! the original hinted program; SVG executes its actual paths and components.
|
||||
use crate::type1::{Type1Font, font_matrix, standard_encoding};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
mod subset;
|
||||
pub(crate) use subset::write_subset;
|
||||
use subset::{GlyphUse, ProgramRanges, SubrRange};
|
||||
fn decrypt(data: &[u8], mut key: u16, skip: usize) -> Result<Vec<u8>, String> {
|
||||
if data.len() < skip {
|
||||
return Err("truncated Type1 cipher prefix".into());
|
||||
@@ -197,10 +201,15 @@ pub(crate) fn pdftex_stem_v(font: &Type1Font) -> Result<Option<i32>, String> {
|
||||
impl Type1Outlines {
|
||||
pub fn parse(font: &Type1Font) -> Result<Self, String> {
|
||||
let private = private_dictionary(font)?;
|
||||
let mut tokens = Tokens {
|
||||
data: &private,
|
||||
at: 0,
|
||||
};
|
||||
Self::from_private(font, &private, None)
|
||||
}
|
||||
|
||||
fn from_private(
|
||||
font: &Type1Font,
|
||||
private: &[u8],
|
||||
mut ranges: Option<&mut ProgramRanges>,
|
||||
) -> Result<Self, String> {
|
||||
let mut tokens = Tokens::new(private);
|
||||
let (mut len_iv, mut subrs, mut glyphs, mut in_subrs) =
|
||||
(4i32, Vec::new(), BTreeMap::new(), false);
|
||||
let mut std_vw = None;
|
||||
@@ -231,7 +240,12 @@ impl Type1Outlines {
|
||||
}
|
||||
"/ForceBold" => force_bold = tokens.required()? == "true",
|
||||
"/Subrs" => {
|
||||
let start = tokens.at;
|
||||
let count = tokens.number()?;
|
||||
if let Some(ranges) = ranges.as_deref_mut() {
|
||||
ranges.subr_size = Some((count, start..tokens.at));
|
||||
ranges.subrs.clear();
|
||||
}
|
||||
if count > 65536 {
|
||||
return Err("Type1 subroutine capacity exceeded".into());
|
||||
}
|
||||
@@ -242,16 +256,42 @@ impl Type1Outlines {
|
||||
in_subrs = true;
|
||||
}
|
||||
"dup" if in_subrs => {
|
||||
let assignment_start = tokens.at - token.len();
|
||||
let index = tokens.number()?;
|
||||
let length_start = tokens.at;
|
||||
let n = tokens.number()?;
|
||||
let length_end = tokens.at;
|
||||
let bytes = tokens.binary(n)?;
|
||||
if let Some(ranges) = ranges.as_deref_mut() {
|
||||
ranges.subrs.push(SubrRange {
|
||||
index,
|
||||
length: length_start..length_end,
|
||||
bytes: tokens.at - n..tokens.at,
|
||||
assignment: subset::subr_assignment_end(&tokens)
|
||||
.map(|end| assignment_start..end),
|
||||
});
|
||||
}
|
||||
*subrs
|
||||
.get_mut(index)
|
||||
.ok_or("Type1 Subrs index outside array")? = Some(bytes);
|
||||
}
|
||||
"ND" | "|-" | "def" if in_subrs => in_subrs = false,
|
||||
"/UniqueID" if ranges.is_some() && !in_subrs => {
|
||||
let start = tokens.at - token.len();
|
||||
tokens.required()?.parse::<i32>().map_err(|_| "invalid Type1 UniqueID")?;
|
||||
if !matches!(tokens.required()?.as_str(), "def" | "ND" | "|-") {
|
||||
return Err("unsupported Type1 UniqueID definition".into());
|
||||
}
|
||||
if let Some(ranges) = ranges.as_deref_mut() {
|
||||
ranges.unique_ids.push(start..tokens.at);
|
||||
}
|
||||
}
|
||||
"/CharStrings" => {
|
||||
let start = tokens.at;
|
||||
let count = tokens.number()?;
|
||||
if let Some(ranges) = ranges.as_deref_mut() {
|
||||
ranges.glyph_count = start..tokens.at;
|
||||
}
|
||||
if count > 65536 {
|
||||
return Err("Type1 glyph capacity exceeded".into());
|
||||
}
|
||||
@@ -262,9 +302,15 @@ impl Type1Outlines {
|
||||
loop {
|
||||
let token = tokens.required()?;
|
||||
if token == "end" {
|
||||
if let Some(ranges) = ranges.as_deref_mut() {
|
||||
ranges.glyph_end = tokens.at - token.len();
|
||||
}
|
||||
break;
|
||||
}
|
||||
if let Some(name) = token.strip_prefix('/') {
|
||||
if let Some(ranges) = ranges.as_deref_mut() {
|
||||
ranges.glyphs.push((name.to_owned(), tokens.at - token.len()));
|
||||
}
|
||||
let n = tokens.number()?;
|
||||
let bytes = tokens.binary(n)?;
|
||||
glyphs.insert(name.into(), bytes);
|
||||
@@ -281,6 +327,9 @@ impl Type1Outlines {
|
||||
if glyphs.is_empty() {
|
||||
return Err("Type1 CharStrings dictionary is missing".into());
|
||||
}
|
||||
if let Some(ranges) = ranges {
|
||||
ranges.len_iv = len_iv;
|
||||
}
|
||||
if len_iv >= 0 {
|
||||
let skip = len_iv as usize;
|
||||
for program in subrs.iter_mut().flatten().chain(glyphs.values_mut()) {
|
||||
@@ -349,7 +398,7 @@ impl Type1Outlines {
|
||||
let mut include = |y: f64| {
|
||||
bound = Some(bound.map_or(y, |old| if top { old.max(y) } else { old.min(y) }));
|
||||
};
|
||||
for command in self.commands(name, 0, &mut budget)? {
|
||||
for command in self.commands(name, 0, &mut budget, None)? {
|
||||
match command {
|
||||
Command::Move(_, y) | Command::Line(_, y) => include(y),
|
||||
Command::Curve(_, a, _, b, _, c) => {
|
||||
@@ -380,6 +429,7 @@ impl Type1Outlines {
|
||||
name: &str,
|
||||
depth: usize,
|
||||
budget: &mut usize,
|
||||
mut usage: Option<&mut GlyphUse>,
|
||||
) -> Result<Vec<Command>, String> {
|
||||
if depth > 32 {
|
||||
return Err("Type1 composite recursion capacity exceeded".into());
|
||||
@@ -388,8 +438,12 @@ impl Type1Outlines {
|
||||
.glyphs
|
||||
.get(name)
|
||||
.ok_or_else(|| format!("Type1 glyph is missing: {name}"))?;
|
||||
if let Some(usage) = usage.as_deref_mut() {
|
||||
usage.names.insert(name.to_owned());
|
||||
}
|
||||
let mut run = Runner {
|
||||
font: self,
|
||||
usage,
|
||||
stack: Vec::new(),
|
||||
commands: Vec::new(),
|
||||
x: 0.,
|
||||
@@ -406,7 +460,7 @@ impl Type1Outlines {
|
||||
}
|
||||
pub fn glyph_path(&self, name: &str) -> Result<String, String> {
|
||||
let mut budget = 1_000_000;
|
||||
let commands = self.commands(name, 0, &mut budget)?;
|
||||
let commands = self.commands(name, 0, &mut budget, None)?;
|
||||
let point = |x: f64, y: f64| {
|
||||
(
|
||||
(self.matrix[0] * x + self.matrix[2] * y + self.matrix[4]) * 1000.,
|
||||
@@ -464,8 +518,9 @@ impl Command {
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Runner<'a> {
|
||||
struct Runner<'a, 'u> {
|
||||
font: &'a Type1Outlines,
|
||||
usage: Option<&'u mut GlyphUse>,
|
||||
stack: Vec<f64>,
|
||||
commands: Vec<Command>,
|
||||
x: f64,
|
||||
@@ -475,7 +530,7 @@ struct Runner<'a> {
|
||||
flex: bool,
|
||||
other_results: usize,
|
||||
}
|
||||
impl Runner<'_> {
|
||||
impl Runner<'_, '_> {
|
||||
fn pop(&mut self) -> Result<f64, String> {
|
||||
self.stack
|
||||
.pop()
|
||||
@@ -602,6 +657,9 @@ impl Runner<'_> {
|
||||
}
|
||||
10 => {
|
||||
let i = self.integer()?;
|
||||
if let Some(usage) = self.usage.as_deref_mut() {
|
||||
usage.subrs.insert(i);
|
||||
}
|
||||
let sub = self
|
||||
.font
|
||||
.subrs
|
||||
@@ -649,7 +707,8 @@ impl Runner<'_> {
|
||||
}
|
||||
let name = standard_encoding(i as u8)
|
||||
.ok_or("unassigned seac StandardEncoding slot")?;
|
||||
let mut commands = self.font.commands(name, depth + 1, budget)?;
|
||||
let mut commands =
|
||||
self.font.commands(name, depth + 1, budget, self.usage.as_deref_mut())?;
|
||||
for c in &mut commands {
|
||||
c.translate(dx, dy);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
//! Subset an embedded PFB while keeping its original hinting and glyph programs.
|
||||
use super::{Tokens, Type1Outlines, private_dictionary};
|
||||
use crate::type1::{Type1Font, builtin_encoding, header_field};
|
||||
use std::{collections::BTreeSet, fmt::Write as _, ops::Range};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct GlyphUse {
|
||||
pub(super) names: BTreeSet<String>,
|
||||
pub(super) subrs: BTreeSet<usize>,
|
||||
}
|
||||
|
||||
pub(super) struct SubrRange {
|
||||
pub(super) index: usize,
|
||||
pub(super) length: Range<usize>,
|
||||
pub(super) bytes: Range<usize>,
|
||||
pub(super) assignment: Option<Range<usize>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ProgramRanges {
|
||||
pub(super) len_iv: i32,
|
||||
pub(super) glyph_count: Range<usize>,
|
||||
pub(super) glyphs: Vec<(String, usize)>,
|
||||
pub(super) glyph_end: usize,
|
||||
pub(super) subrs: Vec<SubrRange>,
|
||||
pub(super) subr_size: Option<(usize, Range<usize>)>,
|
||||
pub(super) unique_ids: Vec<Range<usize>>,
|
||||
}
|
||||
|
||||
pub(crate) struct SubsetProgram {
|
||||
pub name: String,
|
||||
pub program: Vec<u8>,
|
||||
pub length1: usize,
|
||||
pub glyphs: BTreeSet<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn write_subset(
|
||||
font: &Type1Font,
|
||||
requested: &BTreeSet<String>,
|
||||
) -> Result<SubsetProgram, String> {
|
||||
let private = private_dictionary(font)?;
|
||||
let mut ranges = ProgramRanges::default();
|
||||
let outlines = Type1Outlines::from_private(font, &private, Some(&mut ranges))?;
|
||||
let mut usage = GlyphUse::default();
|
||||
for name in std::iter::once(".notdef").chain(requested.iter().map(String::as_str)) {
|
||||
if outlines.has_glyph(name) && !usage.names.contains(name) {
|
||||
let mut budget = 1_000_000;
|
||||
outlines.commands(name, 0, &mut budget, Some(&mut usage))?;
|
||||
}
|
||||
}
|
||||
if usage.names.is_empty() {
|
||||
return Err("Type1 subset contains no available glyphs".into());
|
||||
}
|
||||
|
||||
let mut edits = Vec::new();
|
||||
let mut kept = 0;
|
||||
let mut end = ranges.glyph_end;
|
||||
for (name, start) in ranges.glyphs.into_iter().rev() {
|
||||
if usage.names.contains(&name) {
|
||||
kept += 1;
|
||||
} else {
|
||||
edits.push((start..end, Vec::new()));
|
||||
}
|
||||
end = start;
|
||||
}
|
||||
edits.push((ranges.glyph_count, format!(" {kept}").into_bytes()));
|
||||
edits.extend(ranges.unique_ids.into_iter().map(|span| (span, Vec::new())));
|
||||
|
||||
// Preserve indices through the last needed slot. The first four slots
|
||||
// contain conventional subroutines used by Type 1 flex and hints.
|
||||
let mut subr_slots = 0;
|
||||
if let Some((original, span)) = ranges.subr_size {
|
||||
subr_slots = original.min(4);
|
||||
for subr in &ranges.subrs {
|
||||
if usage.subrs.contains(&subr.index) || subr.assignment.is_none() {
|
||||
subr_slots = subr_slots.max(subr.index + 1);
|
||||
}
|
||||
}
|
||||
edits.push((span, format!(" {subr_slots}").into_bytes()));
|
||||
}
|
||||
// Unused entries within the retained range become encrypted returns.
|
||||
let stub = if ranges.len_iv < 0 {
|
||||
vec![11]
|
||||
} else {
|
||||
encrypt(
|
||||
std::iter::repeat_n(0, ranges.len_iv as usize).chain([11]),
|
||||
4330,
|
||||
)
|
||||
};
|
||||
for subr in ranges.subrs {
|
||||
if subr.index >= subr_slots
|
||||
&& let Some(span) = subr.assignment.clone()
|
||||
{
|
||||
edits.push((span, Vec::new()));
|
||||
continue;
|
||||
}
|
||||
if subr.index < 4 || usage.subrs.contains(&subr.index) {
|
||||
continue;
|
||||
}
|
||||
let mut replacement = format!(" {}", stub.len()).into_bytes();
|
||||
replacement.extend_from_slice(&private[subr.length.end..subr.bytes.start]);
|
||||
replacement.extend_from_slice(&stub);
|
||||
edits.push((subr.length.start..subr.bytes.end, replacement));
|
||||
}
|
||||
let private = rewrite(&private, edits)?;
|
||||
|
||||
let tag = subset_tag(&font.name, requested);
|
||||
let name = format!("{tag}+{}", font.name);
|
||||
let header = std::str::from_utf8(&font.program[..font.length1])
|
||||
.map_err(|_| "unsupported non-UTF8 Type1 header")?;
|
||||
let mut header = subset_header(header, &name, requested)?;
|
||||
let length1 = header.len();
|
||||
header.extend(encrypt([0; 4].into_iter().chain(private), 55665));
|
||||
usage.names.remove(".notdef");
|
||||
Ok(SubsetProgram {
|
||||
name,
|
||||
program: header,
|
||||
length1,
|
||||
glyphs: usage.names,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn subr_assignment_end(tokens: &Tokens<'_>) -> Option<usize> {
|
||||
let mut end = Tokens {
|
||||
data: tokens.data,
|
||||
at: tokens.at,
|
||||
};
|
||||
match end.required().ok()?.as_str() {
|
||||
"NP" | "|" | "put" => {}
|
||||
"noaccess" if end.required().ok()? == "put" => {}
|
||||
_ => return None,
|
||||
}
|
||||
while end.data.get(end.at).is_some_and(u8::is_ascii_whitespace) {
|
||||
end.at += 1;
|
||||
}
|
||||
Some(end.at)
|
||||
}
|
||||
|
||||
fn subset_header(header: &str, name: &str, glyphs: &BTreeSet<String>) -> Result<Vec<u8>, String> {
|
||||
let name_range = header_field(header, "/FontName").ok_or("missing Type1 FontName")?;
|
||||
let mut edits = vec![(name_range, format!("/{name}").into_bytes())];
|
||||
let mut tokens = Tokens::new(header.as_bytes());
|
||||
while tokens.required()? != "/Encoding" {}
|
||||
let start = tokens.at;
|
||||
if tokens.required()? != "StandardEncoding" {
|
||||
let mut depth = 0usize;
|
||||
loop {
|
||||
match tokens.required()?.as_str() {
|
||||
"{" => depth += 1,
|
||||
"}" => depth = depth.saturating_sub(1),
|
||||
"def" if depth == 0 => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut replacement = " 256 array\n0 1 255 {1 index exch /.notdef put} for\n".to_owned();
|
||||
for (slot, glyph) in builtin_encoding(header.as_bytes())?.into_iter().enumerate() {
|
||||
if glyphs.contains(&glyph) && glyph != ".notdef" {
|
||||
writeln!(replacement, "dup {slot} /{glyph} put").unwrap();
|
||||
}
|
||||
}
|
||||
replacement.push_str("readonly def");
|
||||
edits.push((start..tokens.at, replacement.into_bytes()));
|
||||
}
|
||||
let mut offset = 0;
|
||||
for line in header.split_inclusive('\n') {
|
||||
if line.trim_start().starts_with("/UniqueID ") && line.trim_end().ends_with(" def") {
|
||||
edits.push((offset..offset + line.len(), Vec::new()));
|
||||
}
|
||||
offset += line.len();
|
||||
}
|
||||
rewrite(header.as_bytes(), edits)
|
||||
}
|
||||
|
||||
fn rewrite(source: &[u8], mut edits: Vec<(Range<usize>, Vec<u8>)>) -> Result<Vec<u8>, String> {
|
||||
edits.sort_unstable_by_key(|(span, _)| span.start);
|
||||
let mut output = Vec::new();
|
||||
let mut cursor = 0;
|
||||
for (span, replacement) in edits {
|
||||
output.extend_from_slice(
|
||||
source
|
||||
.get(cursor..span.start)
|
||||
.ok_or("overlapping Type1 subset ranges")?,
|
||||
);
|
||||
output.extend(replacement);
|
||||
cursor = span.end;
|
||||
}
|
||||
output.extend_from_slice(source.get(cursor..).ok_or("invalid Type1 subset range")?);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn encrypt(data: impl IntoIterator<Item = u8>, mut key: u16) -> Vec<u8> {
|
||||
data.into_iter()
|
||||
.map(|plain| {
|
||||
let cipher = plain ^ (key >> 8) as u8;
|
||||
key = (u16::from(cipher).wrapping_add(key))
|
||||
.wrapping_mul(52845)
|
||||
.wrapping_add(22719);
|
||||
cipher
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn subset_tag(name: &str, glyphs: &BTreeSet<String>) -> String {
|
||||
let mut hash = md5::Context::new();
|
||||
for glyph in glyphs {
|
||||
hash.consume(glyph.as_bytes());
|
||||
hash.consume(b" ");
|
||||
}
|
||||
hash.consume(name.as_bytes());
|
||||
hash.consume(0u32.to_le_bytes());
|
||||
let digest = hash.finalize().0;
|
||||
let mut sum: u16 = digest[..13].iter().map(|byte| u16::from(*byte)).sum();
|
||||
(0..6)
|
||||
.map(|index| {
|
||||
if index > 0 {
|
||||
sum -= u16::from(digest[index - 1]);
|
||||
sum += u16::from(digest[(index + 12) % 16]);
|
||||
}
|
||||
char::from(b'A' + (sum % 26) as u8)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -2175,6 +2175,40 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
|
||||
全量编译一致。incremental-receipt.json 的 SHA-256 为
|
||||
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
|
||||
|
||||
### pdfTeX 导入字体的物理子集
|
||||
|
||||
字体映射的单小于号与双小于号分别选择子集和完整嵌入。导入页的
|
||||
字体描述符有实际 CharSet 时,子集按其中的名字选择字形。沿用已有
|
||||
Type 1 解释器追踪实际调用、seac 的基字和重音以及 .notdef。
|
||||
写回原始字形和所需子程序,保留子程序编号及惯用的前四个槽位。
|
||||
索引范围内的未用槽位写成带原 lenIV 的返回指令,裁去已确认
|
||||
定义边界的未用尾部。按参考规则写入子集名、编码、CharSet 和
|
||||
实际字体流长度。
|
||||
[pdfTeX 的字形及子程序追踪](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writet1.c#L1085-L1275)
|
||||
[pdfTeX 的子集命名](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/utils.c#L107-L151)
|
||||
|
||||
六个定向用例核对实际字形程序、子程序及其索引数量、词框和
|
||||
144 DPI 光栅。原样 Latin Modern A/V 从 119215 降至 15554 字节,
|
||||
与参考的子集长度相同,重音 Aacute/V 都为 19765 字节。Courier 的
|
||||
seac 子集包含 Aacute、A、acute 和 .notdef。CMR 与 Courier 使用
|
||||
原始 PostScript 记录的空白,字体流长度与参考分别差 14 和 3 字节。
|
||||
两个完整嵌入用例保留各自原始 PFB。四项既有 Type1 字形回归通过。
|
||||
|
||||
四次编辑依次更换图像字形、整字体嵌入、恢复子集和还原图像。
|
||||
每次复用 99 步,只替换第二页,PDF、SVG、来源映射和辅助文件与
|
||||
同初态独立全量一致。
|
||||
|
||||
原样 Elsevier CAS 双栏沿用冻结的 30 项交付、实际字体映射和
|
||||
schema51,从干净目录完成三轮 LaTeX 和一次实际 BibTeX。三轮
|
||||
aux 与实际 bbl 逐字节一致,六页 10372 个字形坐标、1889 个词框
|
||||
和 144 DPI 光栅匹配。图摘的 CMR10 实际使用只含数字 one 的子集。
|
||||
保留两次预置辅助文件被归属保护拒绝的复编日志。
|
||||
|
||||
回执 target/p3-imported-type1-subset/receipt.json 的 SHA-256 为
|
||||
159c3172f522df4c51c19a8f4d2292cbb452a656ec5e7bd56b7d8a6969073533。
|
||||
文档级的字形需求合并、正文与导入图的描述符共享及全局子集名分配
|
||||
继续推进。
|
||||
|
||||
### pdfTeX 导入页面的 Type1C 编码和实际笔画宽度
|
||||
|
||||
根资源中的间接 Type1 字体可以从 FontFile3 的 Type1C 流进入
|
||||
|
||||
@@ -977,6 +977,15 @@ LuaLaTex、languages 和 argues 的断行与冻结参考一致。PDF 提取的
|
||||
字形提取仍待对照,当前整页版面门禁保持未通过。
|
||||
阶段回执 `target/p3-xetex-native-hyphenation/receipt.json`。
|
||||
|
||||
### Elsevier CAS 双栏图摘的实际字体子集
|
||||
|
||||
从冻结的 30 项原始交付重新运行三轮 LaTeX 与一次实际 BibTeX。
|
||||
同一 schema51、字体映射和参考下,三轮 aux 与 bbl 逐字节相同,
|
||||
六页 10372 个字形的位置、1889 个词框及 144 DPI 灰度图相同。
|
||||
首个导入页面的 CMR10 字体实际嵌入数字 one 的子集。统一出版
|
||||
模板矩阵仍在冻结同一版本后的验收范围。
|
||||
[阶段记录](P2_M1_PROGRESS.md#pdftex-导入字体的物理子集)
|
||||
|
||||
### Elsevier CAS 双栏正文复验
|
||||
|
||||
原样 CAS 双栏在同一 30 项原始交付、冻结 schema51、字体映射及
|
||||
|
||||
Reference in new issue
Block a user