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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! Streams a display list directly as PDF.
//!
//! [`write_pdf_to`] writes one PDF page for each page of a display list directly to any
//! [`std::io::Write`] sink without buffering the full PDF document in memory, and [`write_pdf`]
//! collects the same output into a `Vec<u8>`.
//!
//! Each glyph run becomes text in its subsetted CID font from the font database at the run's size
//! and color. F-Office shapes all text itself, so glyph IDs pass through unchanged without
//! reshaping or reordering. Each glyph sits at its display-list position and carries its text via
//! `/ToUnicode` (and `/ActualText` when one glyph stands for multiple text strings). Rectangles,
//! paths, axial gradients, clipped groups, and PNG/JPEG/GIF/BMP/TIFF images are emitted in
//! painting order. Images are deduplicated and flushed straight to the sink on first use without
//! retaining raw image bytes across pages.
//!
//! The PDF holds no dates and no XMP metadata, so the same display list and fonts always produce
//! identical bytes.

mod fonts;
mod images;
mod outline_font;
mod page;
mod stream;
mod text;

use std::collections::HashMap;
use std::fmt;
use std::io::Write;

use f_office_fonts::{FontDb, FontId};
use f_office_paint::{self as paint, DisplayList, GlyphRun, GradientStop, ImageFault, ImageFormat};
use f_office_units::Length;
use pdf_writer::Chunk;

use crate::fonts::UsedFonts;
use crate::images::EmittedImages;
use crate::page::DocState;
use crate::stream::StreamPdf;

/// Why a display list could not be written as PDF.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
    /// The display list has no page. A PDF needs at least one.
    NoPages,
    /// A page has a width or a height that is not positive.
    PageSize,
    /// A glyph run names a font that the font database does not hold.
    UnknownFont(FontId),
    /// A font from the font database cannot be parsed or embedded.
    UnreadableFont(FontId),
    /// A glyph run names a glyph that its font does not have.
    UnknownGlyph {
        /// The font of the run.
        font: FontId,
        /// The glyph ID.
        glyph: u32,
    },
    /// A glyph's text range is not a range of whole characters in the text of its run.
    TextRange,
    /// A group's clip is an empty or invalid path.
    Clip,
    /// The PDF writer could not subset a font or write to the output sink.
    Write(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoPages => f.write_str("the display list has no page"),
            Self::PageSize => f.write_str("a page has a size that is not positive"),
            Self::UnknownFont(id) => write!(f, "the font database has no font {}", id.index()),
            Self::UnreadableFont(id) => write!(f, "font {} cannot be embedded", id.index()),
            Self::UnknownGlyph { font, glyph } => {
                write!(f, "font {} has no glyph {glyph}", font.index())
            }
            Self::TextRange => f.write_str("a glyph's text range is not in its run's text"),
            Self::Clip => f.write_str("a group's clip is not a path that krilla can build"),
            Self::Write(message) => write!(f, "the PDF cannot be written: {message}"),
        }
    }
}

impl std::error::Error for Error {}

/// What the PDF writer left out of a display list, and went on.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Warning {
    /// An image that the PDF leaves out: its format, and why.
    ImageSkipped {
        /// The image's format.
        format: ImageFormat,
        /// Why the PDF leaves it out.
        fault: ImageFault,
    },
}

impl Warning {
    /// The warning's kind, a short name that stays the same across versions, for a caller
    /// that counts warnings.
    #[must_use]
    pub fn kind(&self) -> &'static str {
        match self {
            Self::ImageSkipped { .. } => "pdf-image-skipped",
        }
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ImageSkipped { format, fault } => {
                write!(
                    f,
                    "an image in {format} format is left out of the PDF: {fault}"
                )
            }
        }
    }
}

/// The warnings of a written PDF.
pub type Warnings = f_office_warnings::Warnings<Warning>;

/// A written PDF with its warnings.
pub type Warned<T> = f_office_warnings::Warned<T, Warning>;

/// Writes a display list as a PDF file into a `Vec<u8>`, returning the bytes with any warnings.
///
/// For large documents or file outputs, prefer [`write_pdf_to`] to stream objects directly to an
/// [`std::io::Write`] sink without holding the whole PDF in memory.
///
/// # Errors
///
/// Returns an error when the list has no page, when a page size is not positive, when a glyph
/// run names a font or a glyph that `fonts` does not hold, when a glyph's text range is not in
/// its run's text, or when a font cannot be subsetted or written.
pub fn write_pdf(list: &DisplayList, fonts: &FontDb) -> Result<Warned<Vec<u8>>, Error> {
    let mut out = Vec::new();
    let warned = write_pdf_to(list, fonts, &mut out)?;
    Ok(Warned::new(out, warned.warnings))
}

