ferri-pdf 0.1.10

HTML and CSS to PDF renderer for print, in pure Rust
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Display lists drawn onto a surface: scopes nest pushes and pops, filtered groups are
//! drawn through their filters, and backdrops and additive groups read back what the
//! list painted before them.
use crate::graphics::{BlendMode, DisplayItem, Rect};
use crate::layout::TextLine;
use crate::writer::{
    PdfError, backdrops::Prepared, images::ImageWriter, painting, raster::RasterContext,
    text::TextWriter,
};
use krilla::{geom::Transform, num::NormalizedF32, surface::Surface};

/// What one page's display list draws with.
pub(super) struct Painter<'a, 'w, 'f> {
    pub(super) lines: &'a [TextLine],
    pub(super) page: usize,
    /// Page content area and positioning area of document `fixed` backgrounds.
    pub(super) page_area: Rect,
    pub(super) text: &'w mut TextWriter<'f>,
    pub(super) fonts: &'f crate::fonts::FontBook,
    pub(super) images: &'w mut ImageWriter,
    pub(super) raster: &'w RasterContext<'w>,
    pub(super) prepared: Prepared,
}

/// Where the content of an enclosing group or Backdrop Root starts in the items a frame draws,
/// and the raster density of its drawing space there.
#[derive(Clone, Copy)]
pub(super) struct Origin {
    pub(super) index: usize,
    pub(super) density: f32,
}

#[derive(Clone, Copy)]
enum Kind {
    Clip,
    Transform([f32; 6]),
    /// A transparency group, whose content is the backdrop of blending inside it.
    Group(Origin),
    /// A Backdrop Root (Filter Effects 2 ยง3).
    Root(Origin),
}

/// An open push: the surface pushes to pop and the drawing space to restore.
struct Scope {
    pops: usize,
    space: Space,
    kind: Kind,
}

/// The open scopes of a frame whose items start at `frame`.
pub(super) struct Scopes<'s> {
    frame: Origin,
    open: &'s [Scope],
}
impl Scopes<'_> {
    /// The innermost enclosing Backdrop Root's content start, or the frame's, which the
    /// document root, filters and masks begin, and the transform from the current drawing
    /// space to the space there.
    pub(super) fn backdrop_root(&self) -> (Origin, tiny_skia::Transform) {
        self.innermost(|kind| match kind {
            Kind::Root(origin) => Some(origin),
            Kind::Clip | Kind::Transform(_) | Kind::Group(_) => None,
        })
    }
    /// The innermost enclosing transparency group's content start, likewise.
    pub(super) fn group(&self) -> (Origin, tiny_skia::Transform) {
        self.innermost(|kind| match kind {
            Kind::Group(origin) => Some(origin),
            Kind::Clip | Kind::Transform(_) | Kind::Root(_) => None,
        })
    }
    fn innermost(&self, origin: impl Fn(Kind) -> Option<Origin>) -> (Origin, tiny_skia::Transform) {
        let found = self
            .open
            .iter()
            .enumerate()
            .rev()
            .find_map(|(index, scope)| origin(scope.kind).map(|origin| (index + 1, origin)));
        let (inner, origin) = found.unwrap_or((0, self.frame));
        let transform =
            self.open[inner..]
                .iter()
                .fold(
                    tiny_skia::Transform::identity(),
                    |transform, scope| match scope.kind {
                        Kind::Transform(matrix) => transform.pre_concat(matrix_transform(matrix)),
                        Kind::Clip | Kind::Group(_) | Kind::Root(_) => transform,
                    },
                );
        (origin, transform)
    }
}

/// A display-list affine `[a, b, c, d, e, f]` as a transform.
pub(super) fn matrix_transform([a, b, c, d, e, f]: [f32; 6]) -> tiny_skia::Transform {
    tiny_skia::Transform::from_row(a, b, c, d, e, f)
}

