kcode-html-to-pdf 0.1.1

A tiny self-contained HTML/CSS to PDF wrapper around Ironpress
Documentation
#![forbid(unsafe_code)]

use ironpress::HtmlConverter;
use std::fmt;

/// A custom TrueType font available to the rendered document.
pub struct Font {
    /// The family name referenced by CSS `font-family` declarations.
    pub family: String,
    /// The raw contents of a TrueType font file.
    pub ttf: Vec<u8>,
}

/// An error returned when Ironpress cannot render the document.
#[derive(Debug)]
pub struct RenderError(String);

impl fmt::Display for RenderError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl std::error::Error for RenderError {}

/// Renders one self-contained HTML document to PDF bytes.
///
/// CSS belongs in the document. Custom TTF fonts are registered under their
/// supplied family names. Sanitization remains enabled, and no filesystem base
/// path or remote-loading feature is configured.
pub fn render(html: &str, fonts: Vec<Font>) -> Result<Vec<u8>, RenderError> {
    let mut converter = HtmlConverter::new().sanitize(true);

    for font in fonts {
        converter = converter.add_font(&font.family, font.ttf);
    }

    converter
        .convert(html)
        .map_err(|error| RenderError(error.to_string()))
}