Skip to main content

kcode_html_to_pdf/
lib.rs

1#![forbid(unsafe_code)]
2
3use ironpress::HtmlConverter;
4use std::fmt;
5
6/// A custom TrueType font available to the rendered document.
7pub struct Font {
8    /// The family name referenced by CSS `font-family` declarations.
9    pub family: String,
10    /// The raw contents of a TrueType font file.
11    pub ttf: Vec<u8>,
12}
13
14/// An error returned when Ironpress cannot render the document.
15#[derive(Debug)]
16pub struct RenderError(String);
17
18impl fmt::Display for RenderError {
19    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20        formatter.write_str(&self.0)
21    }
22}
23
24impl std::error::Error for RenderError {}
25
26/// Renders one self-contained HTML document to PDF bytes.
27///
28/// CSS belongs in the document. Custom TTF fonts are registered under their
29/// supplied family names. Sanitization remains enabled, and no filesystem base
30/// path or remote-loading feature is configured.
31pub fn render(html: &str, fonts: Vec<Font>) -> Result<Vec<u8>, RenderError> {
32    let mut converter = HtmlConverter::new().sanitize(true);
33
34    for font in fonts {
35        converter = converter.add_font(&font.family, font.ttf);
36    }
37
38    converter
39        .convert(html)
40        .map_err(|error| RenderError(error.to_string()))
41}