f-office-pdf 0.2.4

Writes a display list as PDF.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Font tracking, on-the-fly glyph CID assignment, subsetting, and streaming Type0/CIDFont
//! emission.

use std::collections::{BTreeMap, HashMap};
use std::io::Write;

use f_office_fonts::{FontDb, FontId};
use pdf_writer::types::{CidFontType, FontFlags, SystemInfo, UnicodeCmap};
use pdf_writer::{Chunk, Filter, Finish, Name, Rect, Ref, Str};
use read_fonts::TableProvider;
use skrifa::FontRef;
use subsetter::GlyphRemapper;

use crate::Error;
use crate::outline_font;
use crate::stream::{StreamPdf, deflate};

/// Adobe-Identity-0 character collection used for CID fonts.
const IDENTITY_SYSTEM_INFO: SystemInfo<'static> = SystemInfo {
    registry: Str(b"Adobe"),
    ordering: Str(b"Identity"),
    supplement: 0,
};

/// Tracks fonts referenced across all streamed pages and emits one subsetted CID font at a time
/// at the end of the document.
pub(crate) struct UsedFonts<'a> {
    db: &'a FontDb,
    /// Lookup from `FontId` into `order`.
    index_by_id: HashMap<FontId, usize>,
    /// Deterministic insertion order of used fonts.
    order: Vec<UsedFont>,
}

/// Per-font state accumulated while pages stream.
pub(crate) struct UsedFont {
    id: FontId,
    /// Pre-allocated PDF object reference for the Type0 font dictionary.
    type0_ref: Ref,
    /// Units per em from the font's `head` table.
    units_per_em: f32,
    /// Right edge of the font's bounding box in font units (`head.xMax`).
    right_edge: Option<i16>,
    /// On-the-fly original GID -> subset CID remapper (CID 0 is always `.notdef`).
    remapper: GlyphRemapper,
    /// Primary Unicode text recorded for each subset CID (first observed mapping).
    unicode: BTreeMap<u16, String>,
    /// Original GID for each assigned subset CID, for width lookup when emitting `/W`.
    orig_gids: Vec<u16>,
}

/// What [`UsedFont::record_glyph`] returns for a single glyph occurrence.
pub(crate) struct MappedGlyph {
    /// Remapped 16-bit CID to write into the content stream.
    pub(crate) cid: u16,
    /// Whether this occurrence's text differs from the CID's primary `ToUnicode` entry and
    /// therefore needs an `/ActualText` marked-content span.
    pub(crate) needs_actual_text: bool,
}

impl<'a> UsedFonts<'a> {
    /// Creates a new font tracker backed by `db`.
    pub(crate) fn new(db: &'a FontDb) -> Self {
        Self {
            db,
            index_by_id: HashMap::new(),
            order: Vec::new(),
        }
    }

    /// Returns the font database.
    pub(crate) fn db(&self) -> &'a FontDb {
        self.db
    }

    /// Validates that `id` exists in `db` and is readable without registering it for embedding.
    pub(crate) fn validate(&self, id: FontId) -> Result<(), Error> {
        let (data, index) = self.db.data(id).ok_or(Error::UnknownFont(id))?;
        let font = FontRef::from_index(data, index).map_err(|_| Error::UnreadableFont(id))?;
        let units = font
            .head()
            .map_err(|_| Error::UnreadableFont(id))?
            .units_per_em();
        if units == 0 {
            return Err(Error::UnreadableFont(id));
        }
        Ok(())
    }

    /// Ensures `id` is registered and validated against `db`, allocating its Type0 `Ref` on first
    /// use, and returns a mutable handle to its state.
    pub(crate) fn get_or_register<W: Write>(
        &mut self,
        id: FontId,
        pdf: &mut StreamPdf<'_, W>,
    ) -> Result<&mut UsedFont, Error> {
        if let Some(&idx) = self.index_by_id.get(&id) {
            return self.order.get_mut(idx).ok_or(Error::UnknownFont(id));
        }
        let (data, index) = self.db.data(id).ok_or(Error::UnknownFont(id))?;
        let font = FontRef::from_index(data, index).map_err(|_| Error::UnreadableFont(id))?;
        let units_per_em = f32::from(
            font.head()
                .map_err(|_| Error::UnreadableFont(id))?
                .units_per_em(),
        );
        if units_per_em <= 0.0 {
            return Err(Error::UnreadableFont(id));
        }
        let right_edge = outline_font::right_edge(data, index);
        let type0_ref = pdf.alloc();
        let mut remapper = GlyphRemapper::new();
        remapper.remap(0);
        let idx = self.order.len();
        self.order.push(UsedFont {
            id,
            type0_ref,
            units_per_em,
            right_edge,
            remapper,
            unicode: BTreeMap::new(),
            orig_gids: vec![0],
        });
        self.index_by_id.insert(id, idx);
        self.order.get_mut(idx).ok_or(Error::UnknownFont(id))
    }

    /// Subsets and streams every used font into `pdf`, one font at a time.
    pub(crate) fn emit_all<W: Write>(&self, pdf: &mut StreamPdf<'_, W>) -> Result<(), Error> {
        for used in &self.order {
            emit_font(self.db, used, pdf)?;
        }
        Ok(())
    }
}

