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
// SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT

//! Low-level PDF rendering utilities.
//!
//! This module provides low-level abstractions over [`printpdf`][]:  A [`Renderer`][] creates a
//! document with one or more pages with different sizes.  A [`Page`][] has one or more layers, all
//! of the same size.  A [`Layer`][] can be used to access its [`Area`][].
//!
//! An [`Area`][] is a view on a full layer or on a part of a layer.  It can be used to print
//! lines and text.  For more advanced text formatting, you can create a [`TextSection`][] from an
//! [`Area`][].
//!
//! [`printpdf`]: https://docs.rs/printpdf/latest/printpdf
//! [`Renderer`]: struct.Renderer.html
//! [`Page`]: struct.Page.html
//! [`Layer`]: struct.Layer.html
//! [`Area`]: struct.Area.html
//! [`TextSection`]: struct.TextSection.html

use std::fs;
use std::io;
use std::path;

use crate::error::Error;
use crate::fonts;
use crate::style::{Color, Style};
use crate::{Margins, Mm, Position, Size};

/// Renders a PDF document with one or more pages.
///
/// This is a wrapper around a [`printpdf::PdfDocumentReference`][].
///
/// [`printpdf::PdfDocumentReference`]: https://docs.rs/printpdf/0.3.2/printpdf/types/pdf_document/struct.PdfDocumentReference.html
pub struct Renderer {
    doc: printpdf::PdfDocumentReference,
    // invariant: pages.len() >= 1
    pages: Vec<Page>,
}

impl Renderer {
    /// Creates a new PDF document renderer with one page of the given size and the given title.
    pub fn new(size: impl Into<Size>, title: impl AsRef<str>) -> Result<Renderer, Error> {
        let size = size.into();
        let (doc, page_idx, layer_idx) = printpdf::PdfDocument::new(
            title.as_ref(),
            size.width.into(),
            size.height.into(),
            "Layer 1",
        );
        let page_ref = doc.get_page(page_idx);
        let layer_ref = page_ref.get_layer(layer_idx);
        let page = Page::new(page_ref, layer_ref, size);

        Ok(Renderer {
            doc,
            pages: vec![page],
        })
    }

    /// Sets the PDF conformance for the generated PDF document.
    pub fn with_conformance(mut self, conformance: printpdf::PdfConformance) -> Self {
        self.doc = self.doc.with_conformance(conformance);
        self
    }

    /// Adds a new page with the given size to the document.
    pub fn add_page(&mut self, size: impl Into<Size>) {
        let size = size.into();
        let (page_idx, layer_idx) =
            self.doc
                .add_page(size.width.into(), size.height.into(), "Layer 1");
        let page_ref = self.doc.get_page(page_idx);
        let layer_ref = page_ref.get_layer(layer_idx);
        self.pages.push(Page::new(page_ref, layer_ref, size))
    }

    /// Returns the number of pages in this document.
    pub fn page_count(&self) -> usize {
        self.pages.len()
    }

    /// Returns a page of this document.
    pub fn get_page(&self, idx: usize) -> Option<&Page> {
        self.pages.get(idx)
    }

    /// Returns a mutable reference to a page of this document.
    pub fn get_page_mut(&mut self, idx: usize) -> Option<&mut Page> {
        self.pages.get_mut(idx)
    }

    /// Returns a mutable reference to the first page of this document.
    pub fn first_page(&self) -> &Page {
        &self.pages[0]
    }

    /// Returns the first page of this document.
    pub fn first_page_mut(&mut self) -> &mut Page {
        &mut self.pages[0]
    }

    /// Returns the last page of this document.
    pub fn last_page(&self) -> &Page {
        &self.pages[self.pages.len() - 1]
    }

    /// Returns a mutable reference to the last page of this document.
    pub fn last_page_mut(&mut self) -> &mut Page {
        let idx = self.pages.len() - 1;
        &mut self.pages[idx]
    }

    /// Loads the font at the given path, adds it to the generated document and returns a reference
    /// to it.
    pub fn load_font(
        &self,
        path: impl AsRef<path::Path>,
    ) -> Result<printpdf::IndirectFontRef, Error> {
        let path = path.as_ref();
        let font_file = fs::File::open(path).map_err(|err| {
            Error::new(format!("Failed to open font file {}", path.display()), err)
        })?;
        self.doc.add_external_font(font_file).map_err(|err| {
            Error::new(
                format!("Failed to load PDF font from file {}", path.display()),
                err,
            )
        })
    }

