1use 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#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum PdfFont {
27 TrueType {
29 file: PathBuf,
32 index: u32,
34 subset: usize,
36 },
37 Core(&'static str),
39}
40
41pub type PdfHatch = (Option<Rgba>, Option<Rgba>, String);
44
45impl PdfRenderer {
46 pub fn reserve_object(&mut self) -> u32 {
48 self.writer.reserve()
49 }
50
51 pub fn record_xref(&mut self, id: u32) {
55 self.writer.record(id);
56 }
57
58 pub fn write_object(&mut self, id: u32, contents: &Obj) -> Result<(), VectorError> {
64 self.writer.write_object(id, contents)
65 }
66
67 pub fn write(&mut self, data: &[u8]) {
70 self.writer.write(data);
71 }
72
73 pub fn output_objects(&mut self, objects: &[Obj]) -> Result<(), VectorError> {
80 self.writer.output(objects)
81 }
82
83 pub fn open_stream(&self) -> Option<u32> {
87 self.writer.open_stream()
88 }
89
90 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 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 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 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 pub fn object_count(&self) -> usize {
163 self.writer.object_count()
164 }
165
166 pub fn alpha_state(&mut self, alphas: (f64, f64)) -> String {
169 self.resources.alpha_state(alphas)
170 }
171
172 pub fn new_alpha_state(&mut self, alphas: (f64, f64)) -> String {
177 self.resources.new_alpha_state(alphas)
178 }
179
180 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 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 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 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 pub fn image_object(&mut self, image: &RgbaImage) -> String {
232 self.resources.image(&mut self.writer, image)
233 }
234
235 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 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 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 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 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 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 pub fn write_markers(&mut self) -> Result<(), VectorError> {
308 self.resources.write_markers(&mut self.writer)
309 }
310
311 pub fn write_path_collection_templates(&mut self) -> Result<(), VectorError> {
318 self.resources.write_path_templates(&mut self.writer)
319 }
320
321 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 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 pub fn reserve_font_name(&mut self) -> String {
359 self.font_names.reserve()
360 }
361
362 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 pub fn dvi_font_name(&mut self, font: Arc<DviFont>, files: &'static TexFiles) -> String {
392 self.dvi_fonts.register(font, files)
393 }
394
395 pub fn dvi_font_used(&self, name: &str) -> bool {
399 self.dvi_fonts.is_used(name)
400 }
401
402 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 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 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 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 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 pub fn unwritten_object(&self) -> Option<usize> {
502 self.writer.unwritten()
503 }
504
505 pub fn write_xref(&mut self) -> Result<(), VectorError> {
511 self.writer.write_xref()
512 }
513
514 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 pub fn finalize(&mut self) -> Result<(), VectorError> {
537 self.write_deferred()?;
538 self.write_xref()?;
539 self.write_trailer()
540 }
541
542 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 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
579fn 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
591fn 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 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}