/// The drawing space of a surface: the physical area visible in it, and how many page points
/// one of its units spans, which raster effects resolve at.
#[derive(Clone, Copy)]
pub(super) struct Space {
    pub(super) viewport: Rect,
    pub(super) scale: f32,
}
impl Space {
    /// The space nested groups start in: krilla draws a group from the identity transform.
    fn nested(self, surface: &Surface<'_>) -> Result<Self, PdfError> {
        Ok(Self {
            viewport: painting::local_bounds(self.viewport, surface)?,
            scale: self.scale * painting::transform_scale(surface.cur_transform()),
        })
    }
}

impl Painter<'_, '_, '_> {
    /// Draws `items`, which open and close their own scopes.
    pub(super) fn draw(
        &mut self,
        items: &[DisplayItem],
        space: Space,
        surface: &mut Surface<'_>,
    ) -> Result<(), PdfError> {
        self.draw_frame(items, space, surface, false)
    }

    /// Draws the start of a display list, closing the scopes still open where it ends.
    pub(super) fn draw_prefix(
        &mut self,
        items: &[DisplayItem],
        space: Space,
        surface: &mut Surface<'_>,
    ) -> Result<(), PdfError> {
        self.draw_frame(items, space, surface, true)
    }

    /// The raster density of `space` as the surface currently draws it.
    pub(super) fn density(&self, space: Space, surface: &Surface<'_>) -> f32 {
        self.raster.pixels_per_point
            * space.scale
            * painting::transform_scale(surface.cur_transform())
    }

    fn draw_frame(
        &mut self,
        items: &[DisplayItem],
        space: Space,
        surface: &mut Surface<'_>,
        prefix: bool,
    ) -> Result<(), PdfError> {
        let mut scopes = Vec::new();
        let prepared = self.prepared.mark();
        let result = self.draw_scoped(items, space, &mut scopes, surface);
        let unclosed = !scopes.is_empty();
        while let Some(scope) = scopes.pop() {
            painting::pop_clips(scope.pops, surface);
        }
        self.prepared.release(prepared);
        result?;
        if unclosed && !prefix {
            return Err(PdfError::InvalidGeometry);
        }
        Ok(())
    }

    fn draw_scoped(
        &mut self,
        items: &[DisplayItem],
        mut space: Space,
        scopes: &mut Vec<Scope>,
        surface: &mut Surface<'_>,
    ) -> Result<(), PdfError> {
        let frame = Origin {
            index: 0,
            density: self.density(space, surface),
        };
        let mut index = 0;
        while index < items.len() {
            let depth = surface.push_depth();
            match self.draw_item(items, index, space, scopes, frame, surface) {
                Ok(next) => (index, space) = next,
                Err(error) if error.is_internal() => return Err(error),
                Err(error) => index = self.omit_item(items, index, depth, &error, surface)?,
            }
        }
        Ok(())
    }

    /// Reports the runs the text writer left out because PDF cannot write them.
    pub(super) fn record_unwritable_runs(&mut self) {
        if let Some(number) = self.text.take_unwritable() {
            self.images.record(crate::writer::PaintDiagnostic::Omitted {
                reason: PdfError::UnwritableNumber(number).to_string(),
            });
        }
    }

    /// Omits the item at `index` that failed to draw with `error`, with the content it groups,
    /// closing what it pushed past `depth`; returns the index of the item after it.
    // Out of `draw_scoped`, whose frame each nested group stacks.
    #[inline(never)]
    fn omit_item(
        &mut self,
        items: &[DisplayItem],
        index: usize,
        depth: usize,
        error: &PdfError,
        surface: &mut Surface<'_>,
    ) -> Result<usize, PdfError> {
        while surface.push_depth() > depth {
            surface.pop();
        }
        self.images.record(crate::writer::PaintDiagnostic::Omitted {
            reason: error.to_string(),
        });
        let next = index + 1;
        Ok(if items[index].is_push() {
            next + group_length(&items[next..])? + 1
        } else {
            next
        })
    }

    /// Draws the item at `index` of `items` in `space`; returns the index of the next item to
    /// draw and the space it draws in.
    fn draw_item(
        &mut self,
        items: &[DisplayItem],
        index: usize,
        space: Space,
        scopes: &mut Vec<Scope>,
        frame: Origin,
        surface: &mut Surface<'_>,
    ) -> Result<(usize, Space), PdfError> {
        let item = &items[index];
        let unwritable = match item {
            // The text writer leaves out the line's runs it cannot write.
            DisplayItem::Text { line } => self.lines.get(*line).and_then(|line| {
                crate::writer::numbers::unwritable_number(&[line.x, line.baseline])
            }),
            _ => crate::writer::numbers::unwritable_number(item),
        };
        if let Some(number) = unwritable {
            // A box that paints nothing loses nothing by not being written.
            if let DisplayItem::Box(paint) = item
                && !paint.has_ink()
            {
                return Ok((index + 1, space));
            }
            return Err(PdfError::UnwritableNumber(number));
        }
        match item {
            DisplayItem::Image(_)
            | DisplayItem::Frame(_)
            | DisplayItem::Box(_)
            | DisplayItem::Text { .. }
            | DisplayItem::TextShadow(_)
            | DisplayItem::Decoration(_)
            | DisplayItem::Backdrop(_)
            | DisplayItem::Scene(_) => {
                let drawn = self.draw_paint(item, space, surface);
                self.record_unwritable_runs();
                drawn.map(|()| (index + 1, space))
            }
            DisplayItem::PushProjection(_)
            | DisplayItem::PushBlend(BlendMode::PlusDarker | BlendMode::PlusLighter)
            | DisplayItem::PushFilter(_)
            | DisplayItem::PushMask(_) => self
                .draw_group(items, index + 1, space, scopes, frame, surface)
                .map(|next| (next, space)),
            _ => self
                .open_scope(items, index + 1, space, scopes, frame, surface)
                .map(|space| (index + 1, space)),
        }
    }

    // The helpers below keep their locals off `draw_item`, whose frame each nested group
    // stacks.
    /// Draws the group `items[index - 1]` opens, with its content; returns the index of the
    /// item after the group.
    #[inline(never)]
    fn draw_group(
        &mut self,
        items: &[DisplayItem],
        index: usize,
        space: Space,
        scopes: &mut Vec<Scope>,
        frame: Origin,
        surface: &mut Surface<'_>,
    ) -> Result<usize, PdfError> {
        let end = index + group_length(&items[index..])?;
        let group = &items[index..end];
        match &items[index - 1] {
            DisplayItem::PushProjection(projection) => {
                crate::writer::projection::draw(self, *projection, group, space, surface)
            }
            DisplayItem::PushBlend(mode @ (BlendMode::PlusDarker | BlendMode::PlusLighter)) => {
                let open = Scopes {
                    frame,
                    open: scopes,
                };
                crate::writer::backdrops::additive(
                    self,
                    *mode,
                    items,
                    index - 1..end,
                    &open,
                    space,
                    surface,
                )
            }
            DisplayItem::PushFilter(filter) => {
                crate::writer::filters::draw(self, filter, group, space, surface)
            }
            DisplayItem::PushMask(mask) => {
                crate::writer::masks::draw(self, mask, group, space, surface)
            }
            _ => unreachable!("only group items are drawn as groups"),
        }
        .map(|()| end + 1)
    }

    /// Opens or closes the scope `items[index - 1]` opens or closes; returns the space the
    /// items after it draw in.
    #[inline(never)]
    fn open_scope(
        &mut self,
        items: &[DisplayItem],
        index: usize,
        mut space: Space,
        scopes: &mut Vec<Scope>,
        frame: Origin,
        surface: &mut Surface<'_>,
    ) -> Result<Space, PdfError> {
        match &items[index - 1] {
            DisplayItem::PushClip(clip) => {
                scopes.push(Scope {
                    pops: painting::push_clip(clip, space.viewport, surface)?,
                    space,
                    kind: Kind::Clip,
                });
            }
            DisplayItem::PushTransform(matrix) => {
                let [a, b, c, d, e, f] = *matrix;
                surface.push_transform(&Transform::from_row(a, b, c, d, e, f));
                scopes.push(Scope {
                    pops: 1,
                    space,
                    kind: Kind::Transform(*matrix),
                });
            }
            DisplayItem::PushOpacity(alpha) => {
                let opacity = NormalizedF32::new(*alpha).ok_or(PdfError::InvalidAlpha(*alpha))?;
                let nested = if opacity == NormalizedF32::ONE {
                    space
                } else {
                    space.nested(surface)?
                };
                surface.push_opacity(opacity);
                scopes.push(Scope {
                    pops: 1,
                    space,
                    kind: Kind::Group(Origin {
                        index,
                        density: self.density(nested, surface),
                    }),
                });
                space = nested;
            }
            DisplayItem::PushBlend(mode) => {
                let nested = space.nested(surface)?;
                let pops = painting::push_blend(*mode, surface)?;
                scopes.push(Scope {
                    pops,
                    space,
                    kind: Kind::Group(Origin {
                        index,
                        density: self.density(nested, surface),
                    }),
                });
                space = nested;
            }
            DisplayItem::PushBackdropRoot => {
                let open = Scopes {
                    frame,
                    open: scopes,
                };
                crate::writer::backdrops::prepare(self, items, index - 1, &open)?;
                scopes.push(Scope {
                    pops: 0,
                    space,
                    kind: Kind::Root(Origin {
                        index,
                        density: self.density(space, surface),
                    }),
                });
            }
            DisplayItem::Pop => {
                let scope = scopes.pop().ok_or(PdfError::InvalidGeometry)?;
                painting::pop_clips(scope.pops, surface);
                space = scope.space;
            }

            _ => unreachable!("only scope items open or close scopes"),
        }
        Ok(space)
    }

    /// Draws `item`, which opens no scope, in `space`.
    // Out of `draw_item`, whose frame each nested group stacks.
    #[inline(never)]
    fn draw_paint(
        &mut self,
        item: &DisplayItem,
        space: Space,
        surface: &mut Surface<'_>,
    ) -> Result<(), PdfError> {
        match item {
            DisplayItem::Image(paint) => {
                self.images.scale = space.scale;
                match paint.image.as_ref() {
                    crate::images::Image::Svg(svg) if svg.has_layer_masks() => {
                        crate::writer::masks::draw_svg(self, paint, space, surface)?;
                    }
                    _ => self.images.draw(paint, space.viewport, surface)?,
                }
            }
            DisplayItem::Frame(frame) => {
                let mut context = FlowContext {
                    page: self.page,
                    text: self.text,
                    fonts: self.fonts,
                    raster: self.raster,
                };
                draw_flow(frame, &mut context, self.images, space, surface)?;
            }
            DisplayItem::Box(box_paint) => {
                self.images.scale = space.scale;
                let mut context = FlowContext {
                    page: self.page,
                    text: self.text,
                    fonts: self.fonts,
                    raster: self.raster,
                };
                painting::draw(
                    box_paint,
                    self.page_area,
                    space.viewport,
                    surface,
                    self.images,
                    &mut |area, images, surface| {
                        draw_flow(area, &mut context, images, space, surface)
                    },
                )?;
            }
            DisplayItem::Text { line } => {
                let fragment = self
                    .lines
                    .get(*line)
                    .ok_or(PdfError::InvalidTextReference {
                        page: self.page,
                        line: *line,
                    })?;
                self.text.draw(fragment, surface)?;
            }
            DisplayItem::TextShadow(shadow) => crate::writer::text_shadows::draw(
                shadow,
                self.text,
                self.fonts,
                space.viewport,
                surface,
            )?,
            DisplayItem::Decoration(decoration) => {
                for fill in decoration.fills() {
                    painting::draw_fill(fill, space.viewport, surface)?;
                }
            }
            DisplayItem::Backdrop(backdrop) => {
                crate::writer::backdrops::draw(self, backdrop, item, space, surface)?;
            }
            DisplayItem::Scene(scene) => {
                crate::writer::scene::draw(self, scene, space, surface)?;
            }
            _ => unreachable!("only items opening no scope are painted alone"),
        }
        Ok(())
    }
}

