ferri-pdf 0.1.2

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
mod dimensions;
use crate::document::{PageBox, Paragraph};
use crate::graphics::{BoxDecoration, BoxPaint, DisplayItem, Rect};
use crate::layout::measure::Measurer;
use crate::layout::{LayoutError, TextLine};
use crate::style::{BoxSizing, MarginLocation, PageMargin, Size, VerticalAlign};
use crate::text::Line;
use dimensions::{Variable, variable};

const HORIZONTAL: usize = 0;
const VERTICAL: usize = 1;
const START: usize = 0;
const CENTER: usize = 1;
const END: usize = 2;
const GROUPS: [[MarginLocation; 3]; 4] = [
    [
        MarginLocation::TopLeft,
        MarginLocation::TopCenter,
        MarginLocation::TopRight,
    ],
    [
        MarginLocation::BottomLeft,
        MarginLocation::BottomCenter,
        MarginLocation::BottomRight,
    ],
    [
        MarginLocation::LeftTop,
        MarginLocation::LeftMiddle,
        MarginLocation::LeftBottom,
    ],
    [
        MarginLocation::RightTop,
        MarginLocation::RightMiddle,
        MarginLocation::RightBottom,
    ],
];
struct Prepared<'a> {
    margin: &'a PageMargin,
    decoration: &'a BoxDecoration,
    paragraph: Option<Paragraph>,
    padding: [f32; 4],
    borders: [f32; 4],
    margins: [Option<f32>; 4],
    specified: [Option<f32>; 2],
    start: [f32; 2],
    content: [f32; 2],
    lines: Vec<Line>,
}
impl Prepared<'_> {
    fn inline_axis(&self) -> usize {
        if self.margin.style.used_writing_mode().vertical() {
            VERTICAL
        } else {
            HORIZONTAL
        }
    }
    fn block_axis(&self) -> usize {
        1 - self.inline_axis()
    }
    fn sides(axis: usize) -> [usize; 2] {
        if axis == HORIZONTAL { [3, 1] } else { [0, 2] }
    }
    fn edges(&self, axis: usize) -> f32 {
        Self::sides(axis)
            .iter()
            .map(|&i| self.padding[i] + self.borders[i])
            .sum()
    }
    fn outer_edges(&self, axis: usize) -> f32 {
        self.edges(axis)
            + Self::sides(axis)
                .iter()
                .map(|&i| self.margins[i].unwrap_or(0.0))
                .sum::<f32>()
    }
    fn fixed(&mut self, axis: usize, available: f32) {
        let [start, end] = Self::sides(axis).map(|i| self.margins[i].unwrap_or(0.0));
        self.start[axis] = start;
        // The fixed dimension fills the margin area regardless of width/height declarations.
        self.content[axis] = available - self.edges(axis) - start - end;
    }
    fn variable(&mut self, axis: usize, available: f32, outer: f32, position: usize) {
        self.content[axis] = (outer - self.outer_edges(axis)).max(0.0);
        let offset = match position {
            START => 0.0,
            CENTER => (available - outer) / 2.0,
            END => available - outer,
            _ => unreachable!(),
        };
        self.start[axis] = offset + self.margins[Self::sides(axis)[0]].unwrap_or(0.0);
    }
    fn validate(&self) -> Result<(), LayoutError> {
        let values = self
            .padding
            .iter()
            .chain(self.borders.iter())
            .chain(self.margins.iter().flatten())
            .chain(self.specified.iter().flatten())
            .chain(self.start.iter())
            .chain(self.content.iter());
        if values.into_iter().any(|value| !value.is_finite())
            || [HORIZONTAL, VERTICAL]
                .iter()
                .any(|&axis| !self.outer_edges(axis).is_finite())
        {
            return Err(LayoutError::NonFinitePageMarginGeometry {
                location: self.margin.location,
            });
        }
        Ok(())
    }
    fn layout(&mut self, measurer: &Measurer<'_>) -> Result<(), LayoutError> {
        self.validate()?;
        self.lines = self
            .paragraph
            .as_ref()
            .map(|p| measurer.text_lines(p, self.content[self.inline_axis()], &[]))
            .transpose()?
            .unwrap_or_default();
        Ok(())
    }
    fn block_extent(&self) -> f32 {
        self.lines.iter().map(|line| line.height).sum()
    }
    fn paint(
        mut self,
        origin: [f32; 2],
        index: usize,
        page: &mut Vec<TextLine>,
        display: &mut Vec<DisplayItem>,
    ) -> Result<(), LayoutError> {
        self.validate()?;
        let block_axis = self.block_axis();
        let vertical = self.inline_axis() == VERTICAL;
        let mut used = 0.0;
        let mut retained = 0;
        for line in &self.lines {
            if self.content[block_axis] < 0.0
                || (retained > 0 && used + line.height > self.content[block_axis])
            {
                break;
            }
            used += line.height;
            retained += 1;
        }
        self.lines.truncate(retained);
        let style = &self.margin.style;
        let rect = Rect {
            x: origin[0] + self.start[0],
            y: origin[1] + self.start[1],
            width: self.content[0] + self.edges(0),
            height: self.content[1] + self.edges(1),
        };
        if [
            rect.x,
            rect.y,
            rect.width,
            rect.height,
            rect.x + rect.width,
            rect.y + rect.height,
        ]
        .iter()
        .any(|value| !value.is_finite())
        {
            return Err(LayoutError::NonFinitePageMarginGeometry {
                location: self.margin.location,
            });
        }
        let paint = BoxPaint {
            padding: self.padding,
            ..BoxPaint::whole(rect, self.decoration.clone())
        };
        let outline = paint.outline();
        if self.decoration.is_visible() {
            display.push(DisplayItem::Box(paint));
        }
        let inline_extent = if vertical {
            self.lines.iter().map(|line| line.width).fold(0.0, f32::max)
        } else {
            self.content[HORIZONTAL]
        };
        let physical_height = if vertical {
            inline_extent
        } else {
            self.block_extent()
        };
        let extra = self.content[VERTICAL] - physical_height;
        let offset = match style.table.vertical_align {
            VerticalAlign::Middle => extra / 2.0,
            VerticalAlign::Bottom => extra,
            VerticalAlign::Top
            | VerticalAlign::Baseline
            | VerticalAlign::BaselineMiddle
            | VerticalAlign::Sub
            | VerticalAlign::Super
            | VerticalAlign::TextTop
            | VerticalAlign::TextBottom
            | VerticalAlign::Length(_) => 0.0,
        };
        let content_origin = [
            rect.x + self.padding[3] + self.borders[3],
            rect.y + self.padding[0] + self.borders[0] + offset,
        ];
        let mut frame_lines = Vec::new();
        let mut frame_items = Vec::new();
        let (text_lines, text_items) = if vertical {
            (&mut frame_lines, &mut frame_items)
        } else {
            (&mut *page, &mut *display)
        };
        let mut y = if vertical { 0.0 } else { content_origin[1] };
        for line in self.lines {
            let x = if vertical { 0.0 } else { content_origin[0] }
                + line.alignment_offset(inline_extent, style.used_rtl());
            let baseline = y + line.ascent;
            let [below, above] =
                crate::layout::inline::decoration_items(&line.decorations, x, baseline);
            text_items.extend(below);
            text_items.push(DisplayItem::Text {
                line: text_lines.len(),
            });
            text_items.extend(above);
            text_lines.push(TextLine {
                paragraph: index,
                text: line.text,
                x,
                baseline,
                width: line.width,
                height: line.height,
                runs: line.runs,
                font_size: style.size,
                color: style.color,
            });
            y += line.height;
        }
        if vertical {
            let size = [self.content[HORIZONTAL], inline_extent];
            crate::layout::writing::Frame::physical(crate::style::logical::Flow::used(style), size)
                .items(&mut frame_items);
            display.push(DisplayItem::Frame(Box::new(crate::graphics::FlowPaint {
                matrix: [1.0, 0.0, 0.0, 1.0, content_origin[0], content_origin[1]],
                area: Rect {
                    x: 0.0,
                    y: 0.0,
                    width: size[0],
                    height: size[1],
                },
                items: frame_items,
                lines: frame_lines,
            })));
        }
        // The outline paints over the margin box's content (CSS UI 4 §3.1).
        display.extend(outline.map(DisplayItem::Box));
        Ok(())
    }
}
fn prepare<'a>(
    margin: &'a PageMargin,
    decoration: &'a BoxDecoration,
    containing: [f32; 2],
    page: usize,
    pages: usize,
    strings: &crate::layout::strings::PageStrings,
) -> Result<Prepared<'a>, LayoutError> {
    let style = &margin.style;
    let bases = [containing[1], containing[0], containing[1], containing[0]];
    let padding = std::array::from_fn(|i| style.padding[i].resolve(bases[i]));
    let borders = style
        .decoration
        .borders
        .map(crate::graphics::Border::used_width);
    let margins = std::array::from_fn(|i| style.margin[i].resolve(bases[i]));
    let mut specified = [style.width.resolve(containing[0]), None];
    if style.box_sizing == BoxSizing::BorderBox {
        for axis in [HORIZONTAL, VERTICAL] {
            let edges = Prepared::sides(axis)
                .iter()
                .map(|&i| padding[i] + borders[i])
                .sum::<f32>();
            specified[axis] = specified[axis].map(|size| (size - edges).max(0.0));
        }
    }
    Ok(Prepared {
        margin,
        decoration,
        paragraph: Paragraph::generated_output(
            &margin.content.page_output_with_strings(
                page,
                pages,
                crate::document::MAX_INLINE_TEXT_BYTES,
                &style.quotes,
                &mut |request| Ok(strings.text(page - 1, request)),
            )?,
            style,
        )?,
        padding,
        borders,
        margins,
        specified,
        start: [0.0; 2],
        content: [0.0; 2],
        lines: Vec::new(),
    })
}

