Skip to main content

pltrs_render/pdf/
file.rs

1//! The object-level interface of a PDF document (matplotlib's `PdfFile`):
2//! objects reserved, written and referenced, streams, the named resources
3//! pages draw with (alpha states, hatches, shadings, images, marker and
4//! path forms, fonts), and the end matter (fonts, resources, page tree,
5//! document information, cross-reference table, trailer), each part
6//! written when the program asks, as matplotlib's `PdfFile` methods write
7//! them.
8
9use std::path::{Path as FsPath, PathBuf};
10use std::sync::Arc;
11
12use pltrs_core::{Affine2D, Path, Point, Rgba};
13use pltrs_font::{GlyphId, Type1Font};
14use pltrs_text::tex::{DviFont, TexFiles};
15use pltrs_text::{AfmDirectory, AfmFont, FontId, FontSource, TextEngine};
16
17use super::fonts::{self, FontKey, SubsetFont};
18use super::object::Obj;
19use super::resources::{HatchStyle, MarkerPaint, ShadingColors, TemplatePaint};
20use super::{PdfRenderer, pages, tex};
21use crate::image::RgbaImage;
22use crate::vector::{Subset, VectorError};
23
24/// A font a document names (a key of matplotlib's `PdfFile.fontNames`).
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum PdfFont {
27    /// One subset of a face of a TrueType file.
28    TrueType {
29        /// The font file: its path, or the bare file name of a bundled
30        /// font.
31        file: PathBuf,
32        /// The face in the file.
33        index: u32,
34        /// The subset of its glyphs.
35        subset: usize,
36    },
37    /// One of the 14 PDF core fonts, by the file name of its metrics.
38    Core(&'static str),
39}
40
41/// A hatch pattern a document holds (matplotlib's `hatchPatterns`): the
42/// edge and face colours and the hatch string.
43pub type PdfHatch = (Option<Rgba>, Option<Rgba>, String);
44
45impl PdfRenderer {
46    /// Reserves an object number (`reserveObject`).
47    pub fn reserve_object(&mut self) -> u32 {
48        self.writer.reserve()
49    }
50
51    /// Records that object `id` starts at the current end of the file
52    /// (`recordXref`), for objects the program writes itself with
53    /// [`write`](Self::write).
54    pub fn record_xref(&mut self, id: u32) {
55        self.writer.record(id);
56    }
57
58    /// Writes object `id` with `contents` (`writeObject`).
59    ///
60    /// # Errors
61    ///
62    /// When `contents` holds a non-finite number.
63    pub fn write_object(&mut self, id: u32, contents: &Obj) -> Result<(), VectorError> {
64        self.writer.write_object(id, contents)
65    }
66
67    /// Appends `data` to the open stream, or to the file when none is open
68    /// (`write`).
69    pub fn write(&mut self, data: &[u8]) {
70        self.writer.write(data);
71    }
72
73    /// Writes `objects` as one line of the open stream or of the file
74    /// (`output`).
75    ///
76    /// # Errors
77    ///
78    /// When an object holds a non-finite number.
79    pub fn output_objects(&mut self, objects: &[Obj]) -> Result<(), VectorError> {
80        self.writer.output(objects)
81    }
82
83    /// The object of the open stream, if any (`currentstream`): the
84    /// content stream of the page being drawn, or a stream begun with
85    /// [`begin_stream`](Self::begin_stream).
86    pub fn open_stream(&self) -> Option<u32> {
87        self.writer.open_stream()
88    }
89
90    /// Opens the stream object `id` whose length goes to object `length`
91    /// (inline for `None`), with the `extra` entries in its dictionary and,
92    /// for data PNG-predicted already, the decode parameters `png`
93    /// (`beginStream`).
94    ///
95    /// # Errors
96    ///
97    /// When a stream is open already.
98    pub fn begin_stream(
99        &mut self,
100        id: u32,
101        length: Option<u32>,
102        extra: Vec<(String, Obj)>,
103        png: Option<Obj>,
104    ) -> Result<(), VectorError> {
105        if self.writer.open_stream().is_some() {
106            return Err(VectorError::StreamOpen);
107        }
108        self.writer.begin_stream(id, length, extra, png);
109        Ok(())
110    }
111
112    /// Closes the open stream, compressed at `pdf.compression`, if any
113    /// (`endStream`); the content stream of a page after restoring the
114    /// graphics state its drawing saved.
115    ///
116    /// # Errors
117    ///
118    /// When its dictionary holds a non-finite number.
119    pub fn end_stream(&mut self) -> Result<(), VectorError> {
120        if self.page_open {
121            self.end_page()
122        } else {
123            self.writer.end_stream()
124        }
125    }
126
127    /// Writes the stream object `id` holding `data` (`outputStream`).
128    ///
129    /// # Errors
130    ///
131    /// When a stream is open already, or `extra` holds a non-finite number.
132    pub fn output_stream(
133        &mut self,
134        id: u32,
135        data: &[u8],
136        extra: Vec<(String, Obj)>,
137    ) -> Result<(), VectorError> {
138        self.writer.output_stream(id, data, extra)
139    }
140
141    /// Writes the stream object `id` holding `data` whole, with the `extra`
142    /// entries and, for data PNG-predicted already, the decode parameters
143    /// `png`, whether or not a stream is open: matplotlib's `Stream` of an
144    /// inline length keeps its data until it ends, then writes itself to
145    /// the end of the file.
146    ///
147    /// # Errors
148    ///
149    /// When `extra` holds a non-finite number.
150    pub fn write_stream(
151        &mut self,
152        id: u32,
153        extra: Vec<(String, Obj)>,
154        png: Option<Obj>,
155        data: Vec<u8>,
156    ) -> Result<(), VectorError> {
157        self.writer.write_stream(id, extra, png, data)
158    }
159
160    /// How many objects the file numbers so far, the zero object included
161    /// (the length of matplotlib's ``xrefTable``).
162    pub fn object_count(&self) -> usize {
163        self.writer.object_count()
164    }
165
166    /// The name of the graphics state setting the stroke and fill alpha
167    /// `alphas` (`alphaState`), made on first use.
168    pub fn alpha_state(&mut self, alphas: (f64, f64)) -> String {
169        self.resources.alpha_state(alphas)
170    }
171
172    /// A new graphics state setting the alphas `alphas`, though another
173    /// may set the same: `alphaState` for a value the program has not
174    /// given before (matplotlib keys its states by the program's values,
175    /// which may be of other types but of equal numbers).
176    pub fn new_alpha_state(&mut self, alphas: (f64, f64)) -> String {
177        self.resources.new_alpha_state(alphas)
178    }
179
180    /// The name of the tiling pattern drawing `pattern` (matplotlib's
181    /// hatch string) in `edge`, over `face`, with lines `linewidth` wide
182    /// (`hatchPattern`), made on first use.
183    pub fn hatch_pattern(
184        &mut self,
185        edge: Option<Rgba>,
186        face: Option<Rgba>,
187        pattern: &str,
188        linewidth: f64,
189    ) -> String {
190        self.resources
191            .hatch_pattern(hatch_style(edge, face, pattern, linewidth))
192    }
193
194    /// A new tiling pattern, though another may draw the same:
195    /// `hatchPattern` for a style the program has not given before (see
196    /// [`new_alpha_state`](Self::new_alpha_state)).
197    pub fn new_hatch_pattern(
198        &mut self,
199        edge: Option<Rgba>,
200        face: Option<Rgba>,
201        pattern: &str,
202        linewidth: f64,
203    ) -> String {
204        self.resources
205            .new_hatch_pattern(hatch_style(edge, face, pattern, linewidth))
206    }
207
208    /// The hatch patterns made so far with their names, in order.
209    pub fn hatch_patterns(&self) -> Vec<(PdfHatch, String)> {
210        self.resources
211            .hatch_styles()
212            .map(|(style, name)| {
213                let hatch = (style.edge, style.face, style.pattern.clone());
214                (hatch, name.to_owned())
215            })
216            .collect()
217    }
218
219    /// The name and object of a new shading of the triangles `points`
220    /// (display coordinates) in the vertex colours `colors`
221    /// (`addGouraudTriangles`).
222    pub fn add_gouraud_triangles(
223        &mut self,
224        points: Vec<[Point; 3]>,
225        colors: ShadingColors,
226    ) -> (String, u32) {
227        self.resources.gouraud(&mut self.writer, points, colors)
228    }
229
230    /// The name of a new image `XObject` showing `image` (`imageObject`).
231    pub fn image_object(&mut self, image: &RgbaImage) -> String {
232        self.resources.image(&mut self.writer, image)
233    }
234
235    /// The name of a new form `XObject` drawing the marker `path` under
236    /// `transform` as `paint` says (`markerObject`).
237    pub fn marker_object(
238        &mut self,
239        path: &Path,
240        transform: Affine2D,
241        paint: MarkerPaint,
242    ) -> String {
243        self.resources
244            .marker(&mut self.writer, path, transform, paint)
245    }
246
247    /// The name of a new form `XObject` drawing `path` of a collection
248    /// under `transform` as `paint` says (`pathCollectionObject`).
249    pub fn path_collection_object(
250        &mut self,
251        path: &Path,
252        transform: Affine2D,
253        paint: TemplatePaint,
254    ) -> String {
255        self.resources
256            .path_template(&mut self.writer, path, transform, paint)
257    }
258
259    /// Writes the dictionary of the graphics states (`writeExtGSTates`)
260    /// and the transparency groups of the soft masks.
261    ///
262    /// # Errors
263    ///
264    /// When an alpha is not finite.
265    pub fn write_ext_gstates(&mut self) -> Result<(), VectorError> {
266        self.resources
267            .write_ext_gstates(&mut self.writer, self.ids.resources.ext_gstates)?;
268        self.resources.write_soft_mask_groups(&mut self.writer)
269    }
270
271    /// Writes the tiling patterns and their dictionary (`writeHatches`).
272    ///
273    /// # Errors
274    ///
275    /// When a hatch colour or width is not finite.
276    pub fn write_hatches(&mut self) -> Result<(), VectorError> {
277        self.resources
278            .write_hatches(&mut self.writer, self.ids.resources.patterns, self.height)
279    }
280
281    /// Writes the shadings and their dictionary
282    /// (`writeGouraudTriangles`).
283    ///
284    /// # Errors
285    ///
286    /// When a vertex is not finite.
287    pub fn write_gouraud_triangles(&mut self) -> Result<(), VectorError> {
288        self.resources
289            .write_shadings(&mut self.writer, self.ids.resources.shadings)
290    }
291
292    /// Writes the image `XObject`s (`writeImages`).
293    ///
294    /// # Errors
295    ///
296    /// When an image cannot be encoded.
297    pub fn write_images(&mut self) -> Result<(), VectorError> {
298        let compressed = self.options.compression > 0;
299        self.resources.write_images(&mut self.writer, compressed)
300    }
301
302    /// Writes the marker forms (`writeMarkers`).
303    ///
304    /// # Errors
305    ///
306    /// When a marker is not finite.
307    pub fn write_markers(&mut self) -> Result<(), VectorError> {
308        self.resources.write_markers(&mut self.writer)
309    }
310
311    /// Writes the path-collection templates
312    /// (`writePathCollectionTemplates`).
313    ///
314    /// # Errors
315    ///
316    /// When a path is not finite.
317    pub fn write_path_collection_templates(&mut self) -> Result<(), VectorError> {
318        self.resources.write_path_templates(&mut self.writer)
319    }
320
321    /// The name of subset `subset` of face `index` of the TrueType file
322    /// `path` (`fontName`), assigned on first use.
323    ///
324    /// # Errors
325    ///
326    /// When the file cannot be read or has no face `index`.
327    pub fn font_name(
328        &mut self,
329        path: &FsPath,
330        index: u32,
331        subset: usize,
332    ) -> Result<String, VectorError> {
333        let font = face_of_file(path, index)?;
334        Ok(self.font_names.name(font, subset))
335    }
336
337    /// The name of the PDF core font whose metrics file is `file`
338    /// (`fontName` under `pdf.use14corefonts`), assigned on first use.
339    ///
340    /// # Errors
341    ///
342    /// When `file` is not the metrics of a core font.
343    pub fn core_font_name(&mut self, file: &str) -> Result<String, VectorError> {
344        let font = AfmFont::all()
345            .iter()
346            .find(|font| font.directory == AfmDirectory::PdfCore && font.file == file)
347            .ok_or(VectorError::Unsupported(
348                "a PDF core font is named by its bundled metrics",
349            ))?;
350        Ok(self.font_names.core_name(font))
351    }
352
353    /// A name for a font the program names that pltrs cannot embed (a
354    /// file it cannot read, a subset that is no count): matplotlib's
355    /// `fontName` names any file, failing only when it writes the fonts.
356    /// The name takes its place among the others and is written as no
357    /// font.
358    pub fn reserve_font_name(&mut self) -> String {
359        self.font_names.reserve()
360    }
361
362    /// The fonts named so far with their names, in first-use order
363    /// (matplotlib's `fontNames`), but those of
364    /// [`reserve_font_name`](Self::reserve_font_name).
365    pub fn font_names(&self) -> Vec<(PdfFont, String)> {
366        let db = TextEngine::global().database();
367        self.font_names
368            .entries()
369            .filter_map(|(key, name)| {
370                let font = match key {
371                    FontKey::Embedded(id, subset) => PdfFont::TrueType {
372                        file: match db.source(id) {
373                            Some(FontSource::File(path)) => path.clone(),
374                            Some(FontSource::Bundled(name)) => PathBuf::from(name),
375                            None => PathBuf::new(),
376                        },
377                        index: db.face_index(id).unwrap_or_default(),
378                        subset,
379                    },
380                    FontKey::Core(font) => PdfFont::Core(font.file),
381                    FontKey::Reserved(_) => return None,
382                };
383                Some((font, name.to_owned()))
384            })
385            .collect()
386    }
387
388    /// The name of the TeX font `font` (`F-<texname>`, `dviFontName`),
389    /// whose files `files` finds, registered to be embedded with the
390    /// glyphs drawn in it.
391    pub fn dvi_font_name(&mut self, font: Arc<DviFont>, files: &'static TexFiles) -> String {
392        self.dvi_fonts.register(font, files)
393    }
394
395    /// Whether glyphs of the TeX font registered under `name`
396    /// ([`dvi_font_name`](Self::dvi_font_name)) were drawn in the document,
397    /// which `writeFonts` needs to embed it.
398    pub fn dvi_font_used(&self, name: &str) -> bool {
399        self.dvi_fonts.is_used(name)
400    }
401
402    /// Writes the font dictionaries of every font named and their
403    /// resource dictionary (`writeFonts`).
404    ///
405    /// # Errors
406    ///
407    /// When a font cannot be read or embedded.
408    pub fn write_fonts(&mut self) -> Result<(), VectorError> {
409        let tex_fonts = self.dvi_fonts.embed(&mut self.writer)?;
410        fonts::write_fonts(
411            &mut self.writer,
412            tex_fonts,
413            &mut self.fonts,
414            &self.font_names,
415            &self.tracker,
416            self.ids.resources.fonts,
417            self.options.fonttype,
418        )
419    }
420
421    /// Whether glyphs of face `index` of the font file `path` were drawn
422    /// in the document (matplotlib's character tracker holds the font,
423    /// which `writeFonts` and `embedTTF` read).
424    ///
425    /// # Errors
426    ///
427    /// When the file cannot be read or has no face `index`.
428    pub fn tracks_font(&self, path: &FsPath, index: u32) -> Result<bool, VectorError> {
429        let id = face_of_file(path, index)?;
430        Ok(self.tracker.subset(id, 0).is_some())
431    }
432
433    /// Embeds the glyphs `charmap` (character codes and the glyphs they
434    /// show) of face `index` of the TrueType file `path` as subset
435    /// `subset_index`, in the format of `pdf.fonttype` (`embedTTF`);
436    /// returns the font dictionary.
437    ///
438    /// # Errors
439    ///
440    /// When `charmap` is empty or the font cannot be read.
441    pub fn embed_ttf(
442        &mut self,
443        path: &FsPath,
444        index: u32,
445        subset_index: usize,
446        charmap: Vec<(u32, GlyphId)>,
447    ) -> Result<u32, VectorError> {
448        if charmap.is_empty() {
449            return Err(VectorError::Unsupported(
450                "a font is embedded with at least one glyph",
451            ));
452        }
453        let id = face_of_file(path, index)?;
454        let subset = Subset::from_entries(charmap);
455        let subset_font = SubsetFont {
456            font: self.fonts.get(id)?,
457            id,
458            index: subset_index,
459            subset: &subset,
460        };
461        fonts::embed_subset(
462            &mut self.writer,
463            subset_font,
464            &self.tracker,
465            self.options.fonttype,
466        )
467    }
468
469    /// Writes the font descriptor and the program of the Type 1 font
470    /// `font` (`createType1Descriptor`); returns the descriptor.
471    ///
472    /// # Errors
473    ///
474    /// When a number of the font is not finite.
475    pub fn create_type1_descriptor(&mut self, font: &Type1Font) -> Result<u32, VectorError> {
476        let name = font
477            .prop()
478            .font_name()
479            .as_text()
480            .unwrap_or_default()
481            .to_owned();
482        tex::type1_descriptor(&mut self.writer, font, &name)
483    }
484
485    /// Writes the document information dictionary (`writeInfoDict`);
486    /// returns its object.
487    ///
488    /// # Errors
489    ///
490    /// Never in practice: the information is text and dates.
491    pub fn write_info_dict(&mut self) -> Result<u32, VectorError> {
492        let info = self.writer.reserve();
493        self.writer
494            .write_object(info, &pages::info_dict(&self.options.metadata))?;
495        self.info = Some(info);
496        Ok(info)
497    }
498
499    /// The first object reserved but not written yet, if any (the one
500    /// [`write_xref`](Self::write_xref) would fail on).
501    pub fn unwritten_object(&self) -> Option<usize> {
502        self.writer.unwritten()
503    }
504
505    /// Writes the cross-reference table (`writeXref`).
506    ///
507    /// # Errors
508    ///
509    /// When an object was reserved but never written.
510    pub fn write_xref(&mut self) -> Result<(), VectorError> {
511        self.writer.write_xref()
512    }
513
514    /// Writes the trailer (`writeTrailer`), after the document information
515    /// if it was not written yet.
516    ///
517    /// # Errors
518    ///
519    /// As [`write_info_dict`](Self::write_info_dict).
520    pub fn write_trailer(&mut self) -> Result<(), VectorError> {
521        let info = match self.info {
522            Some(info) => info,
523            None => self.write_info_dict()?,
524        };
525        self.writer.write_trailer(self.ids.root, info)
526    }
527
528    /// Closes the page and writes the deferred objects and the end of the
529    /// file (`finalize`): what [`write_deferred`](Self::write_deferred)
530    /// writes, then the cross-reference table and the trailer.
531    ///
532    /// # Errors
533    ///
534    /// As [`write_deferred`](Self::write_deferred) and
535    /// [`write_xref`](Self::write_xref).
536    pub fn finalize(&mut self) -> Result<(), VectorError> {
537        self.write_deferred()?;
538        self.write_xref()?;
539        self.write_trailer()
540    }
541
542    /// Closes the page and writes the deferred objects, all `finalize`
543    /// writes before the cross-reference table: annotations, fonts,
544    /// graphics states, hatches, shadings, `XObject`s, the page tree and
545    /// the document information.
546    ///
547    /// # Errors
548    ///
549    /// When a font, image or number met while drawing could not be
550    /// written.
551    pub fn write_deferred(&mut self) -> Result<(), VectorError> {
552        self.end_page()?;
553        self.pages.write_annotations(&mut self.writer)?;
554        self.write_fonts()?;
555        self.resources.write(
556            &mut self.writer,
557            self.ids.resources,
558            self.height,
559            self.options.compression > 0,
560        )?;
561        self.pages.write_tree(&mut self.writer, self.ids.pages)?;
562        self.write_info_dict()?;
563        Ok(())
564    }
565
566    /// The file written so far, after closing the open stream (matplotlib's
567    /// `close`).
568    ///
569    /// # Errors
570    ///
571    /// The first problem met while drawing (a font, image or number that
572    /// could not be written), or one of closing the stream.
573    pub fn close(mut self) -> Result<Vec<u8>, VectorError> {
574        self.end_stream()?;
575        self.problems.into_result(self.writer.into_bytes())
576    }
577}
578
579/// The face `index` of the font file `path`, as the text engine knows it
580/// (a bundled font by its place in the data directory, or its bare name).
581fn face_of_file(path: &FsPath, index: u32) -> Result<FontId, VectorError> {
582    let faces = TextEngine::global().file_faces(path)?;
583    usize::try_from(index)
584        .ok()
585        .and_then(|index| faces.get(index).copied())
586        .ok_or(VectorError::Unsupported(
587            "a font is named by a face its file has",
588        ))
589}
590
591/// The style of a hatch pattern.
592fn hatch_style(
593    edge: Option<Rgba>,
594    face: Option<Rgba>,
595    pattern: &str,
596    linewidth: f64,
597) -> HatchStyle {
598    HatchStyle {
599        edge,
600        face,
601        pattern: pattern.to_owned(),
602        linewidth,
603    }
604}
605
606#[cfg(test)]
607mod tests {
608    use super::*;
609    use crate::pdf::PdfOptions;
610
611    fn document() -> PdfRenderer {
612        PdfRenderer::document(PdfOptions {
613            compression: 0,
614            ..PdfOptions::default()
615        })
616        .unwrap()
617    }
618
619    fn text(pdf: &PdfRenderer) -> String {
620        String::from_utf8_lossy(pdf.writer.bytes()).into_owned()
621    }
622
623    #[test]
624    fn objects_and_streams_are_written_where_the_program_says() {
625        let mut pdf = document();
626        let object = pdf.reserve_object();
627        pdf.write_object(object, &Obj::Array(vec![Obj::Int(1), Obj::Null]))
628            .unwrap();
629        let stream = pdf.reserve_object();
630        pdf.begin_stream(stream, None, Vec::new(), None).unwrap();
631        assert_eq!(pdf.open_stream(), Some(stream));
632        assert!(matches!(
633            pdf.begin_stream(stream, None, Vec::new(), None),
634            Err(VectorError::StreamOpen)
635        ));
636        pdf.output_objects(&[Obj::Real(1.5), Obj::op("w")]).unwrap();
637        pdf.end_stream().unwrap();
638        assert_eq!(pdf.open_stream(), None);
639        let text = text(&pdf);
640        assert!(text.contains(&format!("{object} 0 obj\n[ 1 null ]\nendobj\n")));
641        assert!(text.contains(&format!("{stream} 0 obj\n<< /Length 6 >>\nstream\n1.5 w\n")));
642    }
643
644    #[test]
645    fn unwritten_objects_fail_the_cross_reference_table() {
646        // The page tree (object 2) is written when the document ends.
647        let mut pdf = document();
648        assert_eq!(pdf.unwritten_object(), Some(2));
649        assert!(matches!(
650            pdf.write_xref(),
651            Err(VectorError::UnwrittenObject(2))
652        ));
653    }
654
655    #[test]
656    fn resources_are_named_and_the_file_finished_on_demand() {
657        let mut pdf = document();
658        assert_eq!(pdf.alpha_state((0.5, 0.5)), "A1");
659        assert_eq!(pdf.alpha_state((0.5, 0.5)), "A1");
660        assert_eq!(pdf.new_alpha_state((0.5, 0.5)), "A2");
661        assert_eq!(pdf.hatch_pattern(Some(Rgba::BLACK), None, "/", 1.0), "H1");
662        assert_eq!(
663            pdf.hatch_patterns(),
664            [((Some(Rgba::BLACK), None, "/".to_owned()), "H1".to_owned())]
665        );
666        let (name, _) = pdf.add_gouraud_triangles(
667            vec![[
668                Point::new(0.0, 0.0),
669                Point::new(1.0, 0.0),
670                Point::new(0.0, 1.0),
671            ]],
672            ShadingColors::Gray(vec![[0.0, 0.5, 1.0]]),
673        );
674        assert_eq!(name, "GT0");
675        assert_eq!(pdf.core_font_name("Helvetica.afm").unwrap(), "F1");
676        assert!(pdf.core_font_name("nothing.afm").is_err());
677        assert_eq!(
678            pdf.font_names(),
679            [(PdfFont::Core("Helvetica.afm"), "F1".to_owned())]
680        );
681        assert_eq!(
682            pdf.font_name(FsPath::new("DejaVuSans.ttf"), 0, 0).unwrap(),
683            "F2"
684        );
685        assert!(pdf.font_name(FsPath::new("DejaVuSans.ttf"), 3, 0).is_err());
686        assert_eq!(pdf.reserve_font_name(), "F3");
687        assert_eq!(
688            pdf.font_name(FsPath::new("DejaVuSans.ttf"), 0, 1).unwrap(),
689            "F4"
690        );
691        assert_eq!(pdf.font_names().len(), 3);
692        pdf.new_page(1.0, 1.0, 72.0).unwrap();
693        pdf.finalize().unwrap();
694        let file = pdf.close().unwrap();
695        let text = String::from_utf8_lossy(&file);
696        assert!(text.contains("/A1 << /Type /ExtGState /CA 0.5 /ca 0.5 >>"));
697        assert!(text.contains("/ShadingType 4"));
698        assert!(text.contains("/BaseFont /Helvetica"));
699        assert!(text.ends_with("%%EOF\n"));
700    }
701
702    #[test]
703    fn the_end_matter_is_written_part_by_part() {
704        let mut pdf = document();
705        pdf.write_info_dict().unwrap();
706        pdf.write_fonts().unwrap();
707        pdf.write_ext_gstates().unwrap();
708        pdf.write_hatches().unwrap();
709        pdf.write_gouraud_triangles().unwrap();
710        pdf.write_images().unwrap();
711        pdf.write_markers().unwrap();
712        pdf.write_path_collection_templates().unwrap();
713        let text = text(&pdf);
714        assert!(text.contains("/Creator"));
715        assert!(
716            text.contains("4 0 obj\n<< >>\nendobj\n"),
717            "the graphics states"
718        );
719    }
720}