Skip to main content

pltrs_render/pdf/
mod.rs

1//! The PDF backend: matplotlib's `RendererPdf` and `PdfFile`.
2//!
3//! Every page is a content stream whose graphics state is tracked so that
4//! only changes are emitted; the pages share one resource dictionary:
5//! text in Type 3 fonts built from the glyph outlines, alpha through
6//! extended graphics states, hatches as tiling patterns, markers and large
7//! path collections as form `XObject`s, images as (indexed when possible)
8//! PNG-predicted image `XObject`s with soft masks, and Gouraud triangles as
9//! free-form shadings. A document may hold several pages (matplotlib's
10//! `PdfPages`), with text notes attached to them.
11//!
12//! TrueType fonts are embedded as Type 3 fonts or, with `pdf.fonttype =
13//! 42`, as `CIDFontType2` subsets of the font program; the fonts of usetex
14//! text as subsets of their Type 1 programs (see `tex`). With
15//! `pdf.use14corefonts`, text that is not mathtext is shown in one of the
16//! 14 PDF core fonts instead, referenced by name and never embedded (see
17//! `core_fonts`).
18//!
19//! Not supported: link annotations for URLs.
20
21mod core_fonts;
22mod draw;
23mod file;
24mod fonts;
25mod image;
26mod object;
27mod pages;
28mod resources;
29mod state;
30mod tex;
31mod text;
32mod type42;
33mod writer;
34
35use pltrs_core::path::convert::{SimplifySettings, SketchParams, StringCodes, StringOptions};
36use pltrs_core::{Affine2D, Bbox, Path, Point, Rgba};
37use pltrs_text::tex::{TexError, TexText};
38use pltrs_text::{AfmDirectory, TextRun};
39
40pub use self::file::{PdfFont, PdfHatch};
41pub use self::object::{Obj as PdfObject, line as pdf_line, text_string as pdf_text_string};
42pub use self::resources::{
43    MarkerPaint as PdfMarkerPaint, ShadingColors as PdfShadingColors,
44    TemplatePaint as PdfTemplatePaint,
45};
46
47use self::fonts::FontNames;
48use self::object::{Obj, text_string};
49use self::pages::{Note, PageParents, Pages, media_box};
50use self::resources::{ResourceIds, Resources};
51use self::state::{PdfState, StateStack};
52use self::tex::DviFonts;
53use self::writer::PdfWriter;
54use crate::collection::PathCollection;
55use crate::gc::GraphicsContext;
56use crate::image::RgbaImage;
57use crate::renderer::Renderer;
58use crate::vector::{
59    CharacterTracker, FontCache, FontType, Metadata, Problems, VectorError, check_canvas,
60};
61
62/// Settings of a PDF document (matplotlib's `pdf.*` rcParams and the
63/// `metadata` argument of `savefig`).
64#[derive(Clone, Debug, PartialEq)]
65pub struct PdfOptions {
66    /// `pdf.compression`: zlib level of the streams, 0 to store them.
67    pub compression: u8,
68    /// `pdf.inheritcolor`: leave stroke and fill colours unset.
69    pub inherit_color: bool,
70    /// Title, creator, producer and creation date.
71    pub metadata: Metadata,
72    /// `path.simplify` and `path.simplify_threshold`.
73    pub simplify: SimplifySettings,
74    /// `image.composite_image`.
75    pub composite_images: bool,
76    /// `pdf.fonttype`: how TrueType fonts are embedded.
77    pub fonttype: FontType,
78    /// The font type whose subset size groups the character codes of the
79    /// embedded fonts: `ps.fonttype`, which matplotlib's PDF writer reads
80    /// for it (`PdfFile._character_tracker`), whatever `pdf.fonttype`
81    /// says.
82    pub subset_fonttype: FontType,
83    /// `pdf.use14corefonts`: text that is not mathtext is drawn in the 14
84    /// PDF core fonts, measured with their metrics.
85    pub core_fonts: bool,
86}
87
88impl Default for PdfOptions {
89    fn default() -> Self {
90        Self {
91            compression: 6,
92            inherit_color: false,
93            metadata: Metadata::default(),
94            simplify: SimplifySettings::default(),
95            composite_images: true,
96            fonttype: FontType::Type3,
97            subset_fonttype: FontType::Type3,
98            core_fonts: false,
99        }
100    }
101}
102
103impl PdfOptions {
104    /// The AFM fonts text that is not mathtext is drawn in, and must be
105    /// measured with, if any (`RendererPdf._afm_font_dir` when
106    /// `pdf.use14corefonts` is set).
107    pub fn afm_directory(&self) -> Option<AfmDirectory> {
108        self.core_fonts.then_some(AfmDirectory::PdfCore)
109    }
110}
111
112/// Object numbers fixed when the file is started.
113#[derive(Clone, Copy, Debug)]
114struct Ids {
115    root: u32,
116    pages: u32,
117    resources: ResourceIds,
118    resource_dictionary: u32,
119}
120
121/// `pathOperations`: path data in PDF operators (quadratic curves as
122/// cubics) with optional canvas clipping, simplification and sketching.
123fn path_ops(
124    path: &Path,
125    transform: Affine2D,
126    clip: Option<Bbox>,
127    simplify: Option<f64>,
128    sketch: Option<SketchParams>,
129) -> Vec<u8> {
130    path.convert_to_string(&StringOptions {
131        transform,
132        clip,
133        simplify,
134        sketch,
135        precision: 6,
136        codes: StringCodes::PDF,
137        postfix: true,
138    })
139    .into_bytes()
140}
141
142/// Renders into a PDF document exactly like matplotlib's `RendererPdf`
143/// and `PdfFile`. Coordinates are points with the origin at the bottom
144/// left of the current page.
145#[derive(Debug)]
146pub struct PdfRenderer {
147    writer: PdfWriter,
148    /// Size of the current page in inches.
149    width: f64,
150    height: f64,
151    image_dpi: f64,
152    ids: Ids,
153    pages: Pages,
154    /// Whether the content stream of a page is open.
155    page_open: bool,
156    resources: Resources,
157    states: StateStack,
158    font_names: FontNames,
159    /// The TeX fonts of usetex text.
160    dvi_fonts: DviFonts,
161    tracker: CharacterTracker,
162    fonts: FontCache,
163    options: PdfOptions,
164    /// Identifies the artist drawing: matplotlib compares clip regions by
165    /// object identity and every artist has its own, so a clip set by
166    /// another artist must be set again. Drawing calls inside a group (one
167    /// artist) share a generation; calls outside any group each start one.
168    generation: u64,
169    group_depth: usize,
170    problems: Problems,
171    /// The document information dictionary, once written.
172    info: Option<u32>,
173}
174
175impl PdfRenderer {
176    /// A document with one page of `width × height` inches whose images
177    /// are rasterized at `image_dpi` (matplotlib's `PdfFile` plus
178    /// `newPage`).
179    ///
180    /// # Errors
181    ///
182    /// When the page size or resolution is not positive and finite.
183    pub fn new(
184        width: f64,
185        height: f64,
186        image_dpi: f64,
187        options: PdfOptions,
188    ) -> Result<Self, VectorError> {
189        check_canvas(width, height, image_dpi)?;
190        let mut document = Self::document(options)?;
191        document.new_page(width, height, image_dpi)?;
192        Ok(document)
193    }
194
195    /// A document without pages yet (matplotlib's `PdfFile`); drawing
196    /// needs a page started with [`new_page`](Self::new_page).
197    ///
198    /// # Errors
199    ///
200    /// Never in practice: the document's first objects are always
201    /// writable.
202    pub fn document(options: PdfOptions) -> Result<Self, VectorError> {
203        let mut writer = PdfWriter::new(options.compression);
204        let root = writer.reserve();
205        let pages = writer.reserve();
206        let resource_ids = ResourceIds {
207            fonts: writer.reserve(),
208            ext_gstates: writer.reserve(),
209            patterns: writer.reserve(),
210            shadings: writer.reserve(),
211            xobjects: writer.reserve(),
212        };
213        let resource_dictionary = writer.reserve();
214        writer.write_object(
215            root,
216            &Obj::dict([("Type", Obj::name("Catalog")), ("Pages", Obj::Ref(pages))]),
217        )?;
218        let procsets = ["PDF", "Text", "ImageB", "ImageC", "ImageI"].map(Obj::name);
219        writer.write_object(
220            resource_dictionary,
221            &Obj::dict([
222                ("Font", Obj::Ref(resource_ids.fonts)),
223                ("XObject", Obj::Ref(resource_ids.xobjects)),
224                ("ExtGState", Obj::Ref(resource_ids.ext_gstates)),
225                ("Pattern", Obj::Ref(resource_ids.patterns)),
226                ("Shading", Obj::Ref(resource_ids.shadings)),
227                ("ProcSet", Obj::Array(procsets.to_vec())),
228            ]),
229        )?;
230        let states = StateStack::new(options.inherit_color);
231        Ok(Self {
232            writer,
233            width: 0.0,
234            height: 0.0,
235            image_dpi: 72.0,
236            ids: Ids {
237                root,
238                pages,
239                resources: resource_ids,
240                resource_dictionary,
241            },
242            pages: Pages::default(),
243            page_open: false,
244            resources: Resources::default(),
245            states,
246            font_names: FontNames::default(),
247            dvi_fonts: DviFonts::default(),
248            tracker: CharacterTracker::new(options.subset_fonttype.subset_size()),
249            fonts: FontCache::default(),
250            options,
251            generation: 0,
252            group_depth: 0,
253            problems: Problems::default(),
254            info: None,
255        })
256    }
257
258    /// Ends the current page, if any, and starts a page of `width ×
259    /// height` inches whose images are rasterized at `image_dpi`, drawn
260    /// with a fresh graphics state (matplotlib's `newPage` and a new
261    /// `RendererPdf`). Notes attached since the last page go on it. Any
262    /// finite size makes a page, as matplotlib's `newPage` writes the
263    /// media box it is given (an empty one for a size of zero).
264    ///
265    /// # Errors
266    ///
267    /// When the resolution is not positive and finite, the size is not
268    /// finite, or the previous page could not be written.
269    pub fn new_page(&mut self, width: f64, height: f64, image_dpi: f64) -> Result<(), VectorError> {
270        self.new_page_spanning(width, height, image_dpi, media_box(width, height))
271    }
272
273    /// [`new_page`](Self::new_page) for a page whose media box is written
274    /// as `media_box`: whatever matplotlib's `newPage` writes for the size
275    /// it is given (`[0, 0, 72 * width, 72 * height]` in Python's
276    /// arithmetic), the page drawn as `width × height` inches.
277    ///
278    /// # Errors
279    ///
280    /// As [`new_page`](Self::new_page), and when `media_box` holds a
281    /// non-finite number.
282    pub fn new_page_spanning(
283        &mut self,
284        width: f64,
285        height: f64,
286        image_dpi: f64,
287        media_box: Obj,
288    ) -> Result<(), VectorError> {
289        if !(image_dpi.is_finite() && image_dpi > 0.0) {
290            return Err(VectorError::InvalidCanvas {
291                width,
292                height,
293                dpi: image_dpi,
294            });
295        }
296        self.end_page()?;
297        let parents = PageParents {
298            pages: self.ids.pages,
299            resources: self.ids.resource_dictionary,
300        };
301        let contents = self.pages.start(&mut self.writer, parents, media_box)?;
302        let length = self.writer.reserve();
303        self.writer
304            .begin_stream(contents, Some(length), Vec::new(), None);
305        self.writer
306            .output(&[Obj::name("DeviceRGB"), Obj::op("CS")])?;
307        self.writer
308            .output(&[Obj::name("DeviceRGB"), Obj::op("cs")])?;
309        self.writer.output(&[Obj::Int(1), Obj::op("j")])?;
310        self.states = StateStack::new(self.options.inherit_color);
311        (self.width, self.height, self.image_dpi) = (width, height, image_dpi);
312        self.page_open = true;
313        Ok(())
314    }
315
316    /// Attaches a text note shown at `rect` (`[x0, y0, x1, y1]` in points)
317    /// to the next page started (matplotlib's `newTextnote`).
318    pub fn attach_note(&mut self, text: &str, rect: [f64; 4]) {
319        self.attach_note_objects(text_string(text), Obj::reals(rect));
320    }
321
322    /// [`attach_note`](Self::attach_note) of a note whose text and
323    /// rectangle are written as `contents` and `rect`: whatever matplotlib's
324    /// `newTextnote` is given, kept as it is until the annotations are
325    /// written.
326    pub fn attach_note_objects(&mut self, contents: Obj, rect: Obj) {
327        self.pages.add_note(Note { contents, rect });
328    }
329
330    /// How many pages the document has.
331    pub fn page_count(&self) -> usize {
332        self.pages.len()
333    }
334
335    /// The names of the images the document holds so far (`I1`, `I2`,
336    /// ...), one per image `XObject` written (matplotlib's
337    /// `PdfFile._images`).
338    pub fn image_names(&self) -> Vec<String> {
339        self.resources.image_names().map(str::to_owned).collect()
340    }
341
342    /// The document information written when the document is finished
343    /// (matplotlib's `PdfPages.infodict`).
344    pub fn metadata_mut(&mut self) -> &mut Metadata {
345        &mut self.options.metadata
346    }
347
348    /// The AFM fonts the document draws text that is not mathtext in, if
349    /// any (see [`PdfOptions::afm_directory`]).
350    pub fn afm_directory(&self) -> Option<AfmDirectory> {
351        self.options.afm_directory()
352    }
353
354    /// Restores the graphics state and closes the content stream of the
355    /// current page (`RendererPdf.finalize` and `endStream`).
356    fn end_page(&mut self) -> Result<(), VectorError> {
357        if !self.page_open {
358            return Ok(());
359        }
360        self.restore_gc()?;
361        self.writer.end_stream()?;
362        self.page_open = false;
363        Ok(())
364    }
365
366    /// Closes the page and writes the annotations, fonts, resources, the
367    /// page tree, the document information and the cross-reference table
368    /// (matplotlib's `finalize` and `close`).
369    ///
370    /// # Errors
371    ///
372    /// When a font, image or number met while drawing could not be
373    /// written.
374    pub fn finish(mut self) -> Result<Vec<u8>, VectorError> {
375        self.finalize()?;
376        self.close()
377    }
378
379    /// Restores every graphics state the page saved (matplotlib's
380    /// `RendererPdf.finalize`).
381    ///
382    /// # Errors
383    ///
384    /// When the content stream cannot be written.
385    pub fn restore_gc(&mut self) -> Result<(), VectorError> {
386        let restore = self.states.finish();
387        self.writer.output(&restore)
388    }
389
390    /// Writes `objects` as one content-stream line.
391    fn output(&mut self, objects: &[Obj]) {
392        let result = self.writer.output(objects);
393        self.problems.record(result);
394    }
395
396    /// Writes what changes the graphics state of the page into the one
397    /// `gc` and the fill `fill` need, the state kept by the document
398    /// (matplotlib's `RendererPdf.check_gc`).
399    pub fn check_gc(&mut self, gc: &GraphicsContext, fill: Option<Rgba>) {
400        let target = PdfState::from_gc(gc, fill, self.generation);
401        let cmds = self.states.delta(&target, &mut self.resources);
402        if !cmds.is_empty() {
403            self.output(&cmds);
404        }
405    }
406
407    /// Marks the start of a drawing call (see `generation`).
408    fn begin_draw(&mut self) {
409        if self.group_depth == 0 {
410            self.generation += 1;
411        }
412    }
413
414    /// The page in points.
415    fn canvas(&self) -> Bbox {
416        Bbox::from_extents(0.0, 0.0, self.width * 72.0, self.height * 72.0)
417    }
418}
419
420impl Renderer for PdfRenderer {
421    fn canvas_size(&self) -> (f64, f64) {
422        (self.width * 72.0, self.height * 72.0)
423    }
424
425    /// The image resolution, as matplotlib's `MixedModeRenderer.dpi`.
426    fn dpi(&self) -> f64 {
427        self.image_dpi
428    }
429
430    /// Lengths are points already.
431    fn points_to_pixels(&self, points: f64) -> f64 {
432        points
433    }
434
435    fn draw_path(
436        &mut self,
437        gc: &GraphicsContext,
438        path: &Path,
439        transform: &Affine2D,
440        fill: Option<Rgba>,
441    ) {
442        self.begin_draw();
443        self.pdf_path(gc, path, *transform, fill);
444    }
445
446    fn draw_markers(
447        &mut self,
448        gc: &GraphicsContext,
449        marker: &Path,
450        marker_transform: &Affine2D,
451        path: &Path,
452        transform: &Affine2D,
453        fill: Option<Rgba>,
454    ) {
455        self.begin_draw();
456        self.pdf_markers(gc, marker, *marker_transform, path, *transform, fill);
457    }
458
459    fn draw_path_collection(&mut self, gc: &GraphicsContext, collection: &PathCollection<'_>) {
460        self.begin_draw();
461        self.pdf_path_collection(gc, collection);
462    }
463
464    fn draw_gouraud_triangles(
465        &mut self,
466        gc: &GraphicsContext,
467        triangles: &[[Point; 3]],
468        colors: &[[Rgba; 3]],
469        transform: &Affine2D,
470    ) {
471        self.begin_draw();
472        self.pdf_gouraud_triangles(gc, triangles, colors, *transform);
473    }
474
475    fn draw_image(
476        &mut self,
477        gc: &GraphicsContext,
478        origin: Point,
479        image: &RgbaImage,
480        transform: Option<&Affine2D>,
481    ) {
482        self.begin_draw();
483        self.pdf_image(gc, origin, image, transform.copied());
484    }
485
486    fn draw_text(&mut self, gc: &GraphicsContext, run: &TextRun, origin: Point, angle: f64) {
487        self.begin_draw();
488        self.pdf_text(gc, run, origin, angle);
489    }
490
491    fn draw_tex(
492        &mut self,
493        gc: &GraphicsContext,
494        _run: &TextRun,
495        tex: &TexText,
496        origin: Point,
497        angle: f64,
498    ) -> Result<(), TexError> {
499        self.begin_draw();
500        self.pdf_tex(gc, tex, origin, angle)
501    }
502
503    fn open_group(&mut self, _name: &str, _gid: Option<&str>) {
504        self.group_depth += 1;
505        self.generation += 1;
506    }
507
508    fn close_group(&mut self, _name: &str) {
509        self.group_depth = self.group_depth.saturating_sub(1);
510        self.generation += 1;
511    }
512
513    /// The parts of an artist draw in its generation.
514    fn open_part_group(&mut self, _name: &str, _gid: Option<&str>) {
515        self.group_depth += 1;
516    }
517
518    fn close_part_group(&mut self, _name: &str) {
519        self.group_depth = self.group_depth.saturating_sub(1);
520    }
521
522    fn option_image_nocomposite(&self) -> bool {
523        !self.options.composite_images
524    }
525
526    fn option_scale_image(&self) -> bool {
527        true
528    }
529
530    fn image_magnification(&self) -> f64 {
531        self.image_dpi / 72.0
532    }
533}
534
535#[cfg(test)]
536mod tests;