/// Streams a display list directly as a PDF 1.7 document into `writer`, flushing each image
/// `XObject`, page content stream, and subsetted font object immediately as it is produced.
///
/// # Errors
///
/// Returns an error when the list has no page, when a page size is not positive, when a glyph
/// run names a font or a glyph that `fonts` does not hold, when a glyph's text range is not in
/// its run's text, when a font cannot be subsetted, or when writing to `writer` fails.
pub fn write_pdf_to<W: Write>(
    list: &DisplayList,
    fonts: &FontDb,
    writer: &mut W,
) -> Result<Warned<()>, Error> {
    if list.pages().is_empty() {
        return Err(Error::NoPages);
    }
    let mut pdf = StreamPdf::start(writer)?;
    let pages_ref = pdf.alloc();
    let mut state = DocState {
        pdf,
        fonts: UsedFonts::new(fonts),
        images: EmittedImages::default(),
        ext_gstates: HashMap::new(),
        warnings: Warnings::new(),
    };
    let mut page_refs = Vec::with_capacity(list.pages().len());
    for page in list.pages() {
        page_refs.push(page::write_page(page, pages_ref, &mut state)?);
    }
    state.fonts.emit_all(&mut state.pdf)?;
    let mut pages_chunk = Chunk::new();
    let count = i32::try_from(page_refs.len())
        .map_err(|_| Error::Write("too many pages for PDF".into()))?;
    pages_chunk.pages(pages_ref).kids(page_refs).count(count);
    state.pdf.emit(pages_ref, &pages_chunk)?;
    state.pdf.finish(pages_ref)?;
    Ok(Warned::new((), state.warnings))
}

/// The commands of a clip, where a clip of one rectangle gets a fourth line back to its first
/// corner before its close so readers do not elide near-identity rectangular clips.
pub(crate) fn clip_commands(commands: &[paint::PathCommand]) -> Vec<paint::PathCommand> {
    use paint::PathCommand::{Close, LineTo, MoveTo};
    match *commands {
        [MoveTo(first), LineTo(a), LineTo(b), LineTo(c), Close] => {
            vec![
                MoveTo(first),
                LineTo(a),
                LineTo(b),
                LineTo(c),
                LineTo(first),
                Close,
            ]
        }
        [MoveTo(first), LineTo(a), LineTo(b), LineTo(c), LineTo(last)] if last == first => {
            vec![
                MoveTo(first),
                LineTo(a),
                LineTo(b),
                LineTo(c),
                LineTo(last),
                Close,
            ]
        }
        _ => commands.to_vec(),
    }
}

/// The scale and local length of a picture's side so that `scale * printed(number) * stretch`
/// matches `side` within [`SIDE_ERROR`].
pub(crate) fn side_scale(side: f64, start: SideStart, stretch: f64) -> (f32, f32) {
    let written = side / stretch;
    let own = decimal(written);
    if start.error(side, stretch, own) <= SIDE_ERROR {
        return (1.0, own);
    }
    let mut scale = 2.0_f32;
    for _ in 0..SIDE_SCALES {
        let factor = printed(scale);
        let number = nearest_printed(written, factor, to_f32(written / factor));
        if start.error(side, factor * stretch, number) <= SIDE_ERROR {
            return (scale, number);
        }
        scale = scale.next_up();
    }
    (1.0, own)
}

/// Where a picture's side starts in the transform that draws it.
#[derive(Clone, Copy)]
pub(crate) enum SideStart {
    Corner,
    Centre,
}

impl SideStart {
    fn error(self, side: f64, scale: f64, number: f32) -> f64 {
        let whole = (scale * printed(number) - side).abs();
        match self {
            Self::Corner => whole,
            Self::Centre => {
                let half = printed(number / 2.0);
                let before = (scale * half - side / 2.0).abs();
                let after = (scale * (printed(number) - half) - side / 2.0).abs();
                before.max(after).max(whole)
            }
        }
    }
}

#[expect(
    clippy::cast_precision_loss,
    reason = "the number of half-EMUs to the point is exact in double precision"
)]
const SIDE_ERROR: f64 = 0.4 / Length::UNITS_PER_POINT as f64;
const SIDE_SCALES: usize = 4_096;

/// Whole-point anchor keeping local coordinates small enough for exact half-EMU single-precision
/// representation in PDF content streams.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Anchor {
    pub(crate) x: Length,
    pub(crate) foot: Length,
    pub(crate) y: Length,
}

impl Anchor {
    const REACH: i64 = 256 * Length::UNITS_PER_POINT;