impl UsedFont {
    /// Returns the pre-allocated Type0 font PDF object reference.
    pub(crate) const fn type0_ref(&self) -> Ref {
        self.type0_ref
    }

    /// Returns units per em for this font.
    pub(crate) const fn units_per_em(&self) -> f32 {
        self.units_per_em
    }

    /// Returns the font's right edge (`head.xMax`) in font units, if available.
    pub(crate) const fn right_edge(&self) -> Option<i16> {
        self.right_edge
    }

    /// Remaps `orig_gid` to its subset CID and records `text` for `/ToUnicode` (or flags that
    /// `/ActualText` is required when this CID was already bound to different text).
    pub(crate) fn record_glyph(&mut self, orig_gid: u32, text: &str) -> Result<MappedGlyph, Error> {
        let orig_u16 = u16::try_from(orig_gid).map_err(|_| Error::UnknownGlyph {
            font: self.id,
            glyph: orig_gid,
        })?;
        let cid = self.remapper.remap(orig_u16);
        let cid_idx = usize::from(cid);
        if cid_idx >= self.orig_gids.len() {
            self.orig_gids.resize(cid_idx + 1, 0);
        }
        if let Some(slot) = self.orig_gids.get_mut(cid_idx) {
            *slot = orig_u16;
        }
        let needs_actual_text = if text.is_empty() {
            false
        } else if let Some(existing) = self.unicode.get(&cid) {
            existing != text
        } else {
            self.unicode.insert(cid, text.to_owned());
            false
        };
        Ok(MappedGlyph {
            cid,
            needs_actual_text,
        })
    }
}

/// Emits one subsetted font (`FontFile`, `FontDescriptor`, `ToUnicode` `CMap`, `CIDFont`,
/// `Type0Font`) directly to `pdf`.
fn emit_font<W: Write>(
    db: &FontDb,
    used: &UsedFont,
    pdf: &mut StreamPdf<'_, W>,
) -> Result<(), Error> {
    let (raw_data, raw_index) = db.data(used.id).ok_or(Error::UnknownFont(used.id))?;
    let stripped = outline_font::without_color_tables(raw_data, raw_index);
    let (font_bytes, face_index) = match stripped.as_deref() {
        Some(clean) => (clean, 0_u32),
        None => (raw_data.as_ref(), raw_index),
    };
    let subset_bytes = subsetter::subset(font_bytes, face_index, &used.remapper)
        .map_err(|err| Error::Write(format!("failed to subset font: {err:?}")))?;
    let parsed =
        FontRef::from_index(font_bytes, face_index).map_err(|_| Error::UnreadableFont(used.id))?;
    let is_cff = parsed.cff().is_ok();
    let metrics = extract_metrics(&parsed, used.units_per_em);
    let base_name = subset_font_name(used.id);

    let font_file_ref = emit_font_file(&subset_bytes, is_cff, pdf)?;
    let descriptor_ref = emit_descriptor(&base_name, &metrics, font_file_ref, is_cff, pdf)?;
    let cmap_ref = emit_to_unicode(&used.unicode, pdf)?;
    let cid_ref = emit_cid_font(db, used, (&base_name, descriptor_ref, is_cff), pdf)?;

    let mut chunk = Chunk::new();
    chunk
        .type0_font(used.type0_ref)
        .base_font(Name(base_name.as_bytes()))
        .encoding_predefined(Name(b"Identity-H"))
        .descendant_font(cid_ref)
        .to_unicode(cmap_ref);
    pdf.emit(used.type0_ref, &chunk)
}

/// Extracted OpenType metrics scaled to 1000 units per em for the PDF `FontDescriptor`.
struct DescriptorMetrics {
    bbox: Rect,
    ascent: f32,
    descent: f32,
    cap_height: f32,
    italic_angle: f32,
}

fn extract_metrics(font: &FontRef<'_>, units_per_em: f32) -> DescriptorMetrics {
    let scale = 1000.0 / units_per_em;
    let bbox = font
        .head()
        .map_or(Rect::new(0.0, 0.0, 1000.0, 1000.0), |h| {
            Rect::new(
                f32::from(h.x_min()) * scale,
                f32::from(h.y_min()) * scale,
                f32::from(h.x_max()) * scale,
                f32::from(h.y_max()) * scale,
            )
        });
    let (ascent, descent) = font.hhea().map_or((800.0, -200.0), |h| {
        (
            f32::from(h.ascender().to_i16()) * scale,
            f32::from(h.descender().to_i16()) * scale,
        )
    });
    let cap_height = font
        .os2()
        .ok()
        .and_then(|os2| os2.s_cap_height())
        .map_or(ascent, |h| f32::from(h) * scale);
    let italic_angle = font.post().map_or(0.0, |p| p.italic_angle().to_f32());
    DescriptorMetrics {
        bbox,
        ascent,
        descent,
        cap_height,
        italic_angle,
    }
}

