use usvg as style_usvg;
#[cfg(not(target_arch = "wasm32"))]
#[path = "pdf_synthetic_bold.rs"]
mod synthetic_bold;
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub use synthetic_bold::{prepare_svg_with_synthetic_bold, PdfBoldReport};
#[cfg(not(target_arch = "wasm32"))]
#[path = "pdf_synthetic_italic.rs"]
mod synthetic_italic;
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub use synthetic_italic::{parse_svg_with_synthetic_italic, PdfItalicReport};
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum PdfBackend {
#[default]
CompatibilitySvg,
DirectLayer,
}
#[cfg(not(target_arch = "wasm32"))]
impl PdfBackend {
pub fn parse(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"svg" | "compat" | "compat-svg" | "compatibility" => Some(Self::CompatibilitySvg),
"direct" | "direct-layer" | "layer" | "layer-skia" | "skia" => Some(Self::DirectLayer),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::CompatibilitySvg => "svg",
Self::DirectLayer => "direct",
}
}
}
#[cfg(not(target_arch = "wasm32"))]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct DirectPdfExportOptions {
pub font_paths: Vec<std::path::PathBuf>,
pub raster_dpi: f32,
pub title: Option<String>,
pub author: Option<String>,
pub subject: Option<String>,
pub keywords: Option<String>,
}
#[cfg(not(target_arch = "wasm32"))]
impl Default for DirectPdfExportOptions {
fn default() -> Self {
Self {
font_paths: Vec::new(),
raster_dpi: 144.0,
title: None,
author: None,
subject: None,
keywords: None,
}
}
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DirectPdfPreflightLimits {
pub max_issues: usize,
pub max_work_items: usize,
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
impl Default for DirectPdfPreflightLimits {
fn default() -> Self {
Self {
max_issues: 256,
max_work_items: 100_000,
}
}
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectPdfPreflightReason {
EmptyDocument,
InvalidRasterDpi,
InvalidPageWidth,
InvalidPageHeight,
PageWidthTooLarge,
PageHeightTooLarge,
InvalidLayerBounds,
InvalidClipBounds,
InvalidPaintBounds,
InvalidTextClipPath,
UnsupportedLineStyle,
InvalidStrokeWidth,
InvalidArrowSize,
InvalidArrowGeometry,
InvalidConnectorShaft,
UnsupportedArrowTangent,
InvalidRotation,
UnsupportedGradientType,
GradientColorCountOutOfRange,
InvalidGradientStops,
InvalidGradientBounds,
InvalidExpandedGradientStops,
InvalidGradientAxis,
InvalidRadialGradientCenter,
InvalidRadialGradientCircle,
UnsupportedPatternFill,
UnsupportedShapeShadow,
InvalidOpacity,
UnsupportedImageFormat,
InvalidImagePayload,
InvalidBackgroundBorderWidth,
UnsupportedBlackWhiteAdjustment,
UnsupportedImageWatermark,
UnsupportedPattern8x8,
InvalidLineGeometry,
InvalidCornerRadius,
InvalidPathGeometry,
InvalidConnectorEndpoints,
InvalidTextGeometry,
InvalidFootnoteFontSize,
InvalidEquationGeometry,
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DirectPdfPreflightLocation {
pub page_index: Option<usize>,
pub node_index: Option<usize>,
pub op_index: Option<usize>,
pub operation: Option<&'static str>,
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectPdfPreflightIssue {
pub location: DirectPdfPreflightLocation,
pub reason: DirectPdfPreflightReason,
pub message: String,
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectPdfPreflightLimit {
Issues,
WorkItems,
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectPdfPreflightReport {
pub issues: Vec<DirectPdfPreflightIssue>,
pub truncated: bool,
pub limit_reached: Option<DirectPdfPreflightLimit>,
pub work_items_checked: usize,
pub limits: DirectPdfPreflightLimits,
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
impl DirectPdfPreflightReport {
pub fn is_admitted(&self) -> bool {
self.issues.is_empty() && !self.truncated
}
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
pub fn preflight_direct_pdf(
layer_trees: &[crate::paint::PageLayerTree],
options: &DirectPdfExportOptions,
limits: DirectPdfPreflightLimits,
) -> DirectPdfPreflightReport {
direct_pdf_validation::preflight(layer_trees, options, limits)
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
fn validate_direct_pdf_tree(
tree: &crate::paint::PageLayerTree,
page_index: usize,
) -> Result<(), String> {
let mut inspection = direct_pdf_validation::Inspection::first_error();
direct_pdf_validation::validate_tree(tree, page_index, &mut inspection);
match inspection.report.issues.into_iter().next() {
Some(issue) => Err(issue.message),
None => Ok(()),
}
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
mod direct_pdf_validation {
use super::{
DirectPdfExportOptions, DirectPdfPreflightIssue, DirectPdfPreflightLimit,
DirectPdfPreflightLimits, DirectPdfPreflightLocation, DirectPdfPreflightReason as Reason,
DirectPdfPreflightReport,
};
use crate::model::image::ImageEffect;
use crate::paint::{LayerNodeKind, PageLayerTree, PaintOp};
use crate::renderer::render_tree::{BoundingBox, PathNode, ShapeTransform};
use crate::renderer::{
ArrowStyle, GradientFillInfo, LineRenderType, LineStyle, PathCommand, ShapeStyle,
};
pub(super) const CSS_PX_TO_PDF_POINT: f64 = 72.0 / 96.0;
const MAX_PDF_PAGE_DIMENSION_POINTS: f64 = 14_400.0;
pub(super) struct Failure {
reason: Reason,
pub(super) message: String,
}
fn failure(reason: Reason, message: String) -> Failure {
Failure { reason, message }
}
pub(super) struct Inspection {
pub(super) report: DirectPdfPreflightReport,
location: DirectPdfPreflightLocation,
location_start: usize,
first_error: bool,
stopped: bool,
}
impl Inspection {
fn new(limits: DirectPdfPreflightLimits) -> Self {
Self {
report: DirectPdfPreflightReport {
issues: Vec::new(),
truncated: false,
limit_reached: None,
work_items_checked: 0,
limits: DirectPdfPreflightLimits {
max_issues: limits.max_issues.clamp(1, 4096),
max_work_items: limits.max_work_items.clamp(1, 1_000_000),
},
},
location: DirectPdfPreflightLocation::default(),
location_start: 0,
first_error: false,
stopped: false,
}
}
pub(super) fn first_error() -> Self {
let mut result = Self::new(DirectPdfPreflightLimits::default());
result.first_error = true;
result
}
fn locate(&mut self, location: DirectPdfPreflightLocation) {
self.location = location;
self.location_start = self.report.issues.len();
}
fn begin_item(&mut self) -> bool {
if self.stopped {
return false;
}
if !self.first_error
&& self.report.work_items_checked == self.report.limits.max_work_items
{
self.truncate(DirectPdfPreflightLimit::WorkItems);
return false;
}
self.report.work_items_checked = self.report.work_items_checked.saturating_add(1);
true
}
fn truncate(&mut self, limit: DirectPdfPreflightLimit) {
self.report.truncated = true;
self.report.limit_reached = Some(limit);
self.stopped = true;
}
fn reject(&mut self, failure: Failure) {
if self.stopped
|| self.report.issues[self.location_start..]
.iter()
.any(|issue| issue.reason == failure.reason)
{
return;
}
if self.report.issues.len() == self.report.limits.max_issues {
self.truncate(DirectPdfPreflightLimit::Issues);
return;
}
self.report.issues.push(DirectPdfPreflightIssue {
location: self.location,
reason: failure.reason,
message: failure.message,
});
if self.first_error {
self.stopped = true;
}
}
fn check(&mut self, result: Result<(), Failure>) -> bool {
match result {
Ok(()) => true,
Err(error) => {
self.reject(error);
false
}
}
}
}
fn is_valid_skia_scalar(value: f64) -> bool {
value.is_finite() && value.abs() <= f32::MAX as f64
}
fn same_skia_point(left: (f64, f64), right: (f64, f64)) -> bool {
(left.0 as f32, left.1 as f32) == (right.0 as f32, right.1 as f32)
}
fn valid_path_commands(commands: &[PathCommand]) -> bool {
commands.iter().all(|command| match *command {
PathCommand::MoveTo(x, y) | PathCommand::LineTo(x, y) => {
is_valid_skia_scalar(x) && is_valid_skia_scalar(y)
}
PathCommand::CurveTo(x1, y1, x2, y2, x, y) => [x1, y1, x2, y2, x, y]
.iter()
.all(|value| is_valid_skia_scalar(*value)),
PathCommand::ArcTo(rx, ry, rotation, _, _, x, y) => [rx, ry, rotation, x, y]
.iter()
.all(|value| is_valid_skia_scalar(*value)),
PathCommand::ClosePath => true,
})
}
fn validate_bbox(
bbox: BoundingBox,
page_index: usize,
context: &str,
reason: Reason,
) -> Result<(), Failure> {
if [bbox.x, bbox.y, bbox.width, bbox.height]
.iter()
.any(|value| !is_valid_skia_scalar(*value))
|| bbox.width < 0.0
|| bbox.height < 0.0
{
return Err(failure(
reason,
format!(
"direct PDF page {} has invalid {context} bounds",
page_index + 1
),
));
}
Ok(())
}
fn unsupported(page_index: usize, op: &str, reason: Reason, detail: &str) -> Failure {
failure(reason, format!(
"direct PDF page {} cannot replay {op} without visual loss: {detail}; use the svg backend",
page_index + 1
))
}
fn validate_line_style(
style: &LineStyle,
page_index: usize,
op: &str,
inspection: &mut Inspection,
) -> bool {
let mut valid = true;
if style.line_type != LineRenderType::Single || style.shadow.is_some() {
inspection.reject(unsupported(
page_index,
op,
Reason::UnsupportedLineStyle,
"multi-line or shadow style",
));
valid = false;
}
if !is_valid_skia_scalar(style.width) || style.width < 0.0 {
inspection.reject(failure(
Reason::InvalidStrokeWidth,
format!(
"direct PDF page {} has invalid {op} stroke width: {}",
page_index + 1,
style.width
),
));
valid = false;
}
if [
(style.start_arrow, style.start_arrow_size),
(style.end_arrow, style.end_arrow_size),
]
.into_iter()
.any(|(arrow, size)| arrow != ArrowStyle::None && size > 8)
{
inspection.reject(unsupported(
page_index,
op,
Reason::InvalidArrowSize,
"invalid arrow size",
));
valid = false;
}
valid
}
fn has_skia_outline_area(commands: &[PathCommand]) -> bool {
let point = |x: f64, y: f64| (f64::from(x as f32), f64::from(y as f32));
let mut points = Vec::new();
for command in commands {
match *command {
PathCommand::MoveTo(x, y) | PathCommand::LineTo(x, y) => points.push(point(x, y)),
PathCommand::CurveTo(a, b, c, d, e, f) => {
points.extend([point(a, b), point(c, d), point(e, f)]);
}
PathCommand::ClosePath => {}
PathCommand::ArcTo(..) => return false,
}
}
let Some(&(x0, y0)) = points.first() else {
return false;
};
let Some(&(x1, y1)) = points.iter().find(|&&p| p != (x0, y0)) else {
return false;
};
points
.iter()
.any(|&(x, y)| (x1 - x0) * (y - y0) != (y1 - y0) * (x - x0))
}
fn validate_arrow_heads(
heads: &[crate::renderer::arrow::ArrowHead],
style: &LineStyle,
page_index: usize,
op: &str,
) -> Result<(), Failure> {
let requested = usize::from(style.start_arrow != ArrowStyle::None)
+ usize::from(style.end_arrow != ArrowStyle::None);
if heads.len() != requested
|| heads.iter().any(|head| {
!valid_path_commands(&head.commands) || !has_skia_outline_area(&head.commands)
})
{
return Err(unsupported(
page_index,
op,
Reason::InvalidArrowGeometry,
"invalid arrow geometry",
));
}
Ok(())
}
fn validate_connector_shaft(
path: &PathNode,
style: &LineStyle,
page_index: usize,
) -> Result<(), Failure> {
let invalid = || {
unsupported(
page_index,
"connector",
Reason::InvalidConnectorShaft,
"invalid connector shaft",
)
};
let Some((PathCommand::MoveTo(x1, y1), segments)) = path.commands.split_first() else {
return Err(invalid());
};
if segments.is_empty()
|| segments.iter().any(|command| {
!matches!(command, PathCommand::LineTo(..) | PathCommand::CurveTo(..))
})
{
return Err(invalid());
}
let endpoint = |command: &PathCommand| match *command {
PathCommand::LineTo(x, y) | PathCommand::CurveTo(_, _, _, _, x, y) => (x, y),
_ => unreachable!("validated open connector segment"),
};
let (x2, y2) = endpoint(segments.last().expect("nonempty connector"));
if path.connector_endpoints != Some((*x1, *y1, x2, y2)) {
return Err(invalid());
}
let start_control = match segments[0] {
PathCommand::LineTo(x, y) | PathCommand::CurveTo(x, y, ..) => (x, y),
_ => unreachable!("validated open connector segment"),
};
let end_control = match *segments.last().expect("nonempty connector") {
PathCommand::CurveTo(_, _, x, y, _, _) => (x, y),
PathCommand::LineTo(..) => {
if segments.len() == 1 {
(*x1, *y1)
} else {
endpoint(&segments[segments.len() - 2])
}
}
_ => unreachable!("validated open connector segment"),
};
if (style.start_arrow != ArrowStyle::None && same_skia_point(start_control, (*x1, *y1)))
|| (style.end_arrow != ArrowStyle::None && same_skia_point(end_control, (x2, y2)))
{
return Err(unsupported(
page_index,
"connector",
Reason::UnsupportedArrowTangent,
"unsupported arrow tangent",
));
}
Ok(())
}
fn validate_transform(
transform: ShapeTransform,
page_index: usize,
op: &str,
) -> Result<(), Failure> {
if !is_valid_skia_scalar(transform.rotation) {
return Err(failure(
Reason::InvalidRotation,
format!(
"direct PDF page {} has invalid {op} rotation",
page_index + 1
),
));
}
Ok(())
}
fn validate_gradient(
gradient: &GradientFillInfo,
bbox: BoundingBox,
page_index: usize,
op: &str,
inspection: &mut Inspection,
) {
if inspection.stopped {
return;
}
let supported_type = matches!(gradient.gradient_type, 1 | 2);
if !supported_type {
inspection.reject(unsupported(
page_index,
op,
Reason::UnsupportedGradientType,
"non-linear gradient fill",
));
}
let valid_center = gradient.gradient_type != 2
|| ((0..=100).contains(&gradient.center_x) && (0..=100).contains(&gradient.center_y));
if !valid_center {
inspection.reject(unsupported(
page_index,
op,
Reason::InvalidRadialGradientCenter,
"radial gradient center outside 0..=100 percent",
));
}
let valid_count = (2..=4096).contains(&gradient.colors.len());
if !valid_count {
inspection.reject(unsupported(
page_index,
op,
Reason::GradientColorCountOutOfRange,
"gradient color count outside 2..=4096",
));
}
let valid_stops = gradient.positions.is_empty()
|| (gradient.positions.len() == gradient.colors.len()
&& gradient
.positions
.iter()
.all(|position| position.is_finite() && (0.0..=1.0).contains(position))
&& gradient.positions.windows(2).all(|pair| pair[0] <= pair[1]));
if !valid_stops {
inspection.reject(unsupported(
page_index,
op,
Reason::InvalidGradientStops,
"invalid gradient stop positions",
));
}
let bounds = skia_safe::Rect::from_xywh(
bbox.x as f32,
bbox.y as f32,
bbox.width as f32,
bbox.height as f32,
);
let valid_bounds = bounds.is_finite()
&& !bounds.is_empty()
&& bounds.width().is_finite()
&& bounds.height().is_finite();
if !valid_bounds {
inspection.reject(unsupported(
page_index,
op,
Reason::InvalidGradientBounds,
"invalid gradient replay bounds",
));
}
if inspection.stopped
|| !supported_type
|| !valid_center
|| !valid_count
|| !valid_stops
|| !valid_bounds
{
return;
}
let (colors, positions) = crate::renderer::linear_gradient_color_stops(
gradient,
bbox.x,
bbox.y,
bbox.width,
bbox.height,
);
if colors.len() < 2
|| colors.len() > 8192
|| colors.len() != positions.len()
|| positions
.iter()
.any(|position| !position.is_finite() || !(0.0..=1.0).contains(position))
|| positions.windows(2).any(|pair| pair[0] > pair[1])
{
inspection.reject(unsupported(
page_index,
op,
Reason::InvalidExpandedGradientStops,
"invalid expanded gradient stop positions",
));
}
if gradient.gradient_type == 2 {
if positions
.windows(2)
.any(|pair| pair[0] < pair[1] && pair[0] as f32 == pair[1] as f32)
{
inspection.reject(unsupported(
page_index,
op,
Reason::InvalidExpandedGradientStops,
"collapsed radial gradient stop positions",
));
}
inspection.check(validate_radial_circle(gradient, bbox, page_index, op));
return;
}
let (x1, y1, x2, y2) = crate::renderer::linear_gradient_axis(
gradient.angle,
bbox.x,
bbox.y,
bbox.width,
bbox.height,
);
let dx = x2 as f32 - x1 as f32;
let dy = y2 as f32 - y1 as f32;
let length_squared = dx * dx + dy * dy;
if [x1, y1, x2, y2]
.into_iter()
.any(|value| !is_valid_skia_scalar(value))
|| !length_squared.is_finite()
|| length_squared < 1.0
{
inspection.reject(unsupported(
page_index,
op,
Reason::InvalidGradientAxis,
"invalid gradient axis",
));
}
}
fn validate_radial_circle(
gradient: &GradientFillInfo,
bbox: BoundingBox,
page_index: usize,
op: &str,
) -> Result<(), Failure> {
let invalid = || {
unsupported(
page_index,
op,
Reason::InvalidRadialGradientCircle,
"invalid radial gradient circle",
)
};
let (cx, cy, radius) = crate::renderer::gradient_geometry::radial_circle(
(bbox.x, bbox.y, bbox.width, bbox.height),
gradient.center_x,
gradient.center_y,
)
.ok_or_else(invalid)?;
if [cx, cy, radius]
.into_iter()
.any(|value| !is_valid_skia_scalar(value))
{
return Err(invalid());
}
let (cx, cy, radius) = (cx as f32, cy as f32, radius as f32);
let squared_radius = radius * radius;
if !squared_radius.is_finite()
|| squared_radius < 1.0
|| ![cx - radius, cx + radius, cy - radius, cy + radius]
.into_iter()
.all(f32::is_finite)
|| cx - radius >= cx
|| cx + radius <= cx
|| cy - radius >= cy
|| cy + radius <= cy
{
return Err(invalid());
}
Ok(())
}
fn validate_shape_style(
style: &ShapeStyle,
gradient: Option<&GradientFillInfo>,
bbox: BoundingBox,
page_index: usize,
op: &str,
inspection: &mut Inspection,
) {
if let Some(gradient) = gradient {
validate_gradient(gradient, bbox, page_index, op, inspection);
}
if style.pattern.is_some() {
inspection.reject(unsupported(
page_index,
op,
Reason::UnsupportedPatternFill,
"pattern fill",
));
}
if style.shadow.is_some() {
inspection.reject(unsupported(
page_index,
op,
Reason::UnsupportedShapeShadow,
"shape shadow",
));
}
if !is_valid_skia_scalar(style.opacity) || !(0.0..=1.0).contains(&style.opacity) {
inspection.reject(failure(
Reason::InvalidOpacity,
format!(
"direct PDF page {} has invalid {op} opacity: {}",
page_index + 1,
style.opacity
),
));
}
if !is_valid_skia_scalar(style.stroke_width) || style.stroke_width < 0.0 {
inspection.reject(failure(
Reason::InvalidStrokeWidth,
format!(
"direct PDF page {} has invalid {op} stroke width: {}",
page_index + 1,
style.stroke_width
),
));
}
}
fn validate_image_payload(
data: &[u8],
page_index: usize,
context: &str,
decode: bool,
) -> Result<(), Failure> {
let format = match crate::renderer::image_resolver::detect_image_mime_type(data) {
"image/png" => image::ImageFormat::Png,
"image/jpeg" => image::ImageFormat::Jpeg,
"image/gif" => image::ImageFormat::Gif,
"image/bmp" => image::ImageFormat::Bmp,
"image/tiff" => image::ImageFormat::Tiff,
format => {
return Err(failure(Reason::UnsupportedImageFormat, format!(
"direct PDF page {} does not support {context} payload format {format}; use the svg backend",
page_index + 1
)));
}
};
if !decode {
return Ok(());
}
image::load_from_memory_with_format(data, format)
.map(|_| ())
.map_err(|error| {
failure(
Reason::InvalidImagePayload,
format!(
"direct PDF page {} cannot decode {context} payload: {error}",
page_index + 1
),
)
})
}
fn op_name(op: &PaintOp) -> &'static str {
match op {
PaintOp::PageBackground { .. } => "pageBackground",
PaintOp::TextRun { .. } => "textRun",
PaintOp::GlyphRun { .. } => "glyphRun",
PaintOp::GlyphOutline { .. } => "glyphOutline",
PaintOp::CharOverlap { .. } => "charOverlap",
PaintOp::TextControlMark { .. } => "textControlMark",
PaintOp::TabLeader { .. } => "tabLeader",
PaintOp::TextDecoration { .. } => "textDecoration",
PaintOp::ControlLabel { .. } => "controlLabel",
PaintOp::FootnoteMarker { .. } => "footnoteMarker",
PaintOp::Line { .. } => "line",
PaintOp::Rectangle { .. } => "rectangle",
PaintOp::Ellipse { .. } => "ellipse",
PaintOp::Path { .. } => "path",
PaintOp::Image { .. } => "image",
PaintOp::Equation { .. } => "equation",
PaintOp::FormObject { .. } => "formObject",
PaintOp::Placeholder { .. } => "placeholder",
PaintOp::RawSvg { .. } => "rawSvg",
}
}
fn validate_op(op: &PaintOp, page_index: usize, inspection: &mut Inspection) {
inspection.check(validate_bbox(
op.bounds(),
page_index,
"paint operation",
Reason::InvalidPaintBounds,
));
match op {
PaintOp::PageBackground { bbox, background } => {
if let Some(gradient) = background.gradient.as_deref() {
validate_gradient(gradient, *bbox, page_index, "page background", inspection);
}
if !is_valid_skia_scalar(background.border_width) || background.border_width < 0.0 {
inspection.reject(failure(
Reason::InvalidBackgroundBorderWidth,
format!(
"direct PDF page {} has invalid page background border width",
page_index + 1
),
));
}
if inspection.stopped {
return;
}
if let Some(image) = &background.image {
inspection.check(validate_image_payload(
&image.data,
page_index,
"page background image",
inspection.first_error,
));
if image.effect == ImageEffect::BlackWhite
&& (image.brightness != 0 || image.contrast != 0)
{
inspection.reject(unsupported(
page_index,
"page background image",
Reason::UnsupportedBlackWhiteAdjustment,
"unbaked BlackWhite brightness or contrast",
));
}
if image.is_real_picture_watermark_tone_preset() {
inspection.reject(unsupported(
page_index,
"page background image",
Reason::UnsupportedImageWatermark,
"unbaked RealPic watermark tone",
));
}
if image.effect == ImageEffect::Pattern8x8 {
inspection.reject(unsupported(
page_index,
"page background image",
Reason::UnsupportedPattern8x8,
"Pattern8x8 effect",
));
}
}
}
PaintOp::Line { line, .. } => {
inspection.check(validate_transform(line.transform, page_index, "line"));
let valid_style = validate_line_style(&line.style, page_index, "line", inspection);
let valid_geometry = [line.x1, line.y1, line.x2, line.y2]
.iter()
.all(|value| is_valid_skia_scalar(*value))
&& !((line.style.start_arrow != ArrowStyle::None
|| line.style.end_arrow != ArrowStyle::None)
&& same_skia_point((line.x1, line.y1), (line.x2, line.y2)));
if !valid_geometry {
inspection.reject(failure(
Reason::InvalidLineGeometry,
format!(
"direct PDF page {} has invalid line geometry",
page_index + 1
),
));
}
if valid_style && valid_geometry && !inspection.stopped {
inspection.check(validate_arrow_heads(
&crate::renderer::arrow::line_heads(
(line.x1, line.y1, line.x2, line.y2),
&line.style,
),
&line.style,
page_index,
"line",
));
}
}
PaintOp::Rectangle { bbox, rect } => {
inspection.check(validate_transform(rect.transform, page_index, "rectangle"));
if !is_valid_skia_scalar(rect.corner_radius) || rect.corner_radius < 0.0 {
inspection.reject(failure(
Reason::InvalidCornerRadius,
format!(
"direct PDF page {} has invalid rectangle corner radius",
page_index + 1
),
));
}
validate_shape_style(
&rect.style,
rect.gradient.as_deref(),
*bbox,
page_index,
"rectangle",
inspection,
);
}
PaintOp::Ellipse { bbox, ellipse } => {
inspection.check(validate_transform(ellipse.transform, page_index, "ellipse"));
validate_shape_style(
&ellipse.style,
ellipse.gradient.as_deref(),
*bbox,
page_index,
"ellipse",
inspection,
);
}
PaintOp::Path { bbox, path } => {
inspection.check(validate_transform(path.transform, page_index, "path"));
validate_shape_style(
&path.style,
path.gradient.as_deref(),
*bbox,
page_index,
"path",
inspection,
);
let valid_geometry = valid_path_commands(&path.commands);
if !valid_geometry {
inspection.reject(failure(
Reason::InvalidPathGeometry,
format!(
"direct PDF page {} has invalid path geometry",
page_index + 1
),
));
}
let valid_endpoints = path.connector_endpoints.is_none_or(|(x1, y1, x2, y2)| {
[x1, y1, x2, y2].into_iter().all(is_valid_skia_scalar)
});
if !valid_endpoints {
inspection.reject(failure(
Reason::InvalidConnectorEndpoints,
format!(
"direct PDF page {} has invalid connector endpoints",
page_index + 1
),
));
}
if let Some(style) = &path.line_style {
let valid_style =
validate_line_style(style, page_index, "connector", inspection);
let has_arrows = style.start_arrow != ArrowStyle::None
|| style.end_arrow != ArrowStyle::None;
let valid_tangent = !has_arrows
|| !path.commands.iter().any(|command| {
matches!(command, PathCommand::ArcTo(..) | PathCommand::ClosePath)
});
if !valid_tangent {
inspection.reject(unsupported(
page_index,
"connector",
Reason::UnsupportedArrowTangent,
"unsupported arrow tangent",
));
}
if valid_style
&& valid_geometry
&& valid_endpoints
&& valid_tangent
&& !inspection.stopped
{
let valid_shaft = !has_arrows
|| inspection.check(validate_connector_shaft(path, style, page_index));
if valid_shaft && !inspection.stopped {
inspection.check(validate_arrow_heads(
&crate::renderer::arrow::connector_heads(path),
style,
page_index,
"connector",
));
}
}
}
}
PaintOp::Image {
image, resolved, ..
} => {
inspection.check(validate_transform(image.transform, page_index, "image"));
if inspection.stopped {
return;
}
if let Some(data) = resolved
.as_deref()
.map(|payload| &payload.data[..])
.or(image.data.as_deref())
{
inspection.check(validate_image_payload(
data,
page_index,
"image",
inspection.first_error,
));
}
let baked = resolved
.as_deref()
.is_some_and(|payload| payload.suppress_effects);
if !baked
&& image.effect == ImageEffect::BlackWhite
&& (image.brightness != 0 || image.contrast != 0)
{
inspection.reject(unsupported(
page_index,
"image",
Reason::UnsupportedBlackWhiteAdjustment,
"unbaked BlackWhite brightness or contrast",
));
}
if !baked && image.is_watermark() {
inspection.reject(unsupported(
page_index,
"image",
Reason::UnsupportedImageWatermark,
"unbaked image watermark tone or opacity",
));
}
if !baked && image.effect == ImageEffect::Pattern8x8 {
inspection.reject(unsupported(
page_index,
"image",
Reason::UnsupportedPattern8x8,
"Pattern8x8 effect",
));
}
if !is_valid_skia_scalar(image.opacity) || !(0.0..=1.0).contains(&image.opacity) {
inspection.reject(failure(
Reason::InvalidOpacity,
format!(
"direct PDF page {} has invalid image opacity: {}",
page_index + 1,
image.opacity
),
));
}
}
PaintOp::TextRun { run, .. } => {
if [
run.baseline,
run.rotation,
run.style.font_size,
run.style.letter_spacing,
run.style.ratio,
]
.iter()
.any(|value| !is_valid_skia_scalar(*value))
{
inspection.reject(failure(
Reason::InvalidTextGeometry,
format!(
"direct PDF page {} has invalid text geometry",
page_index + 1
),
));
}
}
PaintOp::FootnoteMarker { marker, .. } => {
let style = marker.paint_style();
if !is_valid_skia_scalar(marker.base_font_size)
|| !is_valid_skia_scalar(style.font_size)
{
inspection.reject(failure(
Reason::InvalidFootnoteFontSize,
format!(
"direct PDF page {} has invalid footnote marker font size",
page_index + 1
),
));
}
if let Some(run) = marker.source_run.as_deref() {
if [run.style.ratio, run.style.letter_spacing, run.baseline]
.into_iter()
.any(|value| !is_valid_skia_scalar(value))
|| run.validated_layout_positions_for(&marker.text).is_none()
{
inspection.reject(failure(
Reason::InvalidTextGeometry,
format!(
"direct PDF page {} has invalid footnote source geometry",
page_index + 1
),
));
}
}
}
PaintOp::Equation { equation, .. } => {
if !is_valid_skia_scalar(equation.font_size)
|| !is_valid_skia_scalar(equation.layout_box.width)
|| !is_valid_skia_scalar(equation.layout_box.height)
{
inspection.reject(failure(
Reason::InvalidEquationGeometry,
format!(
"direct PDF page {} has invalid equation geometry",
page_index + 1
),
));
}
}
PaintOp::GlyphRun { .. }
| PaintOp::GlyphOutline { .. }
| PaintOp::CharOverlap { .. }
| PaintOp::TextControlMark { .. }
| PaintOp::TabLeader { .. }
| PaintOp::TextDecoration { .. }
| PaintOp::ControlLabel { .. }
| PaintOp::FormObject { .. }
| PaintOp::Placeholder { .. }
| PaintOp::RawSvg { .. } => {}
}
}
pub(super) fn validate_tree(
tree: &PageLayerTree,
page_index: usize,
inspection: &mut Inspection,
) {
let mut pending = vec![std::slice::from_ref(&tree.root).iter()];
let mut node_index = 0;
let mut op_index = 0;
while let Some(siblings) = pending.last_mut() {
let Some(node) = siblings.next() else {
pending.pop();
continue;
};
if !inspection.begin_item() {
break;
}
let location = DirectPdfPreflightLocation {
page_index: Some(page_index),
node_index: Some(node_index),
..Default::default()
};
node_index += 1;
inspection.locate(location);
inspection.check(validate_bbox(
node.bounds,
page_index,
"layer",
Reason::InvalidLayerBounds,
));
if inspection.stopped {
break;
}
match &node.kind {
LayerNodeKind::Group { children, .. } => pending.push(children.iter()),
LayerNodeKind::ClipPath { paths, child } => {
if !crate::model::text_clip::valid(paths) {
inspection.reject(failure(
Reason::InvalidTextClipPath,
"invalid text clip path".into(),
));
}
if !inspection.stopped {
pending.push(std::slice::from_ref(child.as_ref()).iter());
}
}
LayerNodeKind::ClipRect { clip, child, .. } => {
inspection.check(validate_bbox(
*clip,
page_index,
"clip",
Reason::InvalidClipBounds,
));
if !inspection.stopped {
pending.push(std::slice::from_ref(child.as_ref()).iter());
}
}
LayerNodeKind::Leaf { ops } => {
for op in ops {
if !inspection.begin_item() {
break;
}
inspection.locate(DirectPdfPreflightLocation {
op_index: Some(op_index),
operation: Some(op_name(op)),
..location
});
op_index += 1;
validate_op(op, page_index, inspection);
}
}
}
}
}
pub(super) fn page_dimension(value: f64, width: bool) -> Result<f32, Failure> {
let label = if width { "width" } else { "height" };
let points = value * CSS_PX_TO_PDF_POINT;
let skia_points = points as f32;
if !points.is_finite() || points <= 0.0 || skia_points <= 0.0 {
return Err(failure(
if width {
Reason::InvalidPageWidth
} else {
Reason::InvalidPageHeight
},
format!("invalid direct PDF page {label}: {value}"),
));
}
if points > MAX_PDF_PAGE_DIMENSION_POINTS {
return Err(failure(if width { Reason::PageWidthTooLarge } else { Reason::PageHeightTooLarge },
format!("direct PDF page {label} exceeds {MAX_PDF_PAGE_DIMENSION_POINTS} points: {points}")));
}
Ok(skia_points)
}
pub(super) fn preflight(
trees: &[PageLayerTree],
options: &DirectPdfExportOptions,
limits: DirectPdfPreflightLimits,
) -> DirectPdfPreflightReport {
let mut inspection = Inspection::new(limits);
if trees.is_empty() {
inspection.reject(failure(
Reason::EmptyDocument,
"direct PDF export requires at least one page".into(),
));
}
if !options.raster_dpi.is_finite() || options.raster_dpi <= 0.0 {
inspection.reject(failure(
Reason::InvalidRasterDpi,
format!("invalid direct PDF raster dpi: {}", options.raster_dpi),
));
}
for (page_index, tree) in trees.iter().enumerate() {
if !inspection.begin_item() {
break;
}
validate_tree(tree, page_index, &mut inspection);
if inspection.stopped {
break;
}
inspection.locate(DirectPdfPreflightLocation {
page_index: Some(page_index),
..Default::default()
});
inspection.check(page_dimension(tree.page_width, true).map(|_| ()));
inspection.check(page_dimension(tree.page_height, false).map(|_| ()));
}
inspection.report
}
}
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PdfExportOptions {
pub fallback_serif: String,
pub fallback_sans: String,
pub fallback_mono: String,
pub equation_font: Option<String>,
pub font_paths: Vec<std::path::PathBuf>,
pub embed_text: bool,
}
#[cfg(not(target_arch = "wasm32"))]
impl Default for PdfExportOptions {
fn default() -> Self {
Self {
fallback_serif: default_serif_family().to_string(),
fallback_sans: default_sans_family().to_string(),
fallback_mono: default_mono_family().to_string(),
equation_font: None,
font_paths: Vec::new(),
embed_text: true,
}
}
}
#[cfg(all(not(target_arch = "wasm32"), target_os = "windows"))]
fn default_serif_family() -> &'static str {
"바탕"
}
#[cfg(all(not(target_arch = "wasm32"), target_os = "windows"))]
fn default_sans_family() -> &'static str {
"맑은 고딕"
}
#[cfg(all(not(target_arch = "wasm32"), target_os = "windows"))]
fn default_mono_family() -> &'static str {
"D2Coding"
}
#[cfg(all(not(target_arch = "wasm32"), target_os = "linux"))]
fn default_serif_family() -> &'static str {
"Noto Serif CJK KR"
}
#[cfg(all(not(target_arch = "wasm32"), target_os = "linux"))]
fn default_sans_family() -> &'static str {
"Noto Sans CJK KR"
}
#[cfg(all(not(target_arch = "wasm32"), target_os = "linux"))]
fn default_mono_family() -> &'static str {
"Noto Sans Mono CJK KR"
}
#[cfg(all(not(target_arch = "wasm32"), target_os = "macos"))]
fn default_serif_family() -> &'static str {
"AppleMyungjo"
}
#[cfg(all(not(target_arch = "wasm32"), target_os = "macos"))]
fn default_sans_family() -> &'static str {
"Apple SD Gothic Neo"
}
#[cfg(all(not(target_arch = "wasm32"), target_os = "macos"))]
fn default_mono_family() -> &'static str {
"Menlo"
}
#[cfg(all(
not(target_arch = "wasm32"),
not(any(target_os = "windows", target_os = "linux", target_os = "macos"))
))]
fn default_serif_family() -> &'static str {
"Noto Serif CJK KR"
}
#[cfg(all(
not(target_arch = "wasm32"),
not(any(target_os = "windows", target_os = "linux", target_os = "macos"))
))]
fn default_sans_family() -> &'static str {
"Noto Sans CJK KR"
}
#[cfg(all(
not(target_arch = "wasm32"),
not(any(target_os = "windows", target_os = "linux", target_os = "macos"))
))]
fn default_mono_family() -> &'static str {
"Noto Sans Mono CJK KR"
}
#[cfg(not(target_arch = "wasm32"))]
fn create_fontdb(options: &PdfExportOptions) -> usvg::fontdb::Database {
let mut fontdb = usvg::fontdb::Database::new();
fontdb.load_system_fonts();
crate::renderer::font_paths::load_into_fontdb(&mut fontdb, &options.font_paths);
fontdb.set_serif_family(options.fallback_serif.as_str());
fontdb.set_sans_serif_family(options.fallback_sans.as_str());
fontdb.set_monospace_family(options.fallback_mono.as_str());
warn_missing_family(
&fontdb,
"serif",
&options.fallback_serif,
"--fallback-serif",
);
warn_missing_family(
&fontdb,
"sans-serif",
&options.fallback_sans,
"--fallback-sans",
);
warn_missing_family(
&fontdb,
"monospace",
&options.fallback_mono,
"--fallback-mono",
);
if let Some(equation_font) = options.equation_font.as_deref() {
let family = first_font_family(equation_font);
if !family.is_empty() {
warn_missing_family(&fontdb, "equation", &family, "--equation-font");
}
}
fontdb
}
#[cfg(not(target_arch = "wasm32"))]
const PDF_FONT_FALLBACK_INDEX_MAX_CHARS: usize = 4_096;
#[cfg(not(target_arch = "wasm32"))]
const PDF_FONT_FALLBACK_INDEX_MAX_FACE_SLOTS: usize = 262_144;
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug)]
struct PdfFontFallbackIndex {
database: Option<(std::sync::Weak<usvg::fontdb::Database>, usize)>,
coverage_by_char: std::collections::HashMap<char, Vec<Option<bool>>>,
face_slot_count: usize,
disabled: bool,
}
#[cfg(not(target_arch = "wasm32"))]
impl PdfFontFallbackIndex {
fn new() -> Self {
Self {
database: None,
coverage_by_char: std::collections::HashMap::new(),
face_slot_count: 0,
disabled: false,
}
}
fn disable(&mut self) {
self.coverage_by_char.clear();
self.face_slot_count = 0;
self.disabled = true;
}
fn select(
&mut self,
c: char,
used_fonts: &[usvg::fontdb::ID],
fontdb: &std::sync::Arc<usvg::fontdb::Database>,
max_chars: usize,
max_face_slots: usize,
) -> PdfFontFallbackLookup {
if self.disabled {
return PdfFontFallbackLookup::Default;
}
let database = std::sync::Arc::downgrade(fontdb);
let face_count = fontdb.len();
match self.database.as_ref() {
None => self.database = Some((database, face_count)),
Some((cached, cached_face_count))
if *cached_face_count != face_count
|| !std::sync::Weak::ptr_eq(cached, &database) =>
{
self.disable();
return PdfFontFallbackLookup::Default;
}
Some(_) => {}
}
if !self.coverage_by_char.contains_key(&c) {
if self.coverage_by_char.len() >= max_chars {
self.disable();
return PdfFontFallbackLookup::Default;
}
self.coverage_by_char.insert(c, Vec::new());
}
let base_face = fontdb.face(used_fonts[0]);
for (face_index, face) in fontdb.faces().enumerate() {
if used_fonts.contains(&face.id) {
continue;
}
let Some(base_face) = base_face else {
return PdfFontFallbackLookup::Cached(None);
};
if base_face.style != face.style
&& base_face.weight != face.weight
&& base_face.stretch != face.stretch
{
continue;
}
let cached = self
.coverage_by_char
.get(&c)
.and_then(|coverage| coverage.get(face_index))
.copied()
.flatten();
let supports_char = match cached {
Some(supports_char) => supports_char,
None => {
let Some(required_len) = face_index.checked_add(1) else {
self.disable();
return PdfFontFallbackLookup::Default;
};
let current_len = self
.coverage_by_char
.get(&c)
.map_or(0, |coverage| coverage.len());
let additional_slots = required_len.saturating_sub(current_len);
let Some(next_face_slot_count) =
self.face_slot_count.checked_add(additional_slots)
else {
self.disable();
return PdfFontFallbackLookup::Default;
};
if next_face_slot_count > max_face_slots {
self.disable();
return PdfFontFallbackLookup::Default;
}
let supports_char = pdf_font_face_has_char(fontdb, face.id, c);
let coverage = self
.coverage_by_char
.get_mut(&c)
.expect("fallback coverage was inserted above");
if coverage.len() < required_len {
coverage.resize(required_len, None);
self.face_slot_count = next_face_slot_count;
}
coverage[face_index] = Some(supports_char);
supports_char
}
};
if supports_char {
return PdfFontFallbackLookup::Cached(Some(face.id));
}
}
PdfFontFallbackLookup::Cached(None)
}
}
#[cfg(not(target_arch = "wasm32"))]
enum PdfFontFallbackLookup {
Cached(Option<usvg::fontdb::ID>),
Default,
}
#[cfg(not(target_arch = "wasm32"))]
fn pdf_font_face_has_char(fontdb: &usvg::fontdb::Database, id: usvg::fontdb::ID, c: char) -> bool {
fontdb
.with_face_data(id, |font_data, face_index| {
ttf_parser::Face::parse(font_data, face_index)
.ok()
.and_then(|face| face.glyph_index(c))
.is_some()
})
.unwrap_or(false)
}
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn pdf_font_fallback_selector_with_limits(
max_chars: usize,
max_face_slots: usize,
) -> usvg::FallbackSelectionFn<'static> {
let index = std::sync::Mutex::new(PdfFontFallbackIndex::new());
let default_selector = usvg::FontResolver::default_fallback_selector();
Box::new(move |c, used_fonts, fontdb| {
let lookup = match index.lock() {
Ok(mut index) => index.select(c, used_fonts, fontdb, max_chars, max_face_slots),
Err(_) => PdfFontFallbackLookup::Default,
};
match lookup {
PdfFontFallbackLookup::Cached(id) => id,
PdfFontFallbackLookup::Default => default_selector(c, used_fonts, fontdb),
}
})
}
#[cfg(not(target_arch = "wasm32"))]
fn warn_missing_family(
fontdb: &usvg::fontdb::Database,
kind: &str,
family: &str,
option_name: &str,
) {
if !font_family_exists(fontdb, family) {
eprintln!(
"WARN: fallback {kind} font '{family}' not found.\n 한글 또는 수식이 빈칸으로 렌더링될 수 있습니다.\n {option_name} \"<family>\" 로 설치된 폰트를 지정하세요."
);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn font_family_exists(fontdb: &usvg::fontdb::Database, family: &str) -> bool {
fontdb.faces().any(|face| {
face.families
.iter()
.any(|(name, _)| name == family || name.eq_ignore_ascii_case(family))
})
}
#[cfg(not(target_arch = "wasm32"))]
fn add_font_fallbacks(svg: &str, options: &PdfExportOptions) -> String {
let serif = css_family_for_attr(&options.fallback_serif);
let sans = css_family_for_attr(&options.fallback_sans);
svg.replace(
"font-family=\"휴먼명조\"",
&format!("font-family=\"휴먼명조, {serif}, serif\""),
)
.replace(
"font-family=\"HCI Poppy\"",
&format!("font-family=\"HCI Poppy, {sans}, sans-serif\""),
)
}
#[cfg(not(target_arch = "wasm32"))]
fn drop_extralight_from_bold_svg_runs(svg: &str) -> String {
let mut out = String::with_capacity(svg.len());
let mut rest = svg;
while let Some(rel) = rest.find('<') {
out.push_str(&rest[..rel]);
rest = &rest[rel..];
let end = rest.find('>').map(|i| i + 1).unwrap_or(rest.len());
let tag = &rest[..end];
rest = &rest[end..];
if svg_tag_is_text_run(tag) && svg_tag_is_bold_weight(tag) {
out.push_str(&crate::renderer::drop_noto_sans_kr_extralight(tag));
} else {
out.push_str(tag);
}
}
out.push_str(rest);
out
}
#[cfg(not(target_arch = "wasm32"))]
fn svg_tag_is_text_run(tag: &str) -> bool {
let Some(rest) = tag.strip_prefix('<') else {
return false;
};
let name = rest
.split(|c: char| c.is_ascii_whitespace() || c == '>' || c == '/')
.next()
.unwrap_or("");
name.eq_ignore_ascii_case("text") || name.eq_ignore_ascii_case("tspan")
}
#[cfg(not(target_arch = "wasm32"))]
fn svg_tag_is_bold_weight(tag: &str) -> bool {
let lower = tag.to_ascii_lowercase();
if lower.contains("font-weight=\"bold\"") || lower.contains("font-weight='bold'") {
return true;
}
for weight in ["600", "700", "800", "900"] {
if lower.contains(&format!("font-weight=\"{weight}\""))
|| lower.contains(&format!("font-weight='{weight}'"))
{
return true;
}
}
false
}
#[cfg(not(target_arch = "wasm32"))]
pub fn apply_pdf_font_options(svg: &str, options: &PdfExportOptions) -> String {
let svg = add_font_fallbacks(svg, options);
let svg = drop_extralight_from_bold_svg_runs(&svg);
if let Some(equation_font) = options.equation_font.as_deref() {
let attr = format!(
"font-family=\"{}\"",
escape_xml_attr(&equation_font_chain(equation_font))
);
svg.replace(
crate::renderer::equation::svg_render::DEFAULT_EQUATION_FONT_FAMILY_ATTR,
&attr,
)
} else {
svg
}
}
#[cfg(not(target_arch = "wasm32"))]
fn equation_font_chain(equation_font: &str) -> String {
if equation_font.contains(',') {
return equation_font.trim().to_string();
}
let first = css_family_for_attr(equation_font);
let default =
"'Latin Modern Math', 'STIX Two Text', 'STIX Two Math', 'Times New Roman', 'Times', serif";
if first == "'Latin Modern Math'" {
default.to_string()
} else {
format!("{first}, {default}")
}
}
#[cfg(not(target_arch = "wasm32"))]
fn first_font_family(value: &str) -> String {
value
.split(',')
.next()
.unwrap_or_default()
.trim()
.trim_matches('"')
.trim_matches('\'')
.to_string()
}
#[cfg(not(target_arch = "wasm32"))]
fn css_family_for_attr(family: &str) -> String {
let family = family.trim();
if family.eq_ignore_ascii_case("serif")
|| family.eq_ignore_ascii_case("sans-serif")
|| family.eq_ignore_ascii_case("monospace")
{
return family.to_string();
}
let escaped = escape_xml_attr(family);
format!("'{escaped}'")
}
#[cfg(not(target_arch = "wasm32"))]
fn escape_xml_attr(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'&' => escaped.push_str("&"),
'<' => escaped.push_str("<"),
'>' => escaped.push_str(">"),
'"' => escaped.push_str("""),
'\'' => escaped.push_str("'"),
'\u{09}' | '\u{0A}' | '\u{0D}' => escaped.push(ch),
'\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}' => {
escaped.push(ch)
}
_ => {} }
}
escaped
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn remap_pua_in_tounicode(pdf: &mut [u8]) {
const BEGIN: &[u8] = b"beginbfchar";
const END: &[u8] = b"endbfchar";
let mut cursor = 0usize;
while let Some(rel) = find_bytes(&pdf[cursor..], BEGIN) {
let start = cursor + rel + BEGIN.len();
let Some(rel_end) = find_bytes(&pdf[start..], END) else {
break;
};
let end = start + rel_end;
remap_bfchar_block(&mut pdf[start..end]);
cursor = end + END.len();
}
}
#[cfg(not(target_arch = "wasm32"))]
fn find_bytes(hay: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() || hay.len() < needle.len() {
return None;
}
hay.windows(needle.len()).position(|w| w == needle)
}
#[cfg(not(target_arch = "wasm32"))]
fn remap_bfchar_block(block: &mut [u8]) {
let mut spans: Vec<(usize, usize)> = Vec::new();
let mut i = 0usize;
while i < block.len() {
if block[i] == b'<' {
match block[i + 1..].iter().position(|&b| b == b'>') {
Some(rel) => {
spans.push((i + 1, i + 1 + rel));
i += rel + 2;
}
None => break,
}
continue;
}
i += 1;
}
for pair in spans.chunks(2) {
let dst = match pair {
[_src, dst] => *dst,
_ => continue,
};
let (s, e) = dst;
let text = match utf16be_hex_to_string(&block[s..e]) {
Some(t) => t,
None => continue,
};
let mapped = crate::renderer::composer::pua_to_text_surface(&text);
if mapped.as_ref() == text.as_str() {
continue;
}
let hex = string_to_utf16be_hex(mapped.as_ref());
if hex.len() > e - s {
continue; }
block[s..s + hex.len()].copy_from_slice(hex.as_bytes());
for b in &mut block[s + hex.len()..e] {
*b = b' ';
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn utf16be_hex_to_string(hex: &[u8]) -> Option<String> {
if hex.is_empty() || !hex.len().is_multiple_of(4) {
return None;
}
let mut units = Vec::with_capacity(hex.len() / 4);
for quad in hex.chunks(4) {
let mut v: u16 = 0;
for &b in quad {
let d = (b as char).to_digit(16)? as u16;
v = v.checked_mul(16)?.checked_add(d)?;
}
units.push(v);
}
String::from_utf16(&units).ok()
}
#[cfg(not(target_arch = "wasm32"))]
fn string_to_utf16be_hex(s: &str) -> String {
let mut out = String::new();
for unit in s.encode_utf16() {
out.push_str(&format!("{unit:04X}"));
}
out
}
#[cfg(not(target_arch = "wasm32"))]
pub fn svg_to_pdf(svg_content: &str) -> Result<Vec<u8>, String> {
svgs_to_pdf(&[svg_content.to_string()])
}
#[cfg(not(target_arch = "wasm32"))]
pub fn svg_to_pdf_with_options(
svg_content: &str,
options: &PdfExportOptions,
) -> Result<Vec<u8>, String> {
svgs_to_pdf_with_options(&[svg_content.to_string()], options)
}
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Svg2pdfPageIsolation {
Fatal,
RetryWithoutEmbedText,
SkipPage,
}
#[cfg(not(target_arch = "wasm32"))]
pub fn classify_svg2pdf_page_error(
err: &svg2pdf::ConversionError,
embed_text: bool,
already_retried: bool,
) -> Svg2pdfPageIsolation {
if !matches!(err, svg2pdf::ConversionError::SubsetError(_)) {
return Svg2pdfPageIsolation::Fatal;
}
if embed_text && !already_retried {
Svg2pdfPageIsolation::RetryWithoutEmbedText
} else {
Svg2pdfPageIsolation::SkipPage
}
}
#[cfg(not(target_arch = "wasm32"))]
pub fn svg2pdf_subset_error_stub() -> svg2pdf::ConversionError {
svg2pdf::ConversionError::SubsetError(usvg::fontdb::ID::dummy())
}
#[cfg(not(target_arch = "wasm32"))]
pub fn svg2pdf_invalid_image_error() -> svg2pdf::ConversionError {
svg2pdf::ConversionError::InvalidImage
}
#[cfg(not(target_arch = "wasm32"))]
pub fn svg2pdf_to_chunk(
tree: &usvg::Tree,
embed_text: bool,
) -> Result<(pdf_writer::Chunk, pdf_writer::Ref), svg2pdf::ConversionError> {
let mut conversion = svg2pdf::ConversionOptions::default();
conversion.embed_text = embed_text;
svg2pdf::to_chunk(tree, conversion)
}
#[cfg(not(target_arch = "wasm32"))]
fn convert_page_chunk<F>(
tree: &usvg::Tree,
embed_text: bool,
page_index: usize,
to_chunk: &mut F,
) -> Result<Option<(pdf_writer::Chunk, pdf_writer::Ref)>, String>
where
F: FnMut(
&usvg::Tree,
bool,
) -> Result<(pdf_writer::Chunk, pdf_writer::Ref), svg2pdf::ConversionError>,
{
match to_chunk(tree, embed_text) {
Ok(ok) => Ok(Some(ok)),
Err(err) => match classify_svg2pdf_page_error(&err, embed_text, false) {
Svg2pdfPageIsolation::Fatal => Err(format!("SVG→chunk 변환 실패: {:?}", err)),
Svg2pdfPageIsolation::RetryWithoutEmbedText => {
eprintln!(
"WARN: 페이지 {} svg2pdf SubsetError({err:?}) — embed_text=false 로 재시도합니다.",
page_index + 1
);
match to_chunk(tree, false) {
Ok(ok) => Ok(Some(ok)),
Err(err2) => match classify_svg2pdf_page_error(&err2, false, true) {
Svg2pdfPageIsolation::SkipPage => {
eprintln!(
"WARN: 페이지 {} svg2pdf SubsetError({err2:?}) — 이 페이지만 건너뛰고 PDF 를 계속합니다.",
page_index + 1
);
Ok(None)
}
Svg2pdfPageIsolation::Fatal
| Svg2pdfPageIsolation::RetryWithoutEmbedText => {
Err(format!("SVG→chunk 변환 실패: {:?}", err2))
}
},
}
}
Svg2pdfPageIsolation::SkipPage => {
eprintln!(
"WARN: 페이지 {} svg2pdf SubsetError({err:?}) — 이 페이지만 건너뛰고 PDF 를 계속합니다.",
page_index + 1
);
Ok(None)
}
},
}
}
#[cfg(not(target_arch = "wasm32"))]
pub fn svgs_to_pdf(svg_pages: &[String]) -> Result<Vec<u8>, String> {
svgs_to_pdf_with_options(svg_pages, &PdfExportOptions::default())
}
#[cfg(not(target_arch = "wasm32"))]
pub fn svgs_to_pdf_with_options(
svg_pages: &[String],
export_options: &PdfExportOptions,
) -> Result<Vec<u8>, String> {
svgs_to_pdf_with_to_chunk(svg_pages, export_options, svg2pdf_to_chunk)
}
#[cfg(not(target_arch = "wasm32"))]
fn pdf_image_href_resolver() -> usvg::ImageHrefResolver<'static> {
let default_data = usvg::ImageHrefResolver::default_data_resolver();
usvg::ImageHrefResolver {
resolve_data: Box::new(move |mime, data, opts| match mime {
"image/svg+xml" => match usvg::Tree::from_data(&data, opts) {
Ok(tree) => Some(usvg::ImageKind::SVG(tree)),
Err(e) => {
eprintln!("경고: PDF 변환 중 하위 SVG 그림을 파싱하지 못해 건너뜁니다: {e}");
None
}
},
_ => default_data(mime, data, opts),
}),
resolve_string: usvg::ImageHrefResolver::default_string_resolver(),
}
}
#[cfg(not(target_arch = "wasm32"))]
pub fn svgs_to_pdf_with_to_chunk<F>(
svg_pages: &[String],
export_options: &PdfExportOptions,
to_chunk: F,
) -> Result<Vec<u8>, String>
where
F: FnMut(
&usvg::Tree,
bool,
) -> Result<(pdf_writer::Chunk, pdf_writer::Ref), svg2pdf::ConversionError>,
{
svgs_to_pdf_with_links_and_to_chunk(
svg_pages,
&vec![Vec::new(); svg_pages.len()],
export_options,
to_chunk,
)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn svgs_to_pdf_with_links(
svg_pages: &[String],
links: &[Vec<super::hyperlinks::PdfLink>],
options: &PdfExportOptions,
) -> Result<Vec<u8>, String> {
svgs_to_pdf_with_links_and_to_chunk(svg_pages, links, options, svg2pdf_to_chunk)
}
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn svgs_to_pdf_with_links_and_to_chunk<F>(
svg_pages: &[String],
links: &[Vec<super::hyperlinks::PdfLink>],
export_options: &PdfExportOptions,
to_chunk: F,
) -> Result<Vec<u8>, String>
where
F: FnMut(
&usvg::Tree,
bool,
) -> Result<(pdf_writer::Chunk, pdf_writer::Ref), svg2pdf::ConversionError>,
{
svgs_to_pdf_annotations_impl(
svg_pages,
links,
export_options,
to_chunk,
&vec![Vec::new(); svg_pages.len()],
)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn svgs_to_pdf_with_annotations(
svg_pages: &[String],
links: &[Vec<super::hyperlinks::PdfLink>],
destinations: &[Vec<super::hyperlinks::PdfNamedDestination>],
options: &PdfExportOptions,
) -> Result<Vec<u8>, String> {
svgs_to_pdf_annotations_impl(svg_pages, links, options, svg2pdf_to_chunk, destinations)
}
#[cfg(not(target_arch = "wasm32"))]
fn svgs_to_pdf_annotations_impl<F>(
svg_pages: &[String],
links: &[Vec<super::hyperlinks::PdfLink>],
export_options: &PdfExportOptions,
mut to_chunk: F,
destinations: &[Vec<super::hyperlinks::PdfNamedDestination>],
) -> Result<Vec<u8>, String>
where
F: FnMut(
&usvg::Tree,
bool,
) -> Result<(pdf_writer::Chunk, pdf_writer::Ref), svg2pdf::ConversionError>,
{
if links.len() != svg_pages.len() {
return Err("PDF 페이지와 링크 목록의 길이가 다릅니다".into());
}
if svg_pages.is_empty() {
return Err("페이지가 없습니다".to_string());
}
use pdf_writer::{Finish, Pdf, Ref};
use std::collections::HashMap;
let fontdb = create_fontdb(export_options);
let mut options = usvg::Options::default();
options.fontdb = std::sync::Arc::new(fontdb);
options.font_resolver.select_fallback = pdf_font_fallback_selector_with_limits(
PDF_FONT_FALLBACK_INDEX_MAX_CHARS,
PDF_FONT_FALLBACK_INDEX_MAX_FACE_SLOTS,
);
options.image_href_resolver = pdf_image_href_resolver();
let mut alloc = Ref::new(1);
let catalog_ref = alloc.bump();
let page_tree_ref = alloc.bump();
struct PageData {
chunk: pdf_writer::Chunk,
svg_ref: Ref,
width: f32,
height: f32,
source_index: usize,
}
let mut page_datas: Vec<PageData> = Vec::new();
for (page_index, svg) in svg_pages.iter().enumerate() {
let svg_with_fallback = apply_pdf_font_options(svg, export_options);
let (svg_with_bold, bold_report) =
prepare_svg_with_synthetic_bold(&svg_with_fallback, &options)?;
if bold_report.unsupported_texts > 0 {
eprintln!("경고: PDF {}페이지의 굵게 text {}개는 혼합 글꼴/복잡한 paint로 합성하지 못했습니다.", page_index + 1, bold_report.unsupported_texts);
}
let (tree, italic_report) = parse_svg_with_synthetic_italic(&svg_with_bold, &options)
.map_err(|e| format!("SVG 파싱 실패: {}", e))?;
if italic_report.unsupported_texts > 0 {
eprintln!(
"경고: PDF {}페이지의 기울임 text {}개는 혼합 글꼴/복잡한 배치로 합성하지 못했습니다.",
page_index + 1,
italic_report.unsupported_texts,
);
}
let Some((chunk, svg_ref)) =
convert_page_chunk(&tree, export_options.embed_text, page_index, &mut to_chunk)?
else {
continue;
};
let dpi_ratio = 72.0 / 96.0; let w = tree.size().width() * dpi_ratio;
let h = tree.size().height() * dpi_ratio;
page_datas.push(PageData {
chunk,
svg_ref,
width: w,
height: h,
source_index: page_index,
});
}
if page_datas.is_empty() {
return Err("모든 페이지의 SVG→PDF 변환이 SubsetError 로 건너뛰어졌습니다".to_string());
}
let mut page_refs: Vec<Ref> = Vec::new();
let mut renumbered_chunks: Vec<pdf_writer::Chunk> = Vec::new();
let mut svg_refs_remapped: Vec<Ref> = Vec::new();
for pd in &page_datas {
let page_ref = alloc.bump();
let content_ref = alloc.bump();
page_refs.push(page_ref);
let mut map = HashMap::new();
let renumbered = pd
.chunk
.renumber(|old| *map.entry(old).or_insert_with(|| alloc.bump()));
let remapped_svg_ref = map.get(&pd.svg_ref).copied().unwrap_or(pd.svg_ref);
svg_refs_remapped.push(remapped_svg_ref);
renumbered_chunks.push(renumbered);
}
let mut pdf = Pdf::new();
let destinations_ref = alloc.bump();
pdf.catalog(catalog_ref)
.pages(page_tree_ref)
.destinations(destinations_ref);
{
let mut named = pdf.destinations(destinations_ref);
let mut names = std::collections::HashSet::new();
for (index, page) in page_datas.iter().enumerate() {
for destination in destinations.get(page.source_index).into_iter().flatten() {
if destination.x.is_finite()
&& destination.y.is_finite()
&& names.insert(destination.name.as_str())
{
named
.insert(pdf_writer::Name(
super::hyperlinks::pdf_destination_key(&destination.name).as_bytes(),
))
.page(page_refs[index])
.xyz(
(destination.x * 0.75) as f32,
page.height - (destination.y * 0.75) as f32,
None,
);
}
}
}
named.finish();
}
pdf.pages(page_tree_ref)
.count(page_refs.len() as i32)
.kids(page_refs.iter().copied());
let svg_name = pdf_writer::Name(b"S1");
for (i, pd) in page_datas.iter().enumerate() {
let page_ref = page_refs[i];
let content_ref = alloc.bump();
let svg_ref = svg_refs_remapped[i];
let page_links = super::hyperlinks::page_links(
&links[pd.source_index],
f64::from(pd.width) / 0.75,
f64::from(pd.height) / 0.75,
);
let annotation_refs: Vec<_> = page_links.iter().map(|_| alloc.bump()).collect();
let mut page = pdf.page(page_ref);
page.media_box(pdf_writer::Rect::new(0.0, 0.0, pd.width, pd.height));
page.parent(page_tree_ref);
page.contents(content_ref);
if !annotation_refs.is_empty() {
page.annotations(annotation_refs.iter().copied());
}
let mut resources = page.resources();
resources.x_objects().pair(svg_name, svg_ref);
resources.finish();
page.finish();
for (link, annotation_ref) in page_links.iter().zip(annotation_refs) {
let r = link.rect;
let mut annotation = pdf.annotation(annotation_ref);
annotation
.subtype(pdf_writer::types::AnnotationType::Link)
.rect(pdf_writer::Rect::new(
(r.x * 0.75) as f32,
pd.height - ((r.y + r.height) * 0.75) as f32,
((r.x + r.width) * 0.75) as f32,
pd.height - (r.y * 0.75) as f32,
))
.page(page_ref)
.border(0.0, 0.0, 0.0, None);
use crate::model::hyperlink::{classify_destination, LinkDestinationKind};
let mut action = annotation.action();
match classify_destination(&link.uri) {
Some(LinkDestinationKind::DocumentAnchor) => {
action
.action_type(pdf_writer::types::ActionType::GoTo)
.destination_named(pdf_writer::Name(
super::hyperlinks::pdf_destination_key(&link.uri[1..]).as_bytes(),
));
}
Some(LinkDestinationKind::RelativeFile | LinkDestinationKind::LocalFile)
if !link.uri.to_ascii_lowercase().starts_with("file:") =>
{
action.action_type(pdf_writer::types::ActionType::Launch);
action
.file_spec()
.path(pdf_writer::Str(link.uri.as_bytes()))
.unic_file(pdf_writer::TextStr(&link.uri));
}
Some(_) => {
let uri = super::hyperlinks::export_uri(&link.uri)
.ok_or("invalid PDF link destination")?;
action
.action_type(pdf_writer::types::ActionType::Uri)
.uri(pdf_writer::Str(uri.as_bytes()));
}
None => return Err("invalid PDF link destination".into()),
}
action.finish();
annotation.finish();
}
let mut content = pdf_writer::Content::new();
content.transform([pd.width, 0.0, 0.0, pd.height, 0.0, 0.0]);
content.x_object(svg_name);
pdf.stream(content_ref, &content.finish());
}
for chunk in &renumbered_chunks {
pdf.extend(chunk);
}
let info_ref = alloc.bump();
pdf.document_info(info_ref)
.producer(pdf_writer::TextStr("rhwp"));
let mut bytes = pdf.finish();
remap_pua_in_tounicode(&mut bytes);
Ok(bytes)
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
pub fn layer_trees_to_pdf(layer_trees: &[crate::paint::PageLayerTree]) -> Result<Vec<u8>, String> {
layer_trees_to_pdf_with_options(layer_trees, &DirectPdfExportOptions::default())
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
pub fn layer_trees_to_pdf_with_options(
layer_trees: &[crate::paint::PageLayerTree],
options: &DirectPdfExportOptions,
) -> Result<Vec<u8>, String> {
layer_trees_to_pdf_with_links(layer_trees, &vec![Vec::new(); layer_trees.len()], options)
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
pub fn layer_trees_to_pdf_with_links(
layer_trees: &[crate::paint::PageLayerTree],
links: &[Vec<super::hyperlinks::PdfLink>],
options: &DirectPdfExportOptions,
) -> Result<Vec<u8>, String> {
layer_trees_to_pdf_with_annotations(
layer_trees,
links,
&vec![Vec::new(); layer_trees.len()],
options,
)
}
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
pub fn layer_trees_to_pdf_with_annotations(
layer_trees: &[crate::paint::PageLayerTree],
links: &[Vec<super::hyperlinks::PdfLink>],
destinations: &[Vec<super::hyperlinks::PdfNamedDestination>],
options: &DirectPdfExportOptions,
) -> Result<Vec<u8>, String> {
if links.len() != layer_trees.len() {
return Err("PDF 페이지와 링크 목록의 길이가 다릅니다".into());
}
use direct_pdf_validation::CSS_PX_TO_PDF_POINT;
if layer_trees.is_empty() {
return Err("direct PDF export requires at least one page".to_string());
}
if !options.raster_dpi.is_finite() || options.raster_dpi <= 0.0 {
return Err(format!(
"invalid direct PDF raster dpi: {}",
options.raster_dpi
));
}
let page_sizes = layer_trees
.iter()
.enumerate()
.map(|(page_index, tree)| {
validate_direct_pdf_tree(tree, page_index)?;
Ok((
direct_pdf_validation::page_dimension(tree.page_width, true)
.map_err(|error| error.message)?,
direct_pdf_validation::page_dimension(tree.page_height, false)
.map_err(|error| error.message)?,
))
})
.collect::<Result<Vec<_>, String>>()?;
let metadata = skia_safe::pdf::Metadata {
title: options.title.clone().unwrap_or_default(),
author: options.author.clone().unwrap_or_default(),
subject: options.subject.clone().unwrap_or_default(),
keywords: options.keywords.clone().unwrap_or_default(),
creator: "rhwp".to_string(),
producer: "rhwp PageLayerTree direct PDF (Skia)".to_string(),
raster_dpi: Some(options.raster_dpi),
..Default::default()
};
let renderer = crate::renderer::skia::SkiaLayerRenderer::new()
.with_font_paths(options.font_paths.as_slice());
let mut output = Vec::new();
{
let mut document = skia_safe::pdf::new_document(&mut output, Some(&metadata));
for (page_index, ((tree, &(width, height)), links)) in layer_trees
.iter()
.zip(page_sizes.iter())
.zip(links)
.enumerate()
{
let mut page = document.begin_page((width, height), None);
let canvas = page.canvas();
canvas.clear(skia_safe::Color::WHITE);
canvas.scale((CSS_PX_TO_PDF_POINT as f32, CSS_PX_TO_PDF_POINT as f32));
renderer
.render_page_to_canvas_strict(canvas, tree, options.raster_dpi / 96.0)
.map_err(|error| format!("direct PDF page replay failed: {error}"))?;
for destination in destinations.get(page_index).into_iter().flatten() {
if destination.x.is_finite() && destination.y.is_finite() {
let mut name =
super::hyperlinks::pdf_destination_key(&destination.name).into_bytes();
name.push(0);
canvas.annotate_named_destination(
(destination.x as f32, destination.y as f32),
&skia_safe::Data::new_copy(&name),
);
}
}
for link in super::hyperlinks::page_links(links, tree.page_width, tree.page_height) {
let r = link.rect;
let mut uri = super::hyperlinks::export_uri(&link.uri)
.ok_or("invalid PDF link destination")?
.into_bytes();
uri.push(0); let rect = skia_safe::Rect::from_xywh(
r.x as f32,
r.y as f32,
r.width as f32,
r.height as f32,
);
if link.uri.starts_with('#') {
let mut name =
super::hyperlinks::pdf_destination_key(&link.uri[1..]).into_bytes();
name.push(0);
canvas.annotate_link_to_destination(rect, &skia_safe::Data::new_copy(&name));
} else {
canvas.annotate_rect_with_url(rect, &skia_safe::Data::new_copy(&uri));
}
}
document = page.end_page();
}
document.close();
}
if !output.starts_with(b"%PDF-") || !output.windows(5).any(|window| window == b"%%EOF") {
return Err("Skia direct PDF writer returned an incomplete document".to_string());
}
Ok(output)
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
#[test]
fn tounicode_pua_is_remapped_without_changing_length() {
let src = b"beginbfchar
<0001> <DB80DEB1>
<0002> <DB80DEB2>
endbfchar";
let mut buf = src.to_vec();
let before = buf.len();
remap_pua_in_tounicode(&mut buf);
assert_eq!(buf.len(), before, "길이가 바뀌면 /Length 와 xref 가 깨진다");
let out = String::from_utf8(buf).expect("utf-8");
assert!(
out.contains("<2460") && out.contains("<2461"),
"표준 원문자로 안 바뀌었다: {out}"
);
assert!(!out.contains("DB80"), "PUA 서로게이트가 남아 있다: {out}");
}
#[test]
fn tounicode_leaves_unmapped_codepoints_alone() {
let src = b"beginbfchar
<0001> <AC00>
<0002> <0041>
endbfchar";
let mut buf = src.to_vec();
remap_pua_in_tounicode(&mut buf);
assert_eq!(buf, src.to_vec(), "매핑 없는 문자를 건드렸다");
}
#[test]
fn tounicode_does_not_touch_bytes_outside_the_block() {
let src = b"<DB80DEB1> beginbfchar
<0001> <DB80DEB1>
endbfchar <DB80DEB1>";
let mut buf = src.to_vec();
remap_pua_in_tounicode(&mut buf);
let out = String::from_utf8(buf).expect("utf-8");
assert_eq!(
out.matches("DB80DEB1").count(),
2,
"블록 밖 바이트까지 고쳤다: {out}"
);
assert!(out.contains("<2460"), "블록 안은 고쳐야 한다: {out}");
}
#[test]
fn pdf_backend_aliases_are_explicit() {
assert_eq!(PdfBackend::default(), PdfBackend::CompatibilitySvg);
assert_eq!(PdfBackend::parse("svg"), Some(PdfBackend::CompatibilitySvg));
assert_eq!(
PdfBackend::parse("compat"),
Some(PdfBackend::CompatibilitySvg)
);
assert_eq!(PdfBackend::parse("direct"), Some(PdfBackend::DirectLayer));
assert_eq!(PdfBackend::parse("skia"), Some(PdfBackend::DirectLayer));
assert_eq!(PdfBackend::parse("unknown"), None);
assert_eq!(PdfBackend::CompatibilitySvg.as_str(), "svg");
assert_eq!(PdfBackend::DirectLayer.as_str(), "direct");
}
#[test]
fn default_pdf_font_options_are_os_specific_and_non_empty() {
let options = PdfExportOptions::default();
assert!(!options.fallback_serif.is_empty());
assert!(!options.fallback_sans.is_empty());
assert!(!options.fallback_mono.is_empty());
assert!(options.equation_font.is_none());
}
#[test]
fn pdf_font_options_replace_generic_fallbacks_and_equation_font() {
let options = PdfExportOptions {
fallback_serif: "Noto Serif CJK KR".to_string(),
fallback_sans: "Noto Sans CJK KR".to_string(),
fallback_mono: "Noto Sans Mono CJK KR".to_string(),
equation_font: Some("STIX Two Math".to_string()),
font_paths: Vec::new(),
embed_text: true,
};
let svg = format!(
r#"<svg><text font-family="휴먼명조">가</text><text font-family="HCI Poppy">A</text><text {}>x</text></svg>"#,
crate::renderer::equation::svg_render::DEFAULT_EQUATION_FONT_FAMILY_ATTR
);
let out = apply_pdf_font_options(&svg, &options);
assert!(out.contains(r#"font-family="휴먼명조, 'Noto Serif CJK KR', serif""#));
assert!(out.contains(r#"font-family="HCI Poppy, 'Noto Sans CJK KR', sans-serif""#));
assert!(out
.contains(r#"font-family="'STIX Two Math', 'Latin Modern Math'"#));
}
#[test]
fn equation_font_accepts_full_family_chain() {
let chain = equation_font_chain("'Custom Math', 'Fallback Math', serif");
assert_eq!(chain, "'Custom Math', 'Fallback Math', serif");
}
#[cfg(feature = "native-skia")]
fn direct_pdf_test_tree(
width: f64,
height: f64,
fill_color: crate::model::ColorRef,
) -> crate::paint::PageLayerTree {
use crate::paint::{LayerNode, PaintOp, RenderProfile};
use crate::renderer::render_tree::{BoundingBox, RectangleNode};
use crate::renderer::ShapeStyle;
let page_bounds = BoundingBox::new(0.0, 0.0, width, height);
let rectangle = RectangleNode::new(
0.0,
ShapeStyle {
fill_color: Some(fill_color),
..Default::default()
},
None,
);
crate::paint::PageLayerTree::with_profile(
width,
height,
LayerNode::leaf(
page_bounds,
None,
vec![PaintOp::rectangle(
BoundingBox::new(8.0, 8.0, width - 16.0, height - 16.0),
rectangle,
)],
),
RenderProfile::Print,
)
}
#[cfg(feature = "native-skia")]
#[test]
fn skia_direct_pdf_records_multiple_layer_pages() {
let pages = [
direct_pdf_test_tree(96.0, 144.0, 0x000000ff),
direct_pdf_test_tree(192.0, 96.0, 0x0000ff00),
];
let options = DirectPdfExportOptions {
title: Some("P37 direct PDF test".to_string()),
..Default::default()
};
let pdf = layer_trees_to_pdf_with_options(&pages, &options).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
assert!(pdf.windows(5).any(|window| window == b"%%EOF"));
assert!(pdf
.windows(b"P37 direct PDF test".len())
.any(|window| window == b"P37 direct PDF test"));
assert!(pdf
.windows(b"/Count 2".len())
.any(|window| window == b"/Count 2"));
assert!(pdf
.windows(b"/MediaBox [0 0 72 108]".len())
.any(|window| window == b"/MediaBox [0 0 72 108]"));
assert!(pdf
.windows(b"/MediaBox [0 0 144 72]".len())
.any(|window| window == b"/MediaBox [0 0 144 72]"));
assert!(!pdf
.windows(b"/Subtype /Image".len())
.any(|window| window == b"/Subtype /Image"));
}
#[cfg(feature = "native-skia")]
#[test]
fn skia_direct_pdf_rejects_invalid_export_inputs() {
assert_eq!(
layer_trees_to_pdf(&[]).unwrap_err(),
"direct PDF export requires at least one page"
);
let valid = direct_pdf_test_tree(96.0, 96.0, 0x000000ff);
for raster_dpi in [0.0, -1.0, f32::NAN, f32::INFINITY] {
let options = DirectPdfExportOptions {
raster_dpi,
..Default::default()
};
assert!(
layer_trees_to_pdf_with_options(std::slice::from_ref(&valid), &options)
.unwrap_err()
.contains("invalid direct PDF raster dpi")
);
}
for invalid in [
direct_pdf_test_tree(0.0, 96.0, 0x000000ff),
direct_pdf_test_tree(f64::NAN, 96.0, 0x000000ff),
direct_pdf_test_tree(20_000.0, 96.0, 0x000000ff),
] {
assert!(layer_trees_to_pdf(std::slice::from_ref(&invalid)).is_err());
}
let mut oversized_layer = direct_pdf_test_tree(96.0, 96.0, 0x000000ff);
oversized_layer.root.bounds.x = f32::MAX as f64 * 2.0;
assert!(layer_trees_to_pdf(&[oversized_layer])
.unwrap_err()
.contains("invalid layer bounds"));
}
#[cfg(feature = "native-skia")]
#[test]
fn skia_direct_pdf_rejects_corrupt_and_unvalidated_images() {
use crate::paint::{LayerNode, PaintOp, RenderProfile};
use crate::renderer::render_tree::{BoundingBox, ImageNode};
use image::{ImageFormat, Rgb, RgbImage};
use std::io::Cursor;
let image = RgbImage::from_fn(64, 64, |x, y| {
Rgb([
(x.wrapping_mul(17) ^ y.wrapping_mul(31)) as u8,
(x.wrapping_mul(47).wrapping_add(y.wrapping_mul(13))) as u8,
(x.wrapping_mul(7) ^ y.wrapping_mul(53)) as u8,
])
});
let mut cursor = Cursor::new(Vec::new());
image
.write_to(&mut cursor, ImageFormat::Png)
.expect("encode test PNG");
let mut corrupt_png = cursor.into_inner();
let idat_type_offset = corrupt_png
.windows(4)
.position(|window| window == b"IDAT")
.expect("encoded PNG must contain IDAT");
corrupt_png[idat_type_offset + 4] ^= 0xff;
assert!(
skia_safe::Image::from_encoded(skia_safe::Data::new_copy(&corrupt_png)).is_some(),
"fixture must pass Skia's encoded-header check"
);
assert!(
image::load_from_memory_with_format(&corrupt_png, ImageFormat::Png).is_err(),
"fixture must fail strict PNG decoding"
);
let page_bounds = BoundingBox::new(0.0, 0.0, 96.0, 96.0);
let tree = crate::paint::PageLayerTree::with_profile(
96.0,
96.0,
LayerNode::leaf(
page_bounds,
None,
vec![PaintOp::image(
BoundingBox::new(8.0, 8.0, 32.0, 32.0),
ImageNode::new(1, Some(corrupt_png)),
None,
)],
),
RenderProfile::Print,
);
let error = layer_trees_to_pdf(&[tree]).unwrap_err();
assert!(
error.contains("cannot decode image payload"),
"unexpected error: {error}"
);
let malformed_gif = crate::paint::PageLayerTree::with_profile(
96.0,
96.0,
LayerNode::leaf(
page_bounds,
None,
vec![PaintOp::image(
BoundingBox::new(8.0, 8.0, 32.0, 32.0),
ImageNode::new(2, Some(b"GIF89a\x01\x00\x01\x00\x80\x00\x00".to_vec())),
None,
)],
),
RenderProfile::Print,
);
let error = layer_trees_to_pdf(&[malformed_gif]).unwrap_err();
assert!(
error.contains("cannot decode image payload"),
"unexpected error: {error}"
);
let unsupported = crate::paint::PageLayerTree::with_profile(
96.0,
96.0,
LayerNode::leaf(
page_bounds,
None,
vec![PaintOp::image(
BoundingBox::new(8.0, 8.0, 32.0, 32.0),
ImageNode::new(3, Some(b"unrecognized image payload".to_vec())),
None,
)],
),
RenderProfile::Print,
);
let error = layer_trees_to_pdf(&[unsupported]).unwrap_err();
assert!(
error.contains("does not support image payload format application/octet-stream"),
"unexpected error: {error}"
);
}
#[cfg(feature = "native-skia")]
#[test]
fn skia_direct_pdf_rejects_known_lossy_shape_replay() {
use crate::paint::{LayerNode, PaintOp, RenderProfile};
use crate::renderer::render_tree::{BoundingBox, RectangleNode};
use crate::renderer::{GradientFillInfo, ShapeStyle};
for gradient_type in [3, 4] {
let bbox = BoundingBox::new(0.0, 0.0, 96.0, 96.0);
let gradient = GradientFillInfo {
gradient_type,
angle: 0,
center_x: 50,
center_y: 50,
colors: vec![0x000000ff, 0x00ff0000],
positions: vec![0.0, 1.0],
};
let tree = crate::paint::PageLayerTree::with_profile(
96.0,
96.0,
LayerNode::leaf(
bbox,
None,
vec![PaintOp::rectangle(
bbox,
RectangleNode::new(0.0, ShapeStyle::default(), Some(Box::new(gradient))),
)],
),
RenderProfile::Print,
);
let error = layer_trees_to_pdf(&[tree]).unwrap_err();
assert!(error.contains("gradient fill"), "unexpected error: {error}");
assert!(error.contains("use the svg backend"));
}
}
#[cfg(feature = "native-skia")]
#[test]
fn skia_direct_pdf_raw_svg_fallback_is_strict_and_uses_requested_dpi() {
use crate::paint::{LayerNode, PaintOp, RenderProfile};
use crate::renderer::render_tree::{BoundingBox, RawSvgNode};
let page_bounds = BoundingBox::new(0.0, 0.0, 96.0, 96.0);
let svg_bounds = BoundingBox::new(8.0, 8.0, 32.0, 16.0);
let tree_with_svg = |svg: &str| {
crate::paint::PageLayerTree::with_profile(
96.0,
96.0,
LayerNode::leaf(
page_bounds,
None,
vec![PaintOp::raw_svg(
svg_bounds,
RawSvgNode::new(svg.to_string()),
)],
),
RenderProfile::Print,
)
};
let invalid = layer_trees_to_pdf(&[tree_with_svg("<path")]).unwrap_err();
assert!(invalid.contains("raw SVG raster fallback failed"));
let options = DirectPdfExportOptions {
raster_dpi: 192.0,
..Default::default()
};
let pdf = layer_trees_to_pdf_with_options(
&[tree_with_svg(
r##"<rect x="8" y="8" width="32" height="16" fill="#f00"/>"##,
)],
&options,
)
.unwrap();
assert!(pdf.windows(9).any(|window| window == b"/Width 64"));
assert!(pdf.windows(10).any(|window| window == b"/Height 32"));
}
}