    pub(crate) fn at(height: Length, x: Length, y: Length) -> Self {
        let whole = |length: Length| {
            let point = Length::UNITS_PER_POINT;
            Length::from_units(length.units().div_euclid(point) * point)
        };
        let foot = whole(height - y);
        Self {
            x: whole(x),
            foot,
            y: height - foot,
        }
    }

    pub(crate) fn middle(
        height: Length,
        (left, top): (Length, Length),
        (right, bottom): (Length, Length),
    ) -> Self {
        let half = |a: Length, b: Length| Length::from_units(a.units().midpoint(b.units()));
        Self::at(height, half(left, right), half(top, bottom))
    }

    pub(crate) fn reaches(self, x: Length, y: Length) -> bool {
        (x - self.x).units().abs() < Self::REACH && (y - self.y).units().abs() < Self::REACH
    }

    pub(crate) fn of_line(height: Length, x: Length, y: Length) -> Self {
        let anchor = Self::at(height, x, y);
        if anchor.y != y {
            return anchor;
        }
        let point = Length::from_units(Length::UNITS_PER_POINT);
        Self {
            x: anchor.x,
            foot: anchor.foot - point,
            y: anchor.y + point,
        }
    }

    pub(crate) fn matrix(self) -> [f32; 6] {
        [1.0, 0.0, 0.0, -1.0, points(self.x), points(self.foot)]
    }

    pub(crate) fn undone_matrix(self) -> [f32; 6] {
        [1.0, 0.0, 0.0, -1.0, -points(self.x), points(self.foot)]
    }

    pub(crate) fn turned_matrix(self, turn: paint::Turn) -> [f32; 6] {
        let [xx, yx, xy, yy] = turn_entries(turn);
        [xx, -yx, xy, -yy, points(self.x), points(self.foot)]
    }

    pub(crate) fn local(self, x: Length, y: Length) -> (f32, f32) {
        (
            decimal((x - self.x).points_f64()),
            decimal((y - self.y).points_f64()),
        )
    }
}

/// Whole-point anchor with optional scale for wide filled paths and rectangles.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FillAnchor {
    pub(crate) anchor: Anchor,
    hundredths: u32,
}

impl FillAnchor {
    const REACH: f64 = 255.0;

    pub(crate) fn middle(
        height: Length,
        (left, top): (Length, Length),
        (right, bottom): (Length, Length),
    ) -> Self {
        let anchor = Anchor::middle(height, (left, top), (right, bottom));
        let reach = [
            left - anchor.x,
            right - anchor.x,
            top - anchor.y,
            bottom - anchor.y,
        ]
        .into_iter()
        .map(|distance| distance.points_f64().abs())
        .fold(0.0, f64::max);
        let hundredths = if reach < Self::REACH {
            100
        } else {
            hundredths_above(reach / Self::REACH)
        };
        Self { anchor, hundredths }
    }

    fn scale(self) -> f64 {
        printed(to_f32(f64::from(self.hundredths) / 100.0))
    }

    pub(crate) fn matrix(self) -> [f32; 6] {
        let scale = to_f32(self.scale());
        let Anchor { x, foot, .. } = self.anchor;
        [scale, 0.0, 0.0, -scale, points(x), points(foot)]
    }

    fn number(self, value: f64) -> f32 {
        if self.hundredths == 100 {
            return decimal(value);
        }
        let scale = self.scale();
        nearest_printed(value, scale, to_f32(value / scale))
    }

    pub(crate) fn local(self, x: Length, y: Length) -> (f32, f32) {
        (
            self.number((x - self.anchor.x).points_f64()),
            self.number((y - self.anchor.y).points_f64()),
        )
    }

    pub(crate) fn span(self, start: Length, length: Length) -> (f32, f32) {
        let from = start.points_f64();
        let to = from + length.points_f64();
        (self.number(from.min(to)), self.number(from.max(to)))
    }
}

#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "the ratio of a place on a page to the reach of a fill is positive and small"
)]
fn hundredths_above(ratio: f64) -> u32 {
    (ratio * 100.0).ceil() as u32
}

pub(crate) fn upright_start(
    turn: paint::Turn,
    anchor: Anchor,
    origin: &paint::Glyph,
) -> (f32, f32) {
    let [xx, yx, xy, yy] = [turn.xx, turn.yx, turn.xy, turn.yy].map(i64::from);
    let (dx, dy) = (
        (origin.x - anchor.x).points_f64(),
        (origin.y - anchor.y).points_f64(),
    );
    let determinant = xx * yy - xy * yx;
    if determinant == 0 {
        return (to_f32(dx), to_f32(dy));
    }
    let [xx, yx, xy, yy, determinant] = [xx, yx, xy, yy, determinant].map(exact_count);
    let scale = f64::from(paint::Turn::SCALE);
    (
        to_f32((yy * dx - xy * dy) * scale / determinant),
        to_f32((xx * dy - yx * dx) * scale / determinant),
    )
}

