Skip to main content

plotine_backend_pdf/
lib.rs

1//! Vector PDF backend for plotine.
2//!
3//! Renders through the deterministic SVG backend, then converts with `svg2pdf`
4//! using the embedded DejaVu Sans font (no system font dependency).
5
6use std::fs;
7use std::path::Path;
8
9use kurbo::BezPath;
10use plotine_backend_svg::SvgRenderer;
11use plotine_core::{Color, PlotError, Point, Rect, Result};
12use plotine_render::{FillStyle, Renderer, StrokeStyle, TextStyle};
13use plotine_text::{registered_font_data, EMBEDDED_FONT, FONT_FAMILY};
14use svg2pdf::{ConversionOptions, PageOptions};
15
16/// Accumulates drawing commands and emits a PDF document.
17pub struct PdfRenderer {
18    inner: SvgRenderer,
19}
20
21impl PdfRenderer {
22    pub fn new(width: u32, height: u32) -> Result<Self> {
23        Ok(Self {
24            inner: SvgRenderer::new(width, height)?,
25        })
26    }
27
28    /// Convert the accumulated drawing commands into PDF bytes.
29    pub fn into_pdf(self) -> Result<Vec<u8>> {
30        let svg = self.inner.into_svg();
31        svg_to_pdf(&svg)
32    }
33
34    pub fn save_pdf(&self, path: impl AsRef<Path>) -> Result<()> {
35        // Clone via re-render path: SvgRenderer has no Clone; rebuild PDF from current SVG.
36        let svg = self.inner.to_svg_string();
37        let pdf = svg_to_pdf(&svg)?;
38        let path = path.as_ref();
39        if let Some(parent) = path.parent() {
40            if !parent.as_os_str().is_empty() {
41                fs::create_dir_all(parent).map_err(|e| PlotError::io(e.to_string()))?;
42            }
43        }
44        fs::write(path, pdf).map_err(|e| PlotError::io(e.to_string()))
45    }
46}
47
48/// Convert an SVG document (from [`SvgRenderer`]) into PDF bytes.
49pub fn svg_to_pdf(svg: &str) -> Result<Vec<u8>> {
50    let mut options = svg2pdf::usvg::Options::default();
51    options.fontdb_mut().load_font_data(EMBEDDED_FONT.to_vec());
52    // Extra faces registered via `plotine_text::register_font_*` (e.g. CJK).
53    for data in registered_font_data() {
54        options.fontdb_mut().load_font_data(data.to_vec());
55    }
56    // SVG emitter lists `{FONT_FAMILY}, …`; embedded DejaVu face must match.
57    debug_assert_eq!(FONT_FAMILY, "DejaVu Sans");
58    let tree = svg2pdf::usvg::Tree::from_str(svg, &options)
59        .map_err(|e| PlotError::render(format!("SVG→PDF parse failed: {e}")))?;
60    svg2pdf::to_pdf(&tree, ConversionOptions::default(), PageOptions::default())
61        .map_err(|e| PlotError::render(format!("SVG→PDF conversion failed: {e}")))
62}
63
64impl Renderer for PdfRenderer {
65    fn clear(&mut self, color: Color) -> Result<()> {
66        self.inner.clear(color)
67    }
68
69    fn fill_rect(&mut self, rect: Rect, style: &FillStyle) -> Result<()> {
70        self.inner.fill_rect(rect, style)
71    }
72
73    fn stroke_rect(&mut self, rect: Rect, style: &StrokeStyle) -> Result<()> {
74        self.inner.stroke_rect(rect, style)
75    }
76
77    fn fill_path(&mut self, path: &BezPath, style: &FillStyle) -> Result<()> {
78        self.inner.fill_path(path, style)
79    }
80
81    fn stroke_path(&mut self, path: &BezPath, style: &StrokeStyle) -> Result<()> {
82        self.inner.stroke_path(path, style)
83    }
84
85    fn draw_text(&mut self, text: &str, position: Point, style: &TextStyle) -> Result<()> {
86        self.inner.draw_text(text, position, style)
87    }
88
89    fn draw_rgba_image(
90        &mut self,
91        rgba: &[u8],
92        width: u32,
93        height: u32,
94        position: Point,
95    ) -> Result<()> {
96        self.inner.draw_rgba_image(rgba, width, height, position)
97    }
98
99    fn measure_text_styled(&self, text: &str, size_px: f32, italic: bool) -> Result<(f64, f64)> {
100        self.inner.measure_text_styled(text, size_px, italic)
101    }
102
103    fn push_clip_rect(&mut self, rect: Rect) -> Result<()> {
104        self.inner.push_clip_rect(rect)
105    }
106
107    fn pop_clip(&mut self) -> Result<()> {
108        self.inner.pop_clip()
109    }
110
111    fn width(&self) -> u32 {
112        self.inner.width()
113    }
114
115    fn height(&self) -> u32 {
116        self.inner.height()
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use plotine_render::FillStyle;
124
125    #[test]
126    fn pdf_magic_and_stable() {
127        let mut r = PdfRenderer::new(120, 80).unwrap();
128        r.clear(Color::WHITE).unwrap();
129        r.fill_rect(
130            Rect::new(10.0, 10.0, 50.0, 40.0),
131            &FillStyle::solid(Color::CRIMSON),
132        )
133        .unwrap();
134        let a = r.into_pdf().unwrap();
135        assert!(a.starts_with(b"%PDF"));
136
137        let mut r2 = PdfRenderer::new(120, 80).unwrap();
138        r2.clear(Color::WHITE).unwrap();
139        r2.fill_rect(
140            Rect::new(10.0, 10.0, 50.0, 40.0),
141            &FillStyle::solid(Color::CRIMSON),
142        )
143        .unwrap();
144        let b = r2.into_pdf().unwrap();
145        assert_eq!(a, b, "PDF should be byte-stable across runs");
146    }
147}