    /// Writes this PDF document to a writer.
    pub fn write(self, w: impl io::Write) -> Result<(), Error> {
        self.doc
            .save(&mut io::BufWriter::new(w))
            .map_err(|err| Error::new("Failed to save document", err))
    }
}

/// A page of a PDF document.
///
/// This is a wrapper around a [`printpdf::PdfPageReference`][].
///
/// [`printpdf::PdfPageReference`]: https://docs.rs/printpdf/0.3.2/printpdf/types/pdf_page/struct.PdfPageReference.html
pub struct Page {
    page: printpdf::PdfPageReference,
    size: Size,
    // invariant: layers.len() >= 1
    layers: Vec<Layer>,
}

impl Page {
    fn new(
        page: printpdf::PdfPageReference,
        layer: printpdf::PdfLayerReference,
        size: Size,
    ) -> Page {
        Page {
            page,
            size,
            layers: vec![Layer::new(layer, size)],
        }
    }

    /// Adds a new layer with the given name to the page.
    pub fn add_layer(&mut self, name: impl Into<String>) {
        let layer = self.page.add_layer(name);
        self.layers.push(Layer::new(layer, self.size));
    }

    /// Returns the number of layers on this page.
    pub fn layer_count(&self) -> usize {
        self.layers.len()
    }

    /// Returns a layer of this page.
    pub fn get_layer(&self, idx: usize) -> Option<&Layer> {
        self.layers.get(idx)
    }

    /// Returns the first layer of this page.
    pub fn first_layer(&self) -> &Layer {
        &self.layers[0]
    }

    /// Returns the last layer of this page.
    pub fn last_layer(&self) -> &Layer {
        &self.layers[self.layers.len() - 1]
    }
}

/// A layer of a page of a PDF document.
///
/// This is a wrapper around a [`printpdf::PdfLayerReference`][].
///
/// [`printpdf::PdfLayerReference`]: https://docs.rs/printpdf/0.3.2/printpdf/types/pdf_layer/struct.PdfLayerReference.html
pub struct Layer {
    layer: printpdf::PdfLayerReference,
    size: Size,
}

impl Layer {
    fn new(layer: printpdf::PdfLayerReference, size: Size) -> Layer {
        Layer { layer, size }
    }

    /// Returns a drawable area for this layer.
    pub fn area(&self) -> Area<'_> {
        Area::new(self, Position::default(), self.size)
    }
}

/// A view on an area of a PDF layer that can be drawn on.
///
/// This page provides access to the drawing methods of a [`printpdf::PdfLayerReference`][].  It is
/// defined by the layer that is drawn on and the origin and the size of the area.
///
/// [`printpdf::PdfLayerReference`]: https://docs.rs/printpdf/0.3.2/printpdf/types/pdf_layer/struct.PdfLayerReference.html
#[derive(Clone)]
pub struct Area<'a> {
    layer: &'a Layer,
    origin: Position,
    size: Size,
}