pub(super) fn render(
    page_boxes: &[std::sync::Arc<PageBox>],
    strings: &crate::layout::strings::PageStrings,
    measurer: &Measurer<'_>,
    first_index: usize,
    pages: &mut [Vec<TextLine>],
    display: &mut [Vec<DisplayItem>],
) -> Result<(), LayoutError> {
    let total = pages.len();
    for (number, (page_lines, display)) in pages.iter_mut().zip(display).enumerate() {
        let page = &page_boxes[number];
        let margins: Vec<_> = page
            .margins
            .iter()
            .map(|margin| (&margin.margin, &margin.decoration))
            .collect();
        if margins.is_empty() {
            continue;
        }
        let page_box = page.geometry.margin_box();
        let [width, height] = [page_box.width, page_box.height];
        let [top, right, bottom, left] = page.geometry.margin;
        let groups = [
            ([left, 0.0], [width - left - right, top], HORIZONTAL),
            (
                [left, height - bottom],
                [width - left - right, bottom],
                HORIZONTAL,
            ),
            ([0.0, top], [left, height - top - bottom], VERTICAL),
            (
                [width - right, top],
                [right, height - top - bottom],
                VERTICAL,
            ),
        ];
        let page = page_lines;
        for (locations, (origin, containing, axis)) in GROUPS.iter().zip(groups) {
            let mut boxes: [Option<Prepared<'_>>; 3] = [None, None, None];
            let mut dimensions = [Variable::default(); 3];
            for (position, location) in locations.iter().enumerate() {
                let Some((margin, decoration)) = margins
                    .iter()
                    .find(|(margin, _)| margin.location == *location)
                else {
                    continue;
                };
                let mut prepared =
                    prepare(margin, decoration, containing, number + 1, total, strings)?;
                prepared.validate()?;
                let fixed_axis = 1 - axis;
                prepared.fixed(fixed_axis, containing[fixed_axis]);
                let bounds = if axis == prepared.inline_axis() {
                    let intrinsic = prepared
                        .paragraph
                        .as_ref()
                        .map(|p| measurer.intrinsic_widths(p, &[]))
                        .transpose()?
                        .unwrap_or_default();
                    [intrinsic.min, intrinsic.max]
                } else {
                    prepared.layout(measurer)?;
                    [prepared.block_extent(); 2]
                };
                if axis == HORIZONTAL
                    && let Size::Intrinsic(keyword) = prepared.margin.style.width
                {
                    let available = containing[axis] - prepared.outer_edges(axis);
                    prepared.specified[axis] = Some(keyword.resolve(
                        crate::style::IntrinsicWidths {
                            min: bounds[0],
                            max: bounds[1],
                        },
                        Some(available.max(0.0)),
                    ));
                }
                let edges = prepared.outer_edges(axis);
                dimensions[position] = Variable {
                    min: bounds[0] + edges,
                    max: bounds[1] + edges,
                    specified: prepared.specified[axis].map(|size| size + edges),
                    generated: true,
                };
                boxes[position] = Some(prepared);
            }
            let sizes = variable(dimensions, containing[axis]);
            for (position, prepared) in boxes.into_iter().enumerate() {
                if let Some(mut prepared) = prepared {
                    prepared.variable(axis, containing[axis], sizes[position], position);
                    prepared.layout(measurer)?;
                    let index = first_index + prepared.margin.location as usize;
                    prepared.paint(origin, index, page, display)?;
                }
            }
        }
        for (location, origin, containing) in [
            (MarginLocation::TopLeftCorner, [0.0, 0.0], [left, top]),
            (
                MarginLocation::TopRightCorner,
                [width - right, 0.0],
                [right, top],
            ),
            (
                MarginLocation::BottomLeftCorner,
                [0.0, height - bottom],
                [left, bottom],
            ),
            (
                MarginLocation::BottomRightCorner,
                [width - right, height - bottom],
                [right, bottom],
            ),
        ] {
            if let Some((margin, decoration)) = margins
                .iter()
                .find(|(margin, _)| margin.location == location)
            {
                let mut prepared =
                    prepare(margin, decoration, containing, number + 1, total, strings)?;
                prepared.validate()?;
                for axis in [HORIZONTAL, VERTICAL] {
                    prepared.fixed(axis, containing[axis]);
                }
                prepared.layout(measurer)?;
                prepared.paint(origin, first_index + location as usize, page, display)?;
            }
        }
    }
    Ok(())
}