Skip to main content

f_office_pdf/
lib.rs

1//! Streams a display list directly as PDF.
2//!
3//! [`write_pdf_to`] writes one PDF page for each page of a display list directly to any
4//! [`std::io::Write`] sink without buffering the full PDF document in memory, and [`write_pdf`]
5//! collects the same output into a `Vec<u8>`.
6//!
7//! Each glyph run becomes text in its subsetted CID font from the font database at the run's size
8//! and color. F-Office shapes all text itself, so glyph IDs pass through unchanged without
9//! reshaping or reordering. Each glyph sits at its display-list position and carries its text via
10//! `/ToUnicode` (and `/ActualText` when one glyph stands for multiple text strings). Rectangles,
11//! paths, axial gradients, clipped groups, and PNG/JPEG/GIF/BMP/TIFF images are emitted in
12//! painting order. Images are deduplicated and flushed straight to the sink on first use without
13//! retaining raw image bytes across pages.
14//!
15//! The PDF holds no dates and no XMP metadata, so the same display list and fonts always produce
16//! identical bytes.
17
18mod fonts;
19mod images;
20mod outline_font;
21mod page;
22mod stream;
23mod text;
24
25use std::collections::HashMap;
26use std::fmt;
27use std::io::Write;
28
29use f_office_fonts::{FontDb, FontId};
30use f_office_paint::{self as paint, DisplayList, GlyphRun, GradientStop, ImageFault, ImageFormat};
31use f_office_units::Length;
32use pdf_writer::Chunk;
33
34use crate::fonts::UsedFonts;
35use crate::images::EmittedImages;
36use crate::page::DocState;
37use crate::stream::StreamPdf;
38
39/// Why a display list could not be written as PDF.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum Error {
42    /// The display list has no page. A PDF needs at least one.
43    NoPages,
44    /// A page has a width or a height that is not positive.
45    PageSize,
46    /// A glyph run names a font that the font database does not hold.
47    UnknownFont(FontId),
48    /// A font from the font database cannot be parsed or embedded.
49    UnreadableFont(FontId),
50    /// A glyph run names a glyph that its font does not have.
51    UnknownGlyph {
52        /// The font of the run.
53        font: FontId,
54        /// The glyph ID.
55        glyph: u32,
56    },
57    /// A glyph's text range is not a range of whole characters in the text of its run.
58    TextRange,
59    /// A group's clip is an empty or invalid path.
60    Clip,
61    /// The PDF writer could not subset a font or write to the output sink.
62    Write(String),
63}
64
65impl fmt::Display for Error {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Self::NoPages => f.write_str("the display list has no page"),
69            Self::PageSize => f.write_str("a page has a size that is not positive"),
70            Self::UnknownFont(id) => write!(f, "the font database has no font {}", id.index()),
71            Self::UnreadableFont(id) => write!(f, "font {} cannot be embedded", id.index()),
72            Self::UnknownGlyph { font, glyph } => {
73                write!(f, "font {} has no glyph {glyph}", font.index())
74            }
75            Self::TextRange => f.write_str("a glyph's text range is not in its run's text"),
76            Self::Clip => f.write_str("a group's clip is not a path that krilla can build"),
77            Self::Write(message) => write!(f, "the PDF cannot be written: {message}"),
78        }
79    }
80}
81
82impl std::error::Error for Error {}
83
84/// What the PDF writer left out of a display list, and went on.
85#[derive(Clone, Debug, PartialEq, Eq, Hash)]
86#[non_exhaustive]
87pub enum Warning {
88    /// An image that the PDF leaves out: its format, and why.
89    ImageSkipped {
90        /// The image's format.
91        format: ImageFormat,
92        /// Why the PDF leaves it out.
93        fault: ImageFault,
94    },
95}
96
97impl Warning {
98    /// The warning's kind, a short name that stays the same across versions, for a caller
99    /// that counts warnings.
100    #[must_use]
101    pub fn kind(&self) -> &'static str {
102        match self {
103            Self::ImageSkipped { .. } => "pdf-image-skipped",
104        }
105    }
106}
107
108impl fmt::Display for Warning {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        match self {
111            Self::ImageSkipped { format, fault } => {
112                write!(
113                    f,
114                    "an image in {format} format is left out of the PDF: {fault}"
115                )
116            }
117        }
118    }
119}
120
121/// The warnings of a written PDF.
122pub type Warnings = f_office_warnings::Warnings<Warning>;
123
124/// A written PDF with its warnings.
125pub type Warned<T> = f_office_warnings::Warned<T, Warning>;
126
127/// Writes a display list as a PDF file into a `Vec<u8>`, returning the bytes with any warnings.
128///
129/// For large documents or file outputs, prefer [`write_pdf_to`] to stream objects directly to an
130/// [`std::io::Write`] sink without holding the whole PDF in memory.
131///
132/// # Errors
133///
134/// Returns an error when the list has no page, when a page size is not positive, when a glyph
135/// run names a font or a glyph that `fonts` does not hold, when a glyph's text range is not in
136/// its run's text, or when a font cannot be subsetted or written.
137pub fn write_pdf(list: &DisplayList, fonts: &FontDb) -> Result<Warned<Vec<u8>>, Error> {
138    let mut out = Vec::new();
139    let warned = write_pdf_to(list, fonts, &mut out)?;
140    Ok(Warned::new(out, warned.warnings))
141}
142
143/// Streams a display list directly as a PDF 1.7 document into `writer`, flushing each image
144/// `XObject`, page content stream, and subsetted font object immediately as it is produced.
145///
146/// # Errors
147///
148/// Returns an error when the list has no page, when a page size is not positive, when a glyph
149/// run names a font or a glyph that `fonts` does not hold, when a glyph's text range is not in
150/// its run's text, when a font cannot be subsetted, or when writing to `writer` fails.
151pub fn write_pdf_to<W: Write>(
152    list: &DisplayList,
153    fonts: &FontDb,
154    writer: &mut W,
155) -> Result<Warned<()>, Error> {
156    if list.pages().is_empty() {
157        return Err(Error::NoPages);
158    }
159    let mut pdf = StreamPdf::start(writer)?;
160    let pages_ref = pdf.alloc();
161    let mut state = DocState {
162        pdf,
163        fonts: UsedFonts::new(fonts),
164        images: EmittedImages::default(),
165        ext_gstates: HashMap::new(),
166        warnings: Warnings::new(),
167    };
168    let mut page_refs = Vec::with_capacity(list.pages().len());
169    for page in list.pages() {
170        page_refs.push(page::write_page(page, pages_ref, &mut state)?);
171    }
172    state.fonts.emit_all(&mut state.pdf)?;
173    let mut pages_chunk = Chunk::new();
174    let count = i32::try_from(page_refs.len())
175        .map_err(|_| Error::Write("too many pages for PDF".into()))?;
176    pages_chunk.pages(pages_ref).kids(page_refs).count(count);
177    state.pdf.emit(pages_ref, &pages_chunk)?;
178    state.pdf.finish(pages_ref)?;
179    Ok(Warned::new((), state.warnings))
180}
181
182/// The commands of a clip, where a clip of one rectangle gets a fourth line back to its first
183/// corner before its close so readers do not elide near-identity rectangular clips.
184pub(crate) fn clip_commands(commands: &[paint::PathCommand]) -> Vec<paint::PathCommand> {
185    use paint::PathCommand::{Close, LineTo, MoveTo};
186    match *commands {
187        [MoveTo(first), LineTo(a), LineTo(b), LineTo(c), Close] => {
188            vec![
189                MoveTo(first),
190                LineTo(a),
191                LineTo(b),
192                LineTo(c),
193                LineTo(first),
194                Close,
195            ]
196        }
197        [MoveTo(first), LineTo(a), LineTo(b), LineTo(c), LineTo(last)] if last == first => {
198            vec![
199                MoveTo(first),
200                LineTo(a),
201                LineTo(b),
202                LineTo(c),
203                LineTo(last),
204                Close,
205            ]
206        }
207        _ => commands.to_vec(),
208    }
209}
210
211/// The scale and local length of a picture's side so that `scale * printed(number) * stretch`
212/// matches `side` within [`SIDE_ERROR`].
213pub(crate) fn side_scale(side: f64, start: SideStart, stretch: f64) -> (f32, f32) {
214    let written = side / stretch;
215    let own = decimal(written);
216    if start.error(side, stretch, own) <= SIDE_ERROR {
217        return (1.0, own);
218    }
219    let mut scale = 2.0_f32;
220    for _ in 0..SIDE_SCALES {
221        let factor = printed(scale);
222        let number = nearest_printed(written, factor, to_f32(written / factor));
223        if start.error(side, factor * stretch, number) <= SIDE_ERROR {
224            return (scale, number);
225        }
226        scale = scale.next_up();
227    }
228    (1.0, own)
229}
230
231/// Where a picture's side starts in the transform that draws it.
232#[derive(Clone, Copy)]
233pub(crate) enum SideStart {
234    Corner,
235    Centre,
236}
237
238impl SideStart {
239    fn error(self, side: f64, scale: f64, number: f32) -> f64 {
240        let whole = (scale * printed(number) - side).abs();
241        match self {
242            Self::Corner => whole,
243            Self::Centre => {
244                let half = printed(number / 2.0);
245                let before = (scale * half - side / 2.0).abs();
246                let after = (scale * (printed(number) - half) - side / 2.0).abs();
247                before.max(after).max(whole)
248            }
249        }
250    }
251}
252
253#[expect(
254    clippy::cast_precision_loss,
255    reason = "the number of half-EMUs to the point is exact in double precision"
256)]
257const SIDE_ERROR: f64 = 0.4 / Length::UNITS_PER_POINT as f64;
258const SIDE_SCALES: usize = 4_096;
259
260/// Whole-point anchor keeping local coordinates small enough for exact half-EMU single-precision
261/// representation in PDF content streams.
262#[derive(Clone, Copy, Debug, PartialEq, Eq)]
263pub(crate) struct Anchor {
264    pub(crate) x: Length,
265    pub(crate) foot: Length,
266    pub(crate) y: Length,
267}
268
269impl Anchor {
270    const REACH: i64 = 256 * Length::UNITS_PER_POINT;
271
272    pub(crate) fn at(height: Length, x: Length, y: Length) -> Self {
273        let whole = |length: Length| {
274            let point = Length::UNITS_PER_POINT;
275            Length::from_units(length.units().div_euclid(point) * point)
276        };
277        let foot = whole(height - y);
278        Self {
279            x: whole(x),
280            foot,
281            y: height - foot,
282        }
283    }
284
285    pub(crate) fn middle(
286        height: Length,
287        (left, top): (Length, Length),
288        (right, bottom): (Length, Length),
289    ) -> Self {
290        let half = |a: Length, b: Length| Length::from_units(a.units().midpoint(b.units()));
291        Self::at(height, half(left, right), half(top, bottom))
292    }
293
294    pub(crate) fn reaches(self, x: Length, y: Length) -> bool {
295        (x - self.x).units().abs() < Self::REACH && (y - self.y).units().abs() < Self::REACH
296    }
297
298    pub(crate) fn of_line(height: Length, x: Length, y: Length) -> Self {
299        let anchor = Self::at(height, x, y);
300        if anchor.y != y {
301            return anchor;
302        }
303        let point = Length::from_units(Length::UNITS_PER_POINT);
304        Self {
305            x: anchor.x,
306            foot: anchor.foot - point,
307            y: anchor.y + point,
308        }
309    }
310
311    pub(crate) fn matrix(self) -> [f32; 6] {
312        [1.0, 0.0, 0.0, -1.0, points(self.x), points(self.foot)]
313    }
314
315    pub(crate) fn undone_matrix(self) -> [f32; 6] {
316        [1.0, 0.0, 0.0, -1.0, -points(self.x), points(self.foot)]
317    }
318
319    pub(crate) fn turned_matrix(self, turn: paint::Turn) -> [f32; 6] {
320        let [xx, yx, xy, yy] = turn_entries(turn);
321        [xx, -yx, xy, -yy, points(self.x), points(self.foot)]
322    }
323
324    pub(crate) fn local(self, x: Length, y: Length) -> (f32, f32) {
325        (
326            decimal(exact_points(x - self.x)),
327            decimal(exact_points(y - self.y)),
328        )
329    }
330}
331
332/// Whole-point anchor with optional scale for wide filled paths and rectangles.
333#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334pub(crate) struct FillAnchor {
335    pub(crate) anchor: Anchor,
336    hundredths: u32,
337}
338
339impl FillAnchor {
340    const REACH: f64 = 255.0;
341
342    pub(crate) fn middle(
343        height: Length,
344        (left, top): (Length, Length),
345        (right, bottom): (Length, Length),
346    ) -> Self {
347        let anchor = Anchor::middle(height, (left, top), (right, bottom));
348        let reach = [
349            left - anchor.x,
350            right - anchor.x,
351            top - anchor.y,
352            bottom - anchor.y,
353        ]
354        .into_iter()
355        .map(|distance| exact_points(distance).abs())
356        .fold(0.0, f64::max);
357        let hundredths = if reach < Self::REACH {
358            100
359        } else {
360            hundredths_above(reach / Self::REACH)
361        };
362        Self { anchor, hundredths }
363    }
364
365    fn scale(self) -> f64 {
366        printed(to_f32(f64::from(self.hundredths) / 100.0))
367    }
368
369    pub(crate) fn matrix(self) -> [f32; 6] {
370        let scale = to_f32(self.scale());
371        let Anchor { x, foot, .. } = self.anchor;
372        [scale, 0.0, 0.0, -scale, points(x), points(foot)]
373    }
374
375    fn number(self, value: f64) -> f32 {
376        if self.hundredths == 100 {
377            return decimal(value);
378        }
379        let scale = self.scale();
380        nearest_printed(value, scale, to_f32(value / scale))
381    }
382
383    pub(crate) fn local(self, x: Length, y: Length) -> (f32, f32) {
384        (
385            self.number(exact_points(x - self.anchor.x)),
386            self.number(exact_points(y - self.anchor.y)),
387        )
388    }
389
390    pub(crate) fn span(self, start: Length, length: Length) -> (f32, f32) {
391        let from = exact_points(start);
392        let to = from + exact_points(length);
393        (self.number(from.min(to)), self.number(from.max(to)))
394    }
395}
396
397#[expect(
398    clippy::cast_possible_truncation,
399    clippy::cast_sign_loss,
400    reason = "the ratio of a place on a page to the reach of a fill is positive and small"
401)]
402fn hundredths_above(ratio: f64) -> u32 {
403    (ratio * 100.0).ceil() as u32
404}
405
406pub(crate) fn upright_start(
407    turn: paint::Turn,
408    anchor: Anchor,
409    origin: &paint::Glyph,
410) -> (f32, f32) {
411    let [xx, yx, xy, yy] = [turn.xx, turn.yx, turn.xy, turn.yy].map(i64::from);
412    let (dx, dy) = (
413        exact_points(origin.x - anchor.x),
414        exact_points(origin.y - anchor.y),
415    );
416    let determinant = xx * yy - xy * yx;
417    if determinant == 0 {
418        return (to_f32(dx), to_f32(dy));
419    }
420    let [xx, yx, xy, yy, determinant] = [xx, yx, xy, yy, determinant].map(exact_count);
421    let scale = f64::from(paint::Turn::SCALE);
422    (
423        to_f32((yy * dx - xy * dy) * scale / determinant),
424        to_f32((xx * dy - yx * dx) * scale / determinant),
425    )
426}
427
428#[expect(
429    clippy::cast_precision_loss,
430    reason = "the entries of a turn and their products stay far below 2^53"
431)]
432fn exact_count(count: i64) -> f64 {
433    count as f64
434}
435
436pub(crate) fn turn_entries(turn: paint::Turn) -> [f32; 4] {
437    #[expect(
438        clippy::cast_precision_loss,
439        reason = "a turn's entries are millionths of at most a few units, which f32 holds to about 1e-7"
440    )]
441    [turn.xx, turn.yx, turn.xy, turn.yy].map(|entry| entry as f32 / paint::Turn::SCALE as f32)
442}
443
444pub(crate) fn upright_run(run: &GlyphRun, turn: paint::Turn) -> GlyphRun {
445    let mut upright = run.clone();
446    upright.turn = None;
447    let [xx, yx, xy, yy] = [turn.xx, turn.yx, turn.xy, turn.yy].map(i128::from);
448    let determinant = xx * yy - xy * yx;
449    if let (Some(first), true) = (run.glyphs.first(), determinant != 0) {
450        let (x0, y0) = (first.x.units(), first.y.units());
451        let scale = i128::from(paint::Turn::SCALE);
452        let back = |value: i128| i64::try_from(value * scale / determinant).unwrap_or(0);
453        for glyph in &mut upright.glyphs {
454            let dx = i128::from(glyph.x.units() - x0);
455            let dy = i128::from(glyph.y.units() - y0);
456            glyph.x = Length::from_units(x0 + back(yy * dx - xy * dy));
457            glyph.y = Length::from_units(y0 + back(xx * dy - yx * dx));
458        }
459    }
460    upright
461}
462
463pub(crate) fn stop_offset(place: u32) -> f32 {
464    to_f32(f64::from(place.min(GradientStop::END)) / f64::from(GradientStop::END))
465}
466
467pub(crate) fn path_anchor(height: Length, commands: &[paint::PathCommand]) -> Anchor {
468    path_bounds(commands).map_or(
469        Anchor::at(height, Length::ZERO, Length::ZERO),
470        |(low, high)| Anchor::middle(height, (low.x, low.y), (high.x, high.y)),
471    )
472}
473
474pub(crate) fn path_bounds(commands: &[paint::PathCommand]) -> Option<(paint::Point, paint::Point)> {
475    use paint::PathCommand::{Close, CubicTo, LineTo, MoveTo, QuadTo};
476    let points = commands.iter().flat_map(|command| match *command {
477        MoveTo(p) | LineTo(p) => vec![p],
478        QuadTo(c, p) => vec![c, p],
479        CubicTo(c0, c1, p) => vec![c0, c1, p],
480        Close => Vec::new(),
481    });
482    points.fold(None, |bounds: Option<(paint::Point, paint::Point)>, p| {
483        Some(bounds.map_or((p, p), |(low, high)| {
484            (
485                paint::Point {
486                    x: low.x.min(p.x),
487                    y: low.y.min(p.y),
488                },
489                paint::Point {
490                    x: high.x.max(p.x),
491                    y: high.y.max(p.y),
492                },
493            )
494        }))
495    })
496}
497
498pub(crate) fn points(length: Length) -> f32 {
499    to_f32(exact_points(length))
500}
501
502pub(crate) fn decimal(value: f64) -> f32 {
503    let nearest = to_f32(value);
504    if value.abs() < 256.0 {
505        return nearest;
506    }
507    nearest_printed(value, 1.0, nearest)
508}
509
510fn nearest_printed(value: f64, scale: f64, nearest: f32) -> f32 {
511    let error = |number: f32| (scale * printed(number) - value).abs();
512    let (mut best, mut best_error) = (nearest, error(nearest));
513    let (mut above, mut below) = (nearest, nearest);
514    for _ in 0..DECIMAL_NEIGHBORS {
515        above = above.next_up();
516        below = below.next_down();
517        for number in [above, below] {
518            let found = error(number);
519            if found < best_error {
520                (best, best_error) = (number, found);
521            }
522        }
523    }
524    best
525}
526
527const DECIMAL_NEIGHBORS: usize = 2;
528
529pub(crate) fn printed(number: f32) -> f64 {
530    let magnitude = number.abs();
531    let text = if number == 0.0 || (magnitude > 1e-6 && magnitude < 1e12) {
532        ryu::Buffer::new().format(number).to_owned()
533    } else {
534        number.to_string()
535    };
536    text.parse().unwrap_or(f64::from(number))
537}
538
539#[expect(
540    clippy::cast_precision_loss,
541    reason = "page coordinates stay far below 2^53 half-EMUs, so the conversion is exact"
542)]
543pub(crate) fn exact_points(length: Length) -> f64 {
544    length.units() as f64 / Length::UNITS_PER_POINT as f64
545}
546
547#[expect(
548    clippy::cast_possible_truncation,
549    reason = "PDF content streams use f32, keeping page coordinates well below 0.001 points"
550)]
551pub(crate) fn to_f32(value: f64) -> f32 {
552    value as f32
553}
554
555#[cfg(test)]
556mod tests;