/// Builds a deterministic PostScript subset font name (`AAAAAA+F{n}`).
fn subset_font_name(id: FontId) -> String {
    let idx = id.index();
    let mut tag = [b'A'; 6];
    let mut value = idx;
    for slot in tag.iter_mut().rev() {
        let letter = u8::try_from(value % 26).unwrap_or(0);
        *slot = b'A' + letter;
        value /= 26;
    }
    let prefix = std::str::from_utf8(&tag).unwrap_or("AAAAAA");
    format!("{prefix}+F{idx}")
}

/// Emits the compressed `FontFile2` (TrueType) or `FontFile3` (CFF) stream.
fn emit_font_file<W: Write>(
    subset_bytes: &[u8],
    is_cff: bool,
    pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
    let file_ref = pdf.alloc();
    if is_cff {
        let sub_font = FontRef::from_index(subset_bytes, 0)
            .map_err(|_| Error::Write("subset CFF font unreadable".into()))?;
        let cff_table = sub_font
            .cff()
            .map_err(|_| Error::Write("subset missing CFF table".into()))?;
        let compressed = deflate(cff_table.offset_data().as_bytes())?;
        let mut chunk = Chunk::new();
        let mut stream = chunk.stream(file_ref, &compressed);
        stream.filter(Filter::FlateDecode);
        stream.pair(Name(b"Subtype"), Name(b"CIDFontType0C"));
        stream.finish();
        pdf.emit(file_ref, &chunk)?;
    } else {
        let compressed = deflate(subset_bytes)?;
        let mut chunk = Chunk::new();
        let mut stream = chunk.stream(file_ref, &compressed);
        stream.filter(Filter::FlateDecode);
        stream.pair(
            Name(b"Length1"),
            i32::try_from(subset_bytes.len()).unwrap_or(i32::MAX),
        );
        stream.finish();
        pdf.emit(file_ref, &chunk)?;
    }
    Ok(file_ref)
}

/// Emits the `FontDescriptor` dictionary.
fn emit_descriptor<W: Write>(
    base_name: &str,
    metrics: &DescriptorMetrics,
    font_file_ref: Ref,
    is_cff: bool,
    pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
    let desc_ref = pdf.alloc();
    let mut chunk = Chunk::new();
    let mut desc = chunk.font_descriptor(desc_ref);
    desc.name(Name(base_name.as_bytes()))
        .flags(FontFlags::SYMBOLIC)
        .bbox(metrics.bbox)
        .italic_angle(metrics.italic_angle)
        .ascent(metrics.ascent)
        .descent(metrics.descent)
        .cap_height(metrics.cap_height)
        .stem_v(80.0);
    if is_cff {
        desc.font_file3(font_file_ref);
    } else {
        desc.font_file2(font_file_ref);
    }
    desc.finish();
    pdf.emit(desc_ref, &chunk)?;
    Ok(desc_ref)
}

/// Emits the `/ToUnicode` `CMap` stream mapping each remapped CID (including CID 0 if mapped) to
/// its Unicode text.
fn emit_to_unicode<W: Write>(
    unicode: &BTreeMap<u16, String>,
    pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
    let cmap_ref = pdf.alloc();
    let mut cmap = UnicodeCmap::new(Name(b"FOfficeUnicode"), IDENTITY_SYSTEM_INFO);
    for (&cid, text) in unicode {
        let mut chars = text.chars();
        if let Some(first) = chars.next() {
            if chars.next().is_none() {
                cmap.pair(cid, first);
            } else {
                cmap.pair_with_multiple(cid, text.chars());
            }
        }
    }
    let raw = cmap.finish();
    let compressed = deflate(raw.as_slice())?;
    let mut chunk = Chunk::new();
    let mut stream = chunk.cmap(cmap_ref, &compressed);
    stream.filter(Filter::FlateDecode);
    stream.finish();
    pdf.emit(cmap_ref, &chunk)?;
    Ok(cmap_ref)
}

/// Emits the descendant `CIDFont` dictionary with `/W` widths in thousandths of an em.
fn emit_cid_font<W: Write>(
    db: &FontDb,
    used: &UsedFont,
    (base_name, descriptor_ref, is_cff): (&str, Ref, bool),
    pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
    let cid_ref = pdf.alloc();
    let widths: Vec<f32> = used
        .orig_gids
        .iter()
        .map(|&orig| {
            db.advance(used.id, u32::from(orig))
                .map_or(0.0, |adv| f32::from(adv) / used.units_per_em * 1000.0)
        })
        .collect();
    let mut chunk = Chunk::new();
    let mut cid = chunk.cid_font(cid_ref);
    cid.subtype(if is_cff {
        CidFontType::Type0
    } else {
        CidFontType::Type2
    })
    .base_font(Name(base_name.as_bytes()))
    .system_info(IDENTITY_SYSTEM_INFO)
    .font_descriptor(descriptor_ref)
    .default_width(0.0);
    if !is_cff {
        cid.cid_to_gid_map_predefined(Name(b"Identity"));
    }
    if !widths.is_empty() {
        cid.widths().consecutive(0, widths);
    }
    cid.finish();
    pdf.emit(cid_ref, &chunk)?;
    Ok(cid_ref)
}