#[expect(
    clippy::cast_precision_loss,
    reason = "the entries of a turn and their products stay far below 2^53"
)]
fn exact_count(count: i64) -> f64 {
    count as f64
}

pub(crate) fn turn_entries(turn: paint::Turn) -> [f32; 4] {
    #[expect(
        clippy::cast_precision_loss,
        reason = "a turn's entries are millionths of at most a few units, which f32 holds to about 1e-7"
    )]
    [turn.xx, turn.yx, turn.xy, turn.yy].map(|entry| entry as f32 / paint::Turn::SCALE as f32)
}

pub(crate) fn upright_run(run: &GlyphRun, turn: paint::Turn) -> GlyphRun {
    let mut upright = run.clone();
    upright.turn = None;
    let [xx, yx, xy, yy] = [turn.xx, turn.yx, turn.xy, turn.yy].map(i128::from);
    let determinant = xx * yy - xy * yx;
    if let (Some(first), true) = (run.glyphs.first(), determinant != 0) {
        let (x0, y0) = (first.x.units(), first.y.units());
        let scale = i128::from(paint::Turn::SCALE);
        let back = |value: i128| i64::try_from(value * scale / determinant).unwrap_or(0);
        for glyph in &mut upright.glyphs {
            let dx = i128::from(glyph.x.units() - x0);
            let dy = i128::from(glyph.y.units() - y0);
            glyph.x = Length::from_units(x0 + back(yy * dx - xy * dy));
            glyph.y = Length::from_units(y0 + back(xx * dy - yx * dx));
        }
    }
    upright
}

pub(crate) fn stop_offset(place: u32) -> f32 {
    to_f32(f64::from(place.min(GradientStop::END)) / f64::from(GradientStop::END))
}

pub(crate) fn path_anchor(height: Length, commands: &[paint::PathCommand]) -> Anchor {
    path_bounds(commands).map_or(
        Anchor::at(height, Length::ZERO, Length::ZERO),
        |(low, high)| Anchor::middle(height, (low.x, low.y), (high.x, high.y)),
    )
}

pub(crate) fn path_bounds(commands: &[paint::PathCommand]) -> Option<(paint::Point, paint::Point)> {
    use paint::PathCommand::{Close, CubicTo, LineTo, MoveTo, QuadTo};
    let points = commands.iter().flat_map(|command| match *command {
        MoveTo(p) | LineTo(p) => vec![p],
        QuadTo(c, p) => vec![c, p],
        CubicTo(c0, c1, p) => vec![c0, c1, p],
        Close => Vec::new(),
    });
    points.fold(None, |bounds: Option<(paint::Point, paint::Point)>, p| {
        Some(bounds.map_or((p, p), |(low, high)| {
            (
                paint::Point {
                    x: low.x.min(p.x),
                    y: low.y.min(p.y),
                },
                paint::Point {
                    x: high.x.max(p.x),
                    y: high.y.max(p.y),
                },
            )
        }))
    })
}

pub(crate) fn points(length: Length) -> f32 {
    to_f32(length.points_f64())
}

pub(crate) fn decimal(value: f64) -> f32 {
    let nearest = to_f32(value);
    if value.abs() < 256.0 {
        return nearest;
    }
    nearest_printed(value, 1.0, nearest)
}

fn nearest_printed(value: f64, scale: f64, nearest: f32) -> f32 {
    let error = |number: f32| (scale * printed(number) - value).abs();
    let (mut best, mut best_error) = (nearest, error(nearest));
    let (mut above, mut below) = (nearest, nearest);
    for _ in 0..DECIMAL_NEIGHBORS {
        above = above.next_up();
        below = below.next_down();
        for number in [above, below] {
            let found = error(number);
            if found < best_error {
                (best, best_error) = (number, found);
            }
        }
    }
    best
}

const DECIMAL_NEIGHBORS: usize = 2;

pub(crate) fn printed(number: f32) -> f64 {
    let magnitude = number.abs();
    let text = if number == 0.0 || (magnitude > 1e-6 && magnitude < 1e12) {
        ryu::Buffer::new().format(number).to_owned()
    } else {
        number.to_string()
    };
    text.parse().unwrap_or(f64::from(number))
}

#[expect(
    clippy::cast_possible_truncation,
    reason = "PDF content streams use f32, keeping page coordinates well below 0.001 points"
)]
pub(crate) fn to_f32(value: f64) -> f32 {
    value as f32
}

#[cfg(test)]
mod tests;