/// What an independent flow inside a page's display list draws its text with.
pub(super) struct FlowContext<'c, 'f> {
    page: usize,
    text: &'c mut TextWriter<'f>,
    fonts: &'f crate::fonts::FontBook,
    raster: &'c RasterContext<'c>,
}

/// Draws a flow in its own coordinates and text lines, placed by its matrix.
fn draw_flow(
    flow: &crate::graphics::FlowPaint,
    context: &mut FlowContext<'_, '_>,
    images: &mut ImageWriter,
    space: Space,
    surface: &mut Surface<'_>,
) -> Result<(), PdfError> {
    let [a, b, c, d, e, f] = flow.matrix;
    surface.push_transform(&Transform::from_row(a, b, c, d, e, f));
    let result = Painter {
        lines: &flow.lines,
        page: context.page,
        page_area: flow.area,
        text: context.text,
        fonts: context.fonts,
        images,
        raster: context.raster,
        prepared: Prepared::default(),
    }
    .draw(&flow.items, space, surface);
    surface.pop();
    result
}

/// Paints a nested document's viewport or an element's rendering into the paint rectangle,
/// with its own text lines, faces and SVG definitions.
pub(super) fn draw_viewport(
    paint: &crate::graphics::ImagePaint,
    view: &crate::layout::ViewportPaint,
    images: &mut ImageWriter,
    space: Space,
    surface: &mut Surface<'_>,
) -> Result<(), PdfError> {
    if view.area.width <= 0.0 || view.area.height <= 0.0 {
        return Ok(());
    }
    // Element IDs belong to their documents, so a nested document's renderings join the
    // writer's.
    images.elements.extend(
        view.elements
            .iter()
            .map(|(element, rendering)| (*element, rendering.clone())),
    );
    let clips = paint
        .clip
        .as_ref()
        .map(|clip| painting::push_clip(clip, space.viewport, surface))
        .transpose()?
        .unwrap_or(0);
    let scale = [
        paint.rect.width / view.area.width,
        paint.rect.height / view.area.height,
    ];
    let offset = [
        paint.rect.x - view.area.x * scale[0],
        paint.rect.y - view.area.y * scale[1],
    ];
    surface.push_transform(&Transform::from_row(
        scale[0], 0.0, 0.0, scale[1], offset[0], offset[1],
    ));
    let raster = RasterContext {
        pixels_per_point: images.pixels_per_point,
        definitions: &view.definitions,
    };
    let mut text = TextWriter::new(&view.fonts);
    let drawn = Painter {
        lines: &view.lines,
        page: 0,
        page_area: view.area,
        text: &mut text,
        fonts: &view.fonts,
        images,
        raster: &raster,
        prepared: Prepared::default(),
    }
    // The drawing space's viewport is the visible area of the surface, which the pushed
    // transform does not move.
    .draw(&view.items, space, surface);
    surface.pop();
    painting::pop_clips(clips, surface);
    drawn
}

/// The number of items before the `Pop` closing a group that `items` follow.
pub(super) fn group_length(items: &[DisplayItem]) -> Result<usize, PdfError> {
    let mut depth = 0_usize;
    for (index, item) in items.iter().enumerate() {
        match item {
            DisplayItem::Pop if depth == 0 => return Ok(index),
            DisplayItem::Pop => depth -= 1,
            push if push.is_push() => depth += 1,
            _ => {}
        }
    }
    Err(PdfError::InvalidGeometry)
}