Skip to main content

rpic_render/
lib.rs

1//! Raster (PNG) and PDF backends for rpic.
2//!
3//! These consume the SVG produced by `rpic-core` and convert it with pure-Rust
4//! libraries (no system dependencies), keeping `rpic-core` itself
5//! dependency-free and WASM-friendly.
6//!
7//! - PNG: parse the SVG with `usvg`, rasterize with `resvg`/`tiny-skia`.
8//! - PDF: parse with svg2pdf's `usvg`, convert with `svg2pdf`.
9//!
10//! Text is rendered with a **bundled** font (the Go font, BSD-3-Clause)
11//! registered as every default family, so attached labels rasterize identically
12//! on any machine — no dependency on which fonts happen to be installed. See
13//! `fonts/LICENSE`.
14
15/// Bundled font used for all text (the SVG backend emits `font-family="sans-serif"`).
16const EMBEDDED_FONT: &[u8] = include_bytes!("../fonts/Go-Regular.ttf");
17/// The bundled font's internal family name.
18const EMBEDDED_FONT_FAMILY: &str = "Go";
19
20/// Rasterize an SVG string to PNG bytes at the given scale (1.0 = 96 dpi, the
21/// SVG's native resolution).
22pub fn to_png(svg: &str, scale: f32) -> Result<Vec<u8>, String> {
23    use resvg::{tiny_skia, usvg};
24
25    let mut opt = usvg::Options::default();
26    {
27        let db = opt.fontdb_mut();
28        db.load_font_data(EMBEDDED_FONT.to_vec());
29        db.set_serif_family(EMBEDDED_FONT_FAMILY);
30        db.set_sans_serif_family(EMBEDDED_FONT_FAMILY);
31        db.set_monospace_family(EMBEDDED_FONT_FAMILY);
32        db.set_cursive_family(EMBEDDED_FONT_FAMILY);
33        db.set_fantasy_family(EMBEDDED_FONT_FAMILY);
34    }
35    let tree = usvg::Tree::from_str(svg, &opt).map_err(|e| e.to_string())?;
36
37    let size = tree.size();
38    let w = ((size.width() * scale).ceil() as u32).max(1);
39    let h = ((size.height() * scale).ceil() as u32).max(1);
40    let mut pixmap = tiny_skia::Pixmap::new(w, h).ok_or("failed to allocate pixmap")?;
41    resvg::render(
42        &tree,
43        tiny_skia::Transform::from_scale(scale, scale),
44        &mut pixmap.as_mut(),
45    );
46    pixmap.encode_png().map_err(|e| e.to_string())
47}
48
49/// Convert an SVG string to PDF bytes.
50pub fn to_pdf(svg: &str) -> Result<Vec<u8>, String> {
51    use svg2pdf::usvg;
52
53    let mut opt = usvg::Options::default();
54    {
55        let db = opt.fontdb_mut();
56        db.load_font_data(EMBEDDED_FONT.to_vec());
57        db.set_serif_family(EMBEDDED_FONT_FAMILY);
58        db.set_sans_serif_family(EMBEDDED_FONT_FAMILY);
59        db.set_monospace_family(EMBEDDED_FONT_FAMILY);
60        db.set_cursive_family(EMBEDDED_FONT_FAMILY);
61        db.set_fantasy_family(EMBEDDED_FONT_FAMILY);
62    }
63    let tree = usvg::Tree::from_str(svg, &opt).map_err(|e| e.to_string())?;
64
65    svg2pdf::to_pdf(
66        &tree,
67        svg2pdf::ConversionOptions::default(),
68        svg2pdf::PageOptions::default(),
69    )
70    .map_err(|e| e.to_string())
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76
77    const SVG: &str = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"20\" viewBox=\"0 0 40 20\"><rect x=\"2\" y=\"2\" width=\"36\" height=\"16\" fill=\"none\" stroke=\"black\"/></svg>";
78    const SVG_TEXT: &str = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"120\" height=\"40\" viewBox=\"0 0 120 40\" font-family=\"sans-serif\" font-size=\"16\"><text x=\"4\" y=\"24\">Hello world</text></svg>";
79
80    #[test]
81    fn png_has_magic_and_scales() {
82        let one = to_png(SVG, 1.0).unwrap();
83        assert_eq!(&one[..4], &[0x89, 0x50, 0x4E, 0x47]); // PNG signature
84        let two = to_png(SVG, 2.0).unwrap();
85        assert!(two.len() > one.len()); // larger raster at 2x
86    }
87
88    #[test]
89    fn pdf_has_magic() {
90        let pdf = to_pdf(SVG).unwrap();
91        assert_eq!(&pdf[..4], b"%PDF");
92    }
93
94    #[test]
95    fn bundled_font_rasterizes_text() {
96        // text must produce non-blank pixels using only the embedded font (no
97        // reliance on system fonts) — the text PNG is materially larger than an
98        // identically-sized blank one.
99        let with_text = to_png(SVG_TEXT, 1.0).unwrap();
100        let blank = to_png(
101            "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"120\" height=\"40\" viewBox=\"0 0 120 40\"></svg>",
102            1.0,
103        )
104        .unwrap();
105        assert!(
106            with_text.len() > blank.len() + 200,
107            "text PNG {} vs blank {}",
108            with_text.len(),
109            blank.len()
110        );
111    }
112}