From 61bead5619fe0e9660eb50a12a162fadd395bbd7 Mon Sep 17 00:00:00 2001 From: Michael Brown Date: Mon, 19 Oct 2026 15:48:43 +0000 Subject: [PATCH] Let a CFF subset keep the original glyph ids as CIDs A PDF writer that writes content streams before the final subset is known needs CIDs that don't depend on the subset. TrueType fonts get that with a CIDToGIDMap; a CFF font's CIDs come from its charset, which was always written in subset order. CidMapping::OriginalGlyphId writes the charset so each glyph's CID is its glyph id in the original font, as one format 2 range per run of consecutive ids. subset_with_options takes it along with the variation coordinates. The default and the existing functions are unchanged. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_013STfqkxxaHR6czBMgfbyrk --- src/cff/charset.rs | 87 +++++++++++++++++++++++++++++++++++++++------- src/cff/mod.rs | 2 +- src/lib.rs | 67 +++++++++++++++++++++++++++++++++-- 3 files changed, 140 insertions(+), 16 deletions(-) diff --git a/src/cff/charset.rs b/src/cff/charset.rs index 21abccb2..bfb77a67 100644 --- a/src/cff/charset.rs +++ b/src/cff/charset.rs @@ -1,23 +1,86 @@ use crate::write::Writer; +use crate::CidMapping; use crate::GlyphRemapper; use crate::Result; -/// Rewrite the charset of the font. We do not perserve the CID's from the original font. Instead, -/// we assign each glyph it's original glyph as the CID. This makes it easier to reference them -/// from the PDF, since we know the CID a glyph will have before it's subsetted. -pub fn rewrite_charset(gid_mapper: &GlyphRemapper, w: &mut Writer) -> Result<()> { +/// Rewrite the charset of the font. We do not preserve the CIDs from the original font. Instead, +/// each glyph gets as its CID either its glyph ID in the subset or, with +/// [`CidMapping::OriginalGlyphId`], its glyph ID in the original font. Either way, the CID of a +/// glyph is known before the font is subsetted, which makes it easy to reference from the PDF. +pub fn rewrite_charset( + gid_mapper: &GlyphRemapper, + cid_mapping: CidMapping, + w: &mut Writer, +) -> Result<()> { if gid_mapper.num_gids() == 1 { // We only have .notdef, so use format 0. w.write::(0); - } else { - // Use format 2. - w.write::(2); - - w.write::(1); - // -2 because -1 for not including .notdef and -1 since the first glyph - // in the range is not counted. - w.write::(gid_mapper.num_gids() - 2); + return Ok(()); + } + + // Use format 2. + w.write::(2); + + match cid_mapping { + CidMapping::SubsetGlyphId => { + w.write::(1); + // -2 because -1 for not including .notdef and -1 since the first glyph + // in the range is not counted. + w.write::(gid_mapper.num_gids() - 2); + } + CidMapping::OriginalGlyphId => { + // One range for each run of consecutive old glyph IDs, in the order of the + // new glyph IDs. .notdef is not part of the charset. + let mut gids = gid_mapper.remapped_gids().skip(1); + let mut first = gids.next().unwrap(); + let mut last = first; + + for gid in gids { + if gid == last + 1 { + last = gid; + } else { + w.write::(first); + w.write::(last - first); + first = gid; + last = gid; + } + } + + w.write::(first); + w.write::(last - first); + } } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + fn charset(glyphs: &[u16], cid_mapping: CidMapping) -> Vec { + let mut w = Writer::new(); + rewrite_charset(&GlyphRemapper::new_from_glyphs(glyphs), cid_mapping, &mut w) + .unwrap(); + w.finish() + } + + #[test] + fn subset_glyph_ids() { + assert_eq!(charset(&[], CidMapping::SubsetGlyphId), [0]); + assert_eq!( + charset(&[5, 6, 7, 20, 3], CidMapping::SubsetGlyphId), + [2, 0, 1, 0, 4] + ); + } + + #[test] + fn original_glyph_ids() { + assert_eq!(charset(&[], CidMapping::OriginalGlyphId), [0]); + assert_eq!(charset(&[7], CidMapping::OriginalGlyphId), [2, 0, 7, 0, 0]); + assert_eq!( + charset(&[5, 6, 7, 20, 3], CidMapping::OriginalGlyphId), + [2, 0, 5, 0, 2, 0, 20, 0, 0, 0, 3, 0, 0] + ); + } +} diff --git a/src/cff/mod.rs b/src/cff/mod.rs index f3321467..50338f67 100644 --- a/src/cff/mod.rs +++ b/src/cff/mod.rs @@ -164,7 +164,7 @@ pub fn subset(ctx: &mut Context<'_>) -> Result<()> { // Charsets offsets.charset_offset.update_value(w.len())?; - rewrite_charset(&ctx.mapper, &mut w)?; + rewrite_charset(&ctx.mapper, ctx.cid_mapping, &mut w)?; // Private dicts. match &table.font_kind { diff --git a/src/lib.rs b/src/lib.rs index fa9568f5..890caf09 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,6 +26,11 @@ A couple of important notes if you want to use this crate in combination with yo mapping from GID to CID for all fonts, regardless of the previous mapping. Because of this, you can always use the remapped GID as the CID for a glyph, and do not need to worry about the type of font you are embedding. +- If you need to address glyphs before the subset is known (for example to write pages on + several threads and subset the fonts once at the end), [`subset_with_options`] with + [`CidMapping::OriginalGlyphId`] makes the CID of each glyph in a CFF subset its glyph ID in + the original font. TrueType subsets carry no charset, so for them write a `CIDToGIDMap` + from the remapper instead. # Example In the example below, we remove all glyphs except the ones with IDs 68, 69, 70 from Noto Sans. @@ -106,7 +111,7 @@ use std::str::FromStr; /// /// CFF2 fonts are not supported. pub fn subset(data: &[u8], index: u32, mapper: &GlyphRemapper) -> Result> { - subset_inner(data, index, &[], false, mapper) + subset_inner(data, index, &[], false, CidMapping::default(), mapper) } /// Subset the font face to include only the necessary glyphs and tables, instantiated @@ -123,7 +128,58 @@ pub fn subset_with_variations( variation_coordinates: &[(Tag, f32)], mapper: &GlyphRemapper, ) -> Result> { - subset_inner(data, index, variation_coordinates, true, mapper) + subset_inner(data, index, variation_coordinates, true, CidMapping::default(), mapper) +} + +/// Subset the font face with [`Options`]. +/// +/// This does the same as [`subset`] or, with the `variable-fonts` feature, +/// [`subset_with_variations`], and in addition lets you choose how the glyphs of a +/// CFF subset are addressed as CIDs. +pub fn subset_with_options( + data: &[u8], + index: u32, + mapper: &GlyphRemapper, + options: &Options, +) -> Result> { + if !cfg!(feature = "variable-fonts") && !options.variation_coordinates.is_empty() { + return Err(Unimplemented); + } + subset_inner( + data, + index, + options.variation_coordinates, + cfg!(feature = "variable-fonts"), + options.cid_mapping, + mapper, + ) +} + +/// How the glyphs of a CFF subset are addressed as CIDs, through its charset. +/// +/// TrueType subsets have no charset: their CIDs are always the glyph IDs in the subset, and +/// a `CIDToGIDMap` in the PDF can map other CIDs onto them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum CidMapping { + /// The CID of each glyph is its glyph ID in the subset, which [`GlyphRemapper::get`] + /// gives. This is the default. + #[default] + SubsetGlyphId, + /// The CID of each glyph is its glyph ID in the original font, so that content can + /// address glyphs before the subset is known. The charset grows by a few bytes for each + /// run of consecutive glyph IDs in the subset. + OriginalGlyphId, +} + +/// Options for [`subset_with_options`]. +#[derive(Debug, Clone, Default)] +pub struct Options<'a> { + /// How the glyphs of a CFF subset are addressed as CIDs. + pub cid_mapping: CidMapping, + /// The variation coordinates to instantiate the font at, as for + /// `subset_with_variations`. Without the `variable-fonts` feature, subsetting + /// fails with [`Error::Unimplemented`] unless this is empty. + pub variation_coordinates: &'a [(Tag, f32)], } fn subset_inner( @@ -131,11 +187,13 @@ fn subset_inner( index: u32, variation_coordinates: &[(Tag, f32)], allow_cff2: bool, + cid_mapping: CidMapping, mapper: &GlyphRemapper, ) -> Result> { let mapper = mapper.clone(); - let context = + let mut context = prepare_context(data, index, variation_coordinates, allow_cff2, mapper)?; + context.cid_mapping = cid_mapping; _subset(context) } @@ -198,6 +256,7 @@ fn prepare_context<'a>( face, mapper: gid_remapper, interjector, + cid_mapping: CidMapping::default(), custom_maxp_data: None, custom_hmtx_data: None, flavor, @@ -371,6 +430,8 @@ struct Context<'a> { face: Face<'a>, /// A map from old gids to new gids, and the reverse mapper: GlyphRemapper, + /// How the glyphs of a CFF subset are addressed as CIDs. + cid_mapping: CidMapping, /// The font flavor. flavor: FontFlavor, /// Subsetted tables.