1mod 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#[derive(Clone, Debug, PartialEq)]
65pub struct PdfOptions {
66 pub compression: u8,
68 pub inherit_color: bool,
70 pub metadata: Metadata,
72 pub simplify: SimplifySettings,
74 pub composite_images: bool,
76 pub fonttype: FontType,
78 pub subset_fonttype: FontType,
83 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 pub fn afm_directory(&self) -> Option<AfmDirectory> {
108 self.core_fonts.then_some(AfmDirectory::PdfCore)
109 }
110}
111
112#[derive(Clone, Copy, Debug)]
114struct Ids {
115 root: u32,
116 pages: u32,
117 resources: ResourceIds,
118 resource_dictionary: u32,
119}
120
121fn 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#[derive(Debug)]
146pub struct PdfRenderer {
147 writer: PdfWriter,
148 width: f64,
150 height: f64,
151 image_dpi: f64,
152 ids: Ids,
153 pages: Pages,
154 page_open: bool,
156 resources: Resources,
157 states: StateStack,
158 font_names: FontNames,
159 dvi_fonts: DviFonts,
161 tracker: CharacterTracker,
162 fonts: FontCache,
163 options: PdfOptions,
164 generation: u64,
169 group_depth: usize,
170 problems: Problems,
171 info: Option<u32>,
173}
174
175impl PdfRenderer {
176 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 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 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 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 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 pub fn attach_note_objects(&mut self, contents: Obj, rect: Obj) {
327 self.pages.add_note(Note { contents, rect });
328 }
329
330 pub fn page_count(&self) -> usize {
332 self.pages.len()
333 }
334
335 pub fn image_names(&self) -> Vec<String> {
339 self.resources.image_names().map(str::to_owned).collect()
340 }
341
342 pub fn metadata_mut(&mut self) -> &mut Metadata {
345 &mut self.options.metadata
346 }
347
348 pub fn afm_directory(&self) -> Option<AfmDirectory> {
351 self.options.afm_directory()
352 }
353
354 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 pub fn finish(mut self) -> Result<Vec<u8>, VectorError> {
375 self.finalize()?;
376 self.close()
377 }
378
379 pub fn restore_gc(&mut self) -> Result<(), VectorError> {
386 let restore = self.states.finish();
387 self.writer.output(&restore)
388 }
389
390 fn output(&mut self, objects: &[Obj]) {
392 let result = self.writer.output(objects);
393 self.problems.record(result);
394 }
395
396 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 fn begin_draw(&mut self) {
409 if self.group_depth == 0 {
410 self.generation += 1;
411 }
412 }
413
414 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 fn dpi(&self) -> f64 {
427 self.image_dpi
428 }
429
430 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 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;