impl<'a> Area<'a> {
    fn new(layer: &'a Layer, origin: Position, size: Size) -> Area<'a> {
        Area {
            layer,
            origin,
            size,
        }
    }

    /// Reduces the size of the drawable area by the given margins.
    pub fn add_margins(&mut self, margins: impl Into<Margins>) {
        let margins = margins.into();
        self.origin.x += margins.left;
        self.origin.y += margins.top;
        self.size.width -= margins.left + margins.right;
        self.size.height -= margins.top + margins.bottom;
    }

    /// Returns the size of this area.
    pub fn size(&self) -> Size {
        self.size
    }

    /// Adds the given offset to the area, reducing the drawable area.
    pub fn add_offset(&mut self, offset: impl Into<Position>) {
        let offset = offset.into();
        self.origin.x += offset.x;
        self.origin.y += offset.y;
        self.size.width -= offset.x;
        self.size.height -= offset.y;
    }

    /// Sets the size of this area.
    pub fn set_size(&mut self, size: impl Into<Size>) {
        self.size = size.into();
    }

    /// Sets the width of this area.
    pub fn set_width(&mut self, width: Mm) {
        self.size.width = width;
    }

    /// Draws a line with the given points and the given style.
    ///
    /// Currently, this method only uses the color of the given style as the outline color (if set).
    /// The points are relative to the upper left corner of the area.
    pub fn draw_line(&self, points: Vec<Position>, style: Style) {
        let line_points: Vec<_> = points
            .into_iter()
            .map(|pos| {
                (
                    printpdf::Point::new(
                        (self.origin.x + pos.x).into(),
                        (self.layer.size.height - self.origin.y - pos.y).into(),
                    ),
                    false,
                )
            })
            .collect();
        let line = printpdf::Line {
            points: line_points,
            is_closed: false,
            has_fill: false,
            has_stroke: true,
            is_clipping_path: false,
        };
        if let Some(color) = style.color() {
            self.layer.layer.set_outline_color(color.into());
        }
        self.layer.layer.add_shape(line);
        if style.color().is_some() {
            self.layer
                .layer
                .set_outline_color(Color::Rgb(0, 0, 0).into());
        }
    }

    /// Tries to draw the given string at the given position and returns `true` if the area was
    /// large enough to draw the string.
    ///
    /// The font cache must contain the PDF font for the font set in the style.  The position is
    /// relative to the upper left corner of the area.
    pub fn print_str<S: AsRef<str>>(
        &self,
        font_cache: &fonts::FontCache,
        position: Position,
        style: Style,
        s: S,
    ) -> bool {
        if let Ok(mut section) = self.text_section(font_cache, position, style) {
            section.print_str(s, style);
            true
        } else {
            false
        }
    }

    /// Creates a new text section at the given position or returns an error if the text section
    /// does not fit in this area.
    ///
    /// The given style is only used to calculate the line height of the section.  The position is
    /// relative to the upper left corner of the area.  The font cache must contain the PDF font
    /// for all fonts printed with the text section.
    pub fn text_section<'f>(
        &self,
        font_cache: &'f fonts::FontCache,
        position: Position,
        style: Style,
    ) -> Result<TextSection<'_, 'f, 'a>, ()> {
        TextSection::new(font_cache, self, position, style)
    }
}

/// A text section that is drawn on an area of a PDF layer.
pub struct TextSection<'a, 'f, 'l> {
    font_cache: &'f fonts::FontCache,
    area: &'a Area<'l>,
    line_height: Mm,
    cursor: Position,
    fill_color: Option<Color>,
}

impl<'a, 'f, 'l> TextSection<'a, 'f, 'l> {
    fn new(
        font_cache: &'f fonts::FontCache,
        area: &'a Area<'l>,
        position: Position,
        style: Style,
    ) -> Result<TextSection<'a, 'f, 'l>, ()> {
        let height = style.font(font_cache).glyph_height(style.font_size());

        if position.y + height > area.size.height {
            return Err(());
        }

        let line_height = style.line_height(font_cache);
        let section = TextSection {
            font_cache,
            area,
            line_height,
            cursor: position,
            fill_color: None,
        };
        section.layer().begin_text_section();
        section.layer().set_line_height(line_height.0 as i64);
        section.layer().set_text_cursor(
            (section.area.origin.x + position.x).into(),
            (section.area.layer.size.height - section.area.origin.y - position.y - height).into(),
        );
        Ok(section)
    }

    /// Tries to add a new line and returns `true` if the area was large enough to fit the new
    /// line.
    #[must_use]
    pub fn add_newline(&mut self) -> bool {
        if self.cursor.y + self.line_height > self.area.size.height {
            false
        } else {
            self.layer().add_line_break();
            self.cursor.y += self.line_height;
            true
        }
    }

    /// Prints the given string with the given style.
    ///
    /// The font cache for this text section must contain the PDF font for the given style.
    pub fn print_str(&mut self, s: impl AsRef<str>, style: Style) {
        let font = self
            .font_cache
            .get_pdf_font(style.font(self.font_cache))
            .expect("Could not find PDF font in font cache");
        if let Some(color) = style.color() {
            self.layer().set_fill_color(color.into());
        } else if self.fill_color.is_some() {
            self.layer().set_fill_color(Color::Rgb(0, 0, 0).into());
        }
        self.fill_color = style.color();
        self.layer().set_font(font, style.font_size().into());
        self.layer().write_text(s.as_ref(), font);
    }

    fn layer(&self) -> &printpdf::PdfLayerReference {
        &self.area.layer.layer
    }
}

impl<'a, 'f, 'l> Drop for TextSection<'a, 'f, 'l> {
    fn drop(&mut self) {
        if self.fill_color.is_some() {
            self.layer().set_fill_color(Color::Rgb(0, 0, 0).into());
        }
        self.layer().end_text_section();
    }
}