#![cfg_attr(feature = "parse", doc = "```no_run")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
use super::{Measure, PDF, PDF_OUTLINES, parse, texts};
use crate::Error;
use krilla::configure::{Accessibility, Archival, ConfigurationBuilder, PdfVersion};
use krilla::destination::XyzDestination;
use krilla::geom::{Point, Size};
use krilla::metadata::{DateTime, Metadata};
use krilla::outline::{Outline, OutlineNode};
use krilla::page::PageSettings;
use krilla::tagging::{ContentTag, Tag, TagGroup, TagTree};
use krilla::{Document, SerializeSettings};
use krilla_svg::{SurfaceExt, SvgSettings};
const POINTS_PER_PIXEL: f32 = 0.75;
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(default, deny_unknown_fields))]
pub struct Options {
pub embed_text: bool,
pub compatible: bool,
pub accessible: bool,
pub title: Option<String>,
pub language: String,
pub date: Option<Date>,
}
impl Default for Options {
fn default() -> Self {
Self {
embed_text: true,
compatible: false,
accessible: false,
title: None,
language: "en".to_owned(),
date: None,
}
}
}
impl Options {
#[must_use]
pub fn with_embed_text(self, embed_text: bool) -> Self {
Self { embed_text, ..self }
}
#[must_use]
pub fn with_compatible(self, compatible: bool) -> Self {
Self { compatible, ..self }
}
#[must_use]
pub fn with_accessible(self, accessible: bool) -> Self {
Self { accessible, ..self }
}
#[must_use]
pub fn with_title(self, title: Option<String>) -> Self {
Self { title, ..self }
}
#[must_use]
pub fn with_language(self, language: String) -> Self {
Self { language, ..self }
}
#[must_use]
pub fn with_date(self, date: Option<Date>) -> Self {
Self { date, ..self }
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct Date {
pub year: u16,
pub month: u8,
pub day: u8,
pub hour: u8,
pub minute: u8,
pub second: u8,
}
impl Date {
pub fn from_unix(seconds: u64) -> Self {
let (days, rest) = (seconds / 86_400, seconds % 86_400);
let z = days + 719_468;
let era = z / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + u64::from(month <= 2);
Self {
year: u16::try_from(year).unwrap_or(u16::MAX),
month: month as u8,
day: day as u8,
hour: (rest / 3600) as u8,
minute: (rest % 3600 / 60) as u8,
second: (rest % 60) as u8,
}
}
}
pub fn from_svg(
svg: &str,
fonts: &[&[u8]],
options: &Options,
limits: &crate::Limits,
) -> Result<Vec<u8>, Error> {
let date = options.date.ok_or(Error::NoDate)?;
let costs = if options.embed_text {
PDF
} else {
PDF_OUTLINES
};
let estimate = Measure::of(svg)?.estimate(&costs, 0);
if let Some(limit) = limits.memory_bytes.filter(|&limit| estimate > limit) {
return Err(Error::Refused(crate::limits::Refusal::Memory {
phase: crate::limits::Phase::Render,
limit_bytes: limit,
needed_bytes: Some(estimate),
}));
}
let tree = parse(svg, fonts)?;
let failed = |what: String| Error::RenderFailed { message: what };
let size = Size::from_wh(
tree.size().width() * POINTS_PER_PIXEL,
tree.size().height() * POINTS_PER_PIXEL,
)
.ok_or_else(|| failed("the drawing has no size".to_owned()))?;
let (drawn_title, description) = texts(svg);
let title = options.title.clone().or(drawn_title).unwrap_or_default();
let builder = match (options.accessible, options.compatible) {
(true, _) => ConfigurationBuilder::new()
.with_version(PdfVersion::Pdf17)
.with_archival_validator(Archival::A2_A)
.with_accessibility_validator(Accessibility::UA1),
(false, true) => ConfigurationBuilder::new()
.with_version(PdfVersion::Pdf17)
.with_archival_validator(Archival::A2_U),
(false, false) => ConfigurationBuilder::new()
.with_version(PdfVersion::Pdf20)
.with_archival_validator(Archival::A4),
};
let configuration = builder.finish().map_err(|e| failed(format!("{e:?}")))?;
let mut document = Document::new_with(SerializeSettings {
configuration,
enable_tagging: options.accessible,
..SerializeSettings::default()
});
let created = DateTime::new(date.year)
.month(date.month)
.day(date.day)
.hour(date.hour)
.minute(date.minute)
.second(date.second)
.utc_offset_hour(0);
document.set_metadata(
Metadata::new()
.title(title.clone())
.language(options.language.clone())
.creation_date(created),
);
let mut page = document.start_page_with(PageSettings::new(size));
let mut surface = page.surface();
let settings = SvgSettings {
embed_text: options.embed_text,
..SvgSettings::default()
};
let figure = options
.accessible
.then(|| surface.start_tagged(ContentTag::Other));
let drawn = surface.draw_svg(&tree, size, settings);
if figure.is_some() {
surface.end_tagged();
}
surface.finish();
page.finish();
drawn.ok_or_else(|| failed("the drawing could not be converted".to_owned()))?;
if let Some(figure) = figure {
let mut group = TagGroup::new(Tag::Figure(Some(description.unwrap_or(title.clone()))));
group.push(figure);
let mut tags = TagTree::new();
tags.push(group);
document.set_tag_tree(tags);
let mut outline = Outline::new();
outline.push_child(OutlineNode::new(
title,
XyzDestination::new(0, Point::from_xy(0.0, 0.0)),
));
document.set_outline(outline);
}
document.finish().map_err(|e| failed(format!("{e:?}")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dates_from_unix_seconds() {
let date = |s| {
let d = Date::from_unix(s);
(d.year, d.month, d.day, d.hour, d.minute, d.second)
};
assert_eq!(date(0), (1970, 1, 1, 0, 0, 0));
assert_eq!(date(951_782_400), (2000, 2, 29, 0, 0, 0));
assert_eq!(date(1_791_158_399), (2026, 10, 4, 23, 59, 59));
assert_eq!(date(4_107_542_400), (2100, 3, 1, 0, 0, 0));
}
}