use std::fmt::Write as _;
use std::path::Path;
use std::sync::{Arc, Mutex};
use svgtypes::LengthUnit;
use resvg::usvg;
use roxmltree::Node;
use super::{data_uri, read_data_uri, resources, AssetView, ImageFontSubstitution, Intrinsics};
use crate::{Error, Result};
#[derive(Debug)]
pub(super) struct SvgAsset {
source: String,
intrinsic: Intrinsics,
}
impl SvgAsset {
pub(super) fn from_file(bytes: &[u8], path: &Path) -> Result<Self> {
Self::from_closed(resources::close(bytes, Some(path))?)
}
pub(super) fn from_bytes(bytes: &[u8]) -> Result<Self> {
Self::from_closed(resources::close(bytes, None)?)
}
fn from_closed(source: String) -> Result<Self> {
let document = resources::parse(&source)?;
let intrinsic = intrinsic_size(&document)?;
let source = if document.descendants().any(|node| node.has_tag_name("text")) {
source
} else {
let mut edits = Vec::new();
for style in document
.descendants()
.filter(|node| node.has_tag_name("style"))
{
let css = style.text().unwrap_or("");
let ranges = font_face_ranges(css)?;
if ranges.is_empty() {
continue;
}
let css = resources::apply_edits(
css,
ranges
.into_iter()
.map(|range| (range, String::new()))
.collect(),
)?;
edits.push((
style.range(),
resources::style_element(&css, style.attribute("media")),
));
}
resources::apply_edits(&source, edits)?
};
Ok(Self { source, intrinsic })
}
pub(super) const fn intrinsics(&self) -> Intrinsics {
self.intrinsic
}
pub(super) fn exact_ink(
&self,
viewport: crate::layout::Rect,
clip: crate::layout::Rect,
) -> Result<crate::layout::InkExtent> {
crate::composition::ink::svg_ink(&self.source, viewport, clip)
}
pub(super) fn prepare(&self, viewport: (f64, f64)) -> Result<AssetView> {
let source = viewport_xml(&self.source, self.intrinsic.complete().unwrap_or(viewport))?;
let mut substitutions = Vec::new();
let outline = match outline_document(&source, &mut substitutions) {
Ok(Some(outline)) => Some(Ok(Arc::from(data_uri("image/svg+xml", outline.as_bytes())))),
Ok(None) => None,
Err(error) => {
substitutions.clear();
if matches!(error, Error::Cancelled) {
return Err(error);
}
crate::operation::checkpoint()?;
Some(Err(error
.diagnostic()
.cloned()
.unwrap_or_else(|| error.to_string().into())))
}
};
let preserve_error = match validate_font_embedding(&source) {
Ok(()) => None,
Err(error) => Some(
error
.diagnostic()
.cloned()
.unwrap_or_else(|| error.to_string().into()),
),
};
crate::operation::checkpoint()?;
Ok(AssetView {
preserved: Arc::from(data_uri("image/svg+xml", source.as_bytes())),
outlined: outline,
preserve_error,
substitutions,
})
}
}
fn svg_length(value: Option<&str>) -> Result<Option<f64>> {
let Some(value) = value.filter(|value| *value != "auto") else {
return Ok(None);
};
let length = value.parse::<svgtypes::Length>().map_err(|error| {
Error::Data(format!("invalid SVG intrinsic length {value:?}: {error}").into())
})?;
let scale = match length.unit {
LengthUnit::None | LengthUnit::Px => 1.,
LengthUnit::In => 96.,
LengthUnit::Cm => 4800. / 127.,
LengthUnit::Mm => 480. / 127.,
LengthUnit::Pt => 4. / 3.,
LengthUnit::Pc => 16.,
LengthUnit::Percent | LengthUnit::Em | LengthUnit::Ex => return Ok(None),
};
let value = length.number * scale;
if value <= 0. || !value.is_finite() {
return Err(Error::Data(
"SVG intrinsic dimensions must be finite and positive".into(),
));
}
Ok(Some(value))
}
fn intrinsic_size(document: &roxmltree::Document<'_>) -> Result<Intrinsics> {
let root = document.root_element();
let mut size = [root.attribute("width"), root.attribute("height")];
let sheet = super::css::sheet(document);
for declaration in super::css::declarations(root, &sheet) {
if let Some(index) = ["width", "height"]
.iter()
.position(|name| *name == declaration.name)
{
size[index] = Some(declaration.value);
}
}
let size = [svg_length(size[0])?, svg_length(size[1])?];
let view_box = root
.attribute("viewBox")
.map(str::parse::<svgtypes::ViewBox>)
.transpose()
.map_err(|error| Error::Data(format!("invalid SVG viewBox: {error}").into()))?;
let ratio = if let [Some(w), Some(h)] = size {
Some(w / h)
} else {
view_box.map(|view| view.w / view.h)
};
if ratio.is_some_and(|value| value <= 0. || !value.is_finite()) {
return Err(Error::Data(
"SVG aspect ratio must be finite and positive".into(),
));
}
Ok(Intrinsics { size, ratio })
}
fn viewport_xml(source: &str, viewport: (f64, f64)) -> Result<String> {
let document = resources::parse(source)?;
let root = document.root_element();
let mut edits = Vec::new();
let mut attributes = String::new();
for (name, value) in [("width", viewport.0), ("height", viewport.1)] {
if let Some(attribute) = root.attribute_node(name) {
edits.push((attribute.range_value(), value.to_string()));
} else {
let _ = write!(attributes, " {name}=\"{value}\"");
}
}
let forced = format!(
";width:{}px !important;height:{}px !important;",
viewport.0, viewport.1
);
if let Some(style) = root.attribute_node("style") {
edits.push((
style.range_value(),
resources::escape(&format!("{}{forced}", style.value())),
));
} else {
let _ = write!(attributes, " style=\"{}\"", resources::escape(&forced));
}
let end = resources::opening_end(source, root);
let offset = if source.as_bytes()[end - 1] == b'/' {
end - 1
} else {
end
};
edits.push((offset..offset, attributes));
resources::apply_edits(source, edits)
}
fn outline_document(
source: &str,
substitutions: &mut Vec<ImageFontSubstitution>,
) -> Result<Option<String>> {
let document = resources::parse(source)?;
let mut edits = Vec::new();
for node in document.descendants().filter(Node::is_element) {
if !matches!(node.tag_name().name(), "image" | "feImage") {
continue;
}
let Some(href) = node
.attributes()
.find(|attr| attr.name() == "href" && attr.value().starts_with("data:"))
else {
continue;
};
let (mime, bytes) = read_data_uri(href.value())?;
if mime != "image/svg+xml" {
continue;
}
let nested = SvgAsset::from_closed(resources::utf8(&bytes)?.to_owned())?;
if href.value().contains('#') {
if nested.source.contains("<text") {
return Err(Error::Render(
"cannot outline text in an SVG image fragment".into(),
));
}
continue;
}
let viewport = nested
.intrinsics()
.complete()
.or_else(|| {
let width = svg_length(node.attribute("width")).ok().flatten()?;
let height = svg_length(node.attribute("height")).ok().flatten()?;
Some((width, height))
})
.ok_or_else(|| {
Error::Render("nested SVG needs a definite source or image viewport".into())
})?;
let source = viewport_xml(&nested.source, viewport)?;
let outlined = outline_document(&source, substitutions)?.unwrap_or(source);
edits.push((
href.range_value(),
data_uri("image/svg+xml", outlined.as_bytes()),
));
}
let has_text = document
.descendants()
.any(|node| node.has_tag_name(("http://www.w3.org/2000/svg", "text")));
if !has_text && edits.is_empty() {
return Ok(None);
}
let source = resources::apply_edits(source, edits)?;
if !has_text {
return Ok(Some(source));
}
validate_renderer(&source)?;
let tree = text_tree(&source, substitutions)?;
let options = usvg::WriteOptions {
preserve_text: false,
..Default::default()
};
Ok(Some(tree.to_string(&options)))
}
fn offline_options() -> usvg::Options<'static> {
usvg::Options {
image_href_resolver: usvg::ImageHrefResolver {
resolve_data: usvg::ImageHrefResolver::default_data_resolver(),
resolve_string: Box::new(|_, _| None),
},
..Default::default()
}
}
fn font_face_ranges(css: &str) -> Result<Vec<std::ops::Range<usize>>> {
let lower = css.to_ascii_lowercase();
let mut offset = 0;
let mut result = Vec::new();
while let Some(start) = lower[offset..]
.find("@font-face")
.map(|index| offset + index)
{
let open = css[start..]
.find('{')
.map(|index| start + index)
.ok_or_else(|| Error::Data("invalid SVG @font-face rule".into()))?;
let mut quote = None;
let mut escaped = false;
let mut end = None;
for (index, ch) in css[open + 1..].char_indices() {
if escaped {
escaped = false;
continue;
}
if ch == '\\' {
escaped = true;
continue;
}
match (quote, ch) {
(Some(value), ch) if value == ch => quote = None,
(None, '"' | '\'') => quote = Some(ch),
(None, '}') => {
end = Some(open + index + 2);
break;
}
_ => {}
}
}
let end = end.ok_or_else(|| Error::Data("unterminated SVG @font-face rule".into()))?;
result.push(start..end);
offset = end;
}
Ok(result)
}
fn validate_font_embedding(source: &str) -> Result<()> {
let document = resources::parse(source)?;
for style in document
.descendants()
.filter(|node| node.has_tag_name("style"))
{
let css = style.text().unwrap_or("");
for range in font_face_ranges(css)? {
let body = &css[range];
for reference in body.split("url(\"").skip(1) {
let Some((href, _)) = reference.split_once('"') else {
continue;
};
let (_, bytes) = read_data_uri(href)?;
let count = ttf_parser::fonts_in_collection(&bytes).unwrap_or(1);
for index in 0..count {
let face = ttf_parser::Face::parse(&bytes, index).map_err(|_| {
Error::Render("cannot verify permission of embedded SVG font".into())
})?;
if !face.is_outline_embedding_allowed()
|| !matches!(
face.permissions(),
Some(
ttf_parser::Permissions::Installable
| ttf_parser::Permissions::Editable
)
)
{
return Err(Error::Render("SVG preserve-text output cannot embed the supplied font with its declared embedding permissions".into()));
}
}
}
}
}
for node in document
.descendants()
.filter(|node| matches!(node.tag_name().name(), "image" | "feImage"))
{
if let Some(href) = node
.attributes()
.find(|attr| attr.name() == "href" && attr.value().starts_with("data:image/svg+xml"))
{
let (_, bytes) = read_data_uri(href.value())?;
validate_font_embedding(resources::utf8(&bytes)?)?;
}
}
Ok(())
}
fn local_font_database(source: &str) -> Result<fontdb::Database> {
let document = resources::parse(source)?;
let mut db = fontdb::Database::new();
for style in document
.descendants()
.filter(|node| node.has_tag_name("style"))
{
let css = style.text().unwrap_or("");
for range in font_face_ranges(css)? {
let (_, body) = css[range].split_once('{').expect("parsed font-face");
let body = body.strip_suffix('}').expect("parsed font-face");
let mut family = None;
let mut sources = None;
let mut weight = fontdb::Weight::NORMAL;
let mut style = fontdb::Style::Normal;
let mut stretch = fontdb::Stretch::Normal;
for declaration in simplecss::DeclarationTokenizer::from(body) {
match declaration.name {
"font-family" => family = Some(declaration.value.trim_matches(['"', '\''])),
"src" => sources = Some(declaration.value),
"font-weight" => {
weight = match declaration.value {
"normal" => fontdb::Weight::NORMAL,
"bold" => fontdb::Weight::BOLD,
value => fontdb::Weight(value.parse().map_err(|_| {
Error::Render("unsupported SVG @font-face weight descriptor".into())
})?),
};
}
"font-style" => {
style = match declaration.value {
"normal" => fontdb::Style::Normal,
"italic" => fontdb::Style::Italic,
"oblique" => fontdb::Style::Oblique,
_ => {
return Err(Error::Render(
"unsupported SVG @font-face style descriptor".into(),
))
}
};
}
"font-stretch" => {
stretch = match declaration.value {
"ultra-condensed" => fontdb::Stretch::UltraCondensed,
"extra-condensed" => fontdb::Stretch::ExtraCondensed,
"condensed" => fontdb::Stretch::Condensed,
"semi-condensed" => fontdb::Stretch::SemiCondensed,
"normal" => fontdb::Stretch::Normal,
"semi-expanded" => fontdb::Stretch::SemiExpanded,
"expanded" => fontdb::Stretch::Expanded,
"extra-expanded" => fontdb::Stretch::ExtraExpanded,
"ultra-expanded" => fontdb::Stretch::UltraExpanded,
_ => {
return Err(Error::Render(
"unsupported SVG @font-face stretch descriptor".into(),
))
}
};
}
"unicode-range" => {
return Err(Error::Render(
"SVG device cannot evaluate @font-face unicode-range".into(),
))
}
_ => {}
}
}
let (Some(family), Some(sources)) = (family, sources) else {
return Err(Error::Render("invalid asset @font-face declaration".into()));
};
let mut loaded = false;
for url in sources.split("url(\"").skip(1) {
let Some((href, _)) = url.split_once('"') else {
continue;
};
let (_, bytes) = read_data_uri(href)?;
let ids = db.load_font_source(fontdb::Source::Binary(Arc::new(bytes)));
if ids.is_empty() {
continue;
}
for id in ids {
let mut face = db.face(id).expect("loaded font ID").clone();
db.remove_face(id);
face.families =
vec![(family.to_owned(), fontdb::Language::English_UnitedStates)];
face.weight = weight;
face.style = style;
face.stretch = stretch;
db.push_face_info(face);
}
loaded = true;
break;
}
if !loaded {
return Err(Error::Render(
format!("asset @font-face {family:?} has no supported font source").into(),
));
}
}
}
Ok(db)
}
struct FontSelection {
catalog: Option<crate::font::canonical::SvgFontCatalog>,
error: Option<Error>,
candidates: Vec<(fontdb::ID, ImageFontSubstitution)>,
}
impl FontSelection {
fn record(
&mut self,
requested: String,
selected: fontdb::ID,
scalar: Option<char>,
db: &fontdb::Database,
) {
if let Some(family) = db.face(selected).and_then(|face| face.families.first()) {
let record = ImageFontSubstitution {
requested,
selected: family.0.clone(),
scalar,
};
if !self
.candidates
.iter()
.any(|(id, existing)| *id == selected && *existing == record)
{
self.candidates.push((selected, record));
}
}
}
fn catalog(&mut self) -> Result<&mut crate::font::canonical::SvgFontCatalog> {
if self.catalog.is_none() {
self.catalog = Some(crate::font::canonical::SvgFontCatalog::new()?);
}
Ok(self.catalog.as_mut().expect("prepared SVG font catalog"))
}
fn select(
&mut self,
font: &usvg::Font,
db: &mut fontdb::Database,
) -> Result<Option<fontdb::ID>> {
let mut families: Vec<_> = font
.families()
.iter()
.map(|family| match family {
usvg::FontFamily::Named(name) => fontdb::Family::Name(name),
usvg::FontFamily::Serif => fontdb::Family::Serif,
usvg::FontFamily::SansSerif => fontdb::Family::SansSerif,
usvg::FontFamily::Monospace => fontdb::Family::Monospace,
usvg::FontFamily::Cursive => fontdb::Family::Cursive,
usvg::FontFamily::Fantasy => fontdb::Family::Fantasy,
})
.collect();
let query = |db: &fontdb::Database,
families: &[fontdb::Family<'_>]|
-> Result<Option<fontdb::ID>> {
let mut resolved = Vec::new();
for family in families {
let name = db.family_name(family);
if let Some(actual) = crate::font::canonical::svg_family_name(db, name)? {
resolved.push(fontdb::Family::Name(actual));
}
}
Ok(db.query(&fontdb::Query {
families: &resolved,
weight: fontdb::Weight(font.weight()),
style: font.style().into(),
stretch: font.stretch().into(),
}))
};
let request = || {
font.families()
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
};
for (index, family) in families.iter().enumerate() {
if !matches!(family, fontdb::Family::Name(_)) {
self.catalog()?.load(std::slice::from_ref(family), db)?;
}
let mut id = query(db, std::slice::from_ref(family))?;
if id.is_none() {
self.catalog()?.load(std::slice::from_ref(family), db)?;
id = query(db, std::slice::from_ref(family))?;
}
if let Some(id) = id {
if index > 0 {
self.record(request(), id, None, db);
}
return Ok(Some(id));
}
}
families = vec![
fontdb::Family::Serif,
fontdb::Family::SansSerif,
fontdb::Family::Monospace,
];
self.catalog()?.load(&families, db)?;
let id = query(db, &families)?.ok_or_else(|| {
Error::Render(format!("no SVG font for {:?}", font.families()).into())
})?;
self.record(request(), id, None, db);
Ok(Some(id))
}
}
fn text_tree(source: &str, substitutions: &mut Vec<ImageFontSubstitution>) -> Result<usvg::Tree> {
let state = Mutex::new(FontSelection {
catalog: None,
error: None,
candidates: Vec::new(),
});
let options = usvg::Options {
fontdb: Arc::new(local_font_database(source)?),
font_resolver: usvg::FontResolver {
select_font: Box::new(|font, db| {
let mut state = state.lock().expect("SVG font selection");
match state.select(font, Arc::make_mut(db)) {
Ok(value) => value,
Err(error) => {
state.error = Some(error);
None
}
}
}),
select_fallback: Box::new(|scalar, used, db| {
if crate::text::is_nonpainting_control(scalar) {
return None;
}
let mut state = state.lock().expect("SVG font selection");
let request = used
.first()
.and_then(|id| db.face(*id))
.and_then(|face| face.families.first())
.map_or_else(String::new, |family| family.0.clone());
let lookup = usvg::FontResolver::default_fallback_selector();
if let Some(id) = lookup(scalar, used, db) {
state.record(request, id, Some(scalar), db);
return Some(id);
}
let result = state
.catalog()
.and_then(|catalog| catalog.fallback(scalar, Arc::make_mut(db)));
match result {
Ok(Some(id)) => {
state.record(request, id, Some(scalar), db);
Some(id)
}
Ok(None) => {
state.error = Some(Error::Render(
format!("SVG asset has no glyph for {scalar:?}").into(),
));
None
}
Err(error) => {
state.error = Some(error);
None
}
}
}),
},
..offline_options()
};
let tree = usvg::Tree::from_str(source, &options)
.map_err(|error| Error::Render(format!("outline SVG asset: {error}").into()))?;
if let Some(error) = state.lock().expect("SVG font selection").error.take() {
return Err(error);
}
let mut used = std::collections::HashSet::new();
check_glyphs(tree.root(), &mut used)?;
let mut state = state.lock().expect("SVG font selection");
for (id, substitution) in state.candidates.drain(..) {
if used.contains(&(id, substitution.scalar)) && !substitutions.contains(&substitution) {
substitutions.push(substitution);
}
}
Ok(tree)
}
fn check_glyphs(
group: &usvg::Group,
used: &mut std::collections::HashSet<(fontdb::ID, Option<char>)>,
) -> Result<()> {
for node in group.children() {
match node {
usvg::Node::Text(text) => {
for span in text.layouted().iter().filter(|span| span.visible) {
for glyph in &span.positioned_glyphs {
used.insert((glyph.font, None));
used.extend(glyph.text.chars().map(|ch| (glyph.font, Some(ch))));
}
if span.positioned_glyphs.iter().any(|glyph| {
glyph.id.0 == 0
&& glyph.text.chars().any(|ch| {
!ch.is_whitespace() && !crate::text::is_nonpainting_control(ch)
})
}) {
return Err(Error::Render(
"SVG asset contains a missing visible glyph".into(),
));
}
}
}
usvg::Node::Group(group) => check_glyphs(group, used)?,
_ => {}
}
let mut result = Ok(());
node.subroots(|root| {
if result.is_ok() {
result = check_glyphs(root, used);
}
});
result?;
}
Ok(())
}
fn validate_renderer(source: &str) -> Result<()> {
let document = resources::parse(source)?;
let sheet = super::css::sheet(&document);
for node in document.descendants().filter(Node::is_element) {
if matches!(
node.tag_name().name(),
"mesh"
| "meshgradient"
| "meshrow"
| "meshpatch"
| "hatch"
| "hatchpath"
| "flowRoot"
| "flowPara"
| "solidcolor"
| "color-profile"
| "video"
| "audio"
) {
return Err(Error::Render(
format!("SVG device does not support {}", node.tag_name().name()).into(),
));
}
let unsupported_css = |css: &str| {
["var(", "calc(", "color(", "@media", "@supports", "@layer"]
.iter()
.any(|token| css.contains(token))
};
if node.attribute("style").is_some_and(unsupported_css)
|| (node.has_tag_name("style") && node.text().is_some_and(unsupported_css))
{
return Err(Error::Render(
"SVG device cannot faithfully evaluate this CSS expression or conditional sheet"
.into(),
));
}
if node.has_tag_name("style") && node.attribute("media").is_some_and(|media| media != "all")
{
return Err(Error::Render(
"SVG device cannot evaluate a conditional stylesheet".into(),
));
}
if matches!(node.tag_name().name(), "image" | "feImage")
&& node.attributes().any(|attr| {
attr.name() == "href"
&& attr.value().starts_with("data:")
&& attr.value().contains('#')
})
{
return Err(Error::Render(
"SVG device does not support image fragment viewports".into(),
));
}
if let Some(filter) = super::css::declarations(node, &sheet)
.iter()
.rev()
.find(|declaration| declaration.name == "filter")
.map(|declaration| declaration.value)
.or_else(|| node.attribute("filter"))
{
for value in svgtypes::FilterValueListParser::from(filter) {
match value.map_err(|error| {
Error::Render(format!("unsupported SVG filter {filter:?}: {error}").into())
})? {
svgtypes::FilterValue::Url(id)
if !document.descendants().any(|node| {
node.attribute("id") == Some(id) && node.has_tag_name("filter")
}) =>
{
return Err(Error::Render(
format!("SVG filter references missing definition {id:?}").into(),
));
}
_ => {}
}
}
}
}
Ok(())
}
pub(crate) fn raster_svg(bytes: &[u8]) -> Result<usvg::Tree> {
let source = resources::utf8(bytes)?;
validate_renderer(source)?;
let error = Mutex::new(None);
let options = usvg::Options {
image_href_resolver: usvg::ImageHrefResolver {
resolve_data: Box::new(|mime, data, _options| {
let result = match mime {
"image/png" => super::png::png_samples(&data)
.and_then(png_for_svg)
.map(|bytes| Some(usvg::ImageKind::PNG(Arc::new(bytes)))),
"image/svg+xml" => {
raster_svg(&data).map(|tree| Some(usvg::ImageKind::SVG(tree)))
}
"image/jpg" | "image/jpeg" | "image/gif" | "image/webp" => {
super::raster_image::decode(mime, &data)
.and_then(png_for_svg)
.map(|bytes| Some(usvg::ImageKind::PNG(Arc::new(bytes))))
}
_ => Err(Error::Render(
format!("SVG device cannot decode {mime}").into(),
)),
};
match result {
Ok(kind) => kind,
Err(cause) => {
*error.lock().expect("SVG resource result") = Some(cause);
None
}
}
}),
resolve_string: Box::new(|href, _| {
*error.lock().expect("SVG resource result") = Some(Error::Render(
format!("unsealed SVG resource {href:?}").into(),
));
None
}),
},
..offline_options()
};
if source.contains("<text") {
return Err(Error::Render(
"SVG asset rasterization requires frozen text outlines".into(),
));
}
let tree = usvg::Tree::from_str(source, &options)
.map_err(|error| Error::Render(format!("rasterize SVG asset: {error}").into()))?;
if let Some(error) = error.lock().expect("SVG resource result").take() {
return Err(error);
}
Ok(tree)
}
fn png_for_svg(samples: super::PngSamples) -> Result<Vec<u8>> {
let mut raw = Vec::new();
let count = samples
.rgba
.len()
.checked_mul(8)
.ok_or_else(|| Error::Render("embedded PNG sample storage overflow".into()))?;
crate::data::source::reserve_source(&mut raw, count)?;
for pixel in samples.rgba {
for channel in pixel {
raw.extend_from_slice(&channel.to_be_bytes());
}
}
let mut result = Vec::new();
let mut encoder = png::Encoder::new(&mut result, samples.width, samples.height);
encoder.set_depth(png::BitDepth::Sixteen);
encoder.set_color(png::ColorType::Rgba);
encoder.set_source_srgb(png::SrgbRenderingIntent::RelativeColorimetric);
let mut writer = encoder
.write_header()
.map_err(|error| Error::Render(format!("encode embedded SVG PNG: {error}").into()))?;
writer
.write_image_data(&raw)
.map_err(|error| Error::Render(format!("encode embedded SVG PNG: {error}").into()))?;
writer
.finish()
.map_err(|error| Error::Render(format!("finish embedded SVG PNG: {error}").into()))?;
Ok(result)
}