mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-08 19:42:12 +00:00
* hayro-interpret: ink colors, overprint and font bytes for the flattener Local patches for craft-prepress's PDF-in adapter, labeled Craft patch (flatten) and listed in vendor/README.craft-reader.md: - Device::set_overprint and Device::set_isolated, called where the blend mode is set and after an isolated group is pushed. - Color::ink_paint, ColorSpace::ink_space and ink_values: colors and image samples as the inks they print, without converting to RGB. RasterImage::with_inks gives native samples with Decode and Matte. - OutlineFontData::embedded and index, and the CFF bytes of Type1C fonts, so text can be embedded again. - The sh operator ignores /Background (ISO 32000-2 8.7.4.5.1). * plate-test: flattened-page checks, image alpha and scenes F01, F02 - report::run_flattened separates each scene's page after a caller's flattener as well as the original, and structure::transparency lists what transparency a page still has. plate-test doesn't depend on the flattener. - Scene images take an alpha channel, written as /SMask. - F01: a partly transparent image over a flat fill; where its alpha is 0 the fill keeps its exact inks (vectorcraft#2160). - F02: art hidden under opaque fills leaves no trace after flattening (vectorcraft#2161). * prepress: transparency flattener (flatten feature) craft_prepress::flatten turns PDF pages with transparency into pages without it, keeping inks, overprint and live text, for PDF/X-1a and other output that can't carry transparency. - pdf: reads a page into a display list in inks through hayro-interpret: paths, outlined strokes, clips, groups, soft masks, overprint, spot and DeviceN colors, images in their own color space, gradients, rasterized mesh shadings, tiling patterns and glyph runs. - font: prepares the source fonts for embedding again (TrueType, OpenType, CFF wrapped as OpenType); others fall back to outlines with ActualText. - geom: planar regions with the shapes that cover each one (linesweeper). - compose: composites each region per ink (separable and non-separable blend modes, isolated and knockout groups, overprint per plate as ISO 32000 defines it); regions under images, gradients and soft masks are marked complex. - raster: complex regions as DeviceN images through plate mode, grid snapped with a one-pixel outset; flatten_page. - write: writes the result with the vendored krilla; flatten_document writes every page into one PDF with the output intent, page boxes and fonts shared across pages when their bytes match. The regions and the compositor are ported from VectorCraft (commit c2b15982, crates/pathops and crates/engine/src/cmd/flatten.rs), credited in the crate README. scripts/plate-check.sh --flatten separates every scene's flattened page with Ghostscript (local only). CI runs craft-prepress with all features. * krilla: DeviceN /Colorants from PDF 1.3, NChannel attributes from 1.6 (patch 11) * prepress: flatten_document output PDF version and PDF/X version * prepress: format the PDF/X-1a flatten test * krilla, craft-prepress: write GTS_PDFXConformance next to GTS_PDFXVersion PDF/X-1a:2003 files carry GTS_PDFXVersion (PDF/X-1:2003) and GTS_PDFXConformance (PDF/X-1a:2003). Krilla patch 12 adds SerializeSettings::pdfx_conformance, and FlattenDocumentOptions passes it through. * krilla, craft-pdf, craft-prepress: carry the modification date over Krilla patch 13 adds Metadata::modification_date, written as /ModDate and xmp:ModifyDate in place of the creation date. craft-pdf's Metadata gains modified, and flatten_document takes it from the source's ModDate. * craft-prepress: count the print annotations a read leaves out ReadReport::dropped_annotations counts the annotations a printer would paint (Print flag, not Hidden, with a normal appearance) when ReadOptions::annotations is false; FlattenTotals sums it. * craft-prepress: degenerate groups rasterize without a soft mask A group the region sweep fails on is clipped to its members' boxes, which no other group's items reach, so the paper is its only backdrop. Its image is written opaque, as the plates of the items over paper, and the page keeps no transparency for PDF/X-1a. * craft-prepress: write untouched JPEG images as they are A DCT-encoded DeviceGray or DeviceCMYK image that krilla's JPEG passthrough writes with the same meaning (8 bits, no decode parameters, the default gray Decode or the inverted Adobe CMYK one) keeps its data in ImageItem::jpeg, and the writer embeds it unchanged when the image has no soft mask. Other images are still 8-bit Flate samples. * craft-prepress: keep group members with no transparency above them Groups are transitive by bounding box, so a background frame put all the body text on it under a transparent object far away, and the text came back as outlined fills. A member is now drawn as it is when it is opaque and, in every region its shapes are in, only members kept this way are above it. The region fills under it are the composite of the other members, and it is drawn over them in paint order. * prepress: keep the backdrop under elements of a knockout group * prepress: rasterize complex regions thinner than a point * prepress: mark flatten errors, reasons and reports non_exhaustive * prepress: bound the items a tiling pattern fill expands into Each of up to MAX_TILING_CELLS cells copied the whole cell content, and a cell can hold many items or an expanded pattern of its own. A fill whose cells would hold more than MAX_TILING_ITEMS items in all, counting groups, masks and nested patterns, is read as an image. * prepress: stroke solid past the dash budget A dash pattern that cuts a stroke into more than 250,000 pieces is outlined solid, with the estimate hayro's renderer uses. * prepress: bound the sampling and memory of rasterized tiling patterns Each pixel sampled every cell over it, which for a BBox far larger than its step is millions of cells per pixel; past MAX_TILING_CELLS cells per pixel the fill paints nothing, and below it the image resolution drops to keep the samples within MAX_TILING_SAMPLES. The canvases also hold a value per page ink, so their pixel limits shrink with the ink count to keep the memory of CMYK canvases, and the canvas size uses checked arithmetic. * prepress: mark the page reader's error and report non_exhaustive * prepress: format the tiling tests * prepress: CodeRabbit fixes: no nonzero overprint mode for images and shadings, count dropped tilings, widen the hhea ascender * prepress: refuse DeviceN spaces past the output's colorant limit and regions past the separated spot inks
200 lines
8.6 KiB
Rust
200 lines
8.6 KiB
Rust
//! PDF authoring shared by Craft apps, using Krilla's drawing primitives.
|
|
//!
|
|
//! Applications supply already laid-out pages and retain their document models, font
|
|
//! licensing and fallback policy, export presets, tagging semantics and postprocessing.
|
|
//! [`backend`] exposes Krilla explicitly; this is not an independent graphics model.
|
|
|
|
use std::panic::{AssertUnwindSafe, catch_unwind};
|
|
|
|
pub use krilla as backend;
|
|
|
|
// Require the root workspace patch; an unpatched backend can abort during unwind, writes
|
|
// RGB blending groups and no print output intent, and has no optional content.
|
|
const _: bool = backend::CRAFT_UNWIND_POISONING;
|
|
const _: bool = backend::CRAFT_PRINT_COLOR;
|
|
const _: bool = backend::CRAFT_OPTIONAL_CONTENT;
|
|
|
|
pub mod print;
|
|
|
|
use backend::configure::{Archival, Configuration, ConfigurationBuilder, ConfigurationError, PdfVersion};
|
|
use backend::text::{Font, Tag};
|
|
|
|
/// Largest individual font copied for embedding (512 MiB).
|
|
pub const MAX_FONT_BYTES: usize = 512 * 1024 * 1024;
|
|
/// Maximum number of variation coordinates accepted for one font instance.
|
|
pub const MAX_FONT_VARIATIONS: usize = 256;
|
|
|
|
/// Shared failures retain backend diagnostics instead of silently emitting a partial PDF.
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum WriteError {
|
|
#[error("{0:?}")]
|
|
Configuration(ConfigurationError),
|
|
#[error("{0:?}")]
|
|
Serialization(#[source] Box<backend::error::KrillaError>),
|
|
#[error("PDF export failed internally: {0}")]
|
|
BackendPanic(String),
|
|
#[error("font exceeds the {MAX_FONT_BYTES}-byte embedding limit")]
|
|
FontLimit,
|
|
#[error("font variation coordinates must be finite and number at most {MAX_FONT_VARIATIONS}")]
|
|
FontVariations,
|
|
#[error("font data could not be allocated")]
|
|
Allocation,
|
|
#[error("font could not be read for embedding")]
|
|
InvalidFont,
|
|
#[error("the print profile is not a readable CMYK ICC profile")]
|
|
InvalidProfile,
|
|
}
|
|
|
|
/// Run an entire app export, including drawing and postprocessing, behind a native
|
|
/// unwind guard. Existing application errors pass through unchanged.
|
|
///
|
|
/// Discard any writer or drawing state captured by the closure after a panic. Prefer
|
|
/// constructing the writer inside the closure. WASM aborts and process-wide allocation
|
|
/// failures cannot be caught; this is not a memory or execution-time budget.
|
|
pub fn guard<T, E: From<WriteError>>(operation: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
|
|
catch_unwind(AssertUnwindSafe(operation)).map_err(|payload| {
|
|
let message = payload
|
|
.downcast_ref::<String>()
|
|
.map(String::as_str)
|
|
.or_else(|| payload.downcast_ref::<&str>().copied())
|
|
.unwrap_or("non-string panic payload");
|
|
E::from(WriteError::BackendPanic(message.chars().take(1024).collect()))
|
|
})?
|
|
}
|
|
|
|
/// Build a version/archival configuration without changing application export policy.
|
|
pub fn configuration(version: PdfVersion, archival: Option<Archival>) -> Result<Configuration, WriteError> {
|
|
guard(|| {
|
|
let mut builder = ConfigurationBuilder::new().with_version(version);
|
|
if let Some(archival) = archival {
|
|
builder = builder.with_archival_validator(archival);
|
|
}
|
|
builder.finish().map_err(WriteError::Configuration)
|
|
})
|
|
}
|
|
|
|
/// Common document information. Callers decide which values to provide and whether to
|
|
/// trim them. Dates are supplied explicitly; this crate never consults a platform clock.
|
|
#[derive(Clone, Debug, Default)]
|
|
pub struct Metadata {
|
|
pub creator: String,
|
|
pub producer: String,
|
|
pub title: Option<String>,
|
|
pub authors: Vec<String>,
|
|
pub description: Option<String>,
|
|
pub keywords: Vec<String>,
|
|
pub created: Option<backend::metadata::DateTime>,
|
|
/// Written as the modification date; `created` is written there when this is `None`.
|
|
pub modified: Option<backend::metadata::DateTime>,
|
|
}
|
|
|
|
impl Metadata {
|
|
fn into_backend(self) -> backend::metadata::Metadata {
|
|
let mut metadata =
|
|
backend::metadata::Metadata::new().creator(self.creator).producer(self.producer).authors(self.authors).keywords(self.keywords);
|
|
if let Some(title) = self.title {
|
|
metadata = metadata.title(title);
|
|
}
|
|
if let Some(description) = self.description {
|
|
metadata = metadata.description(description);
|
|
}
|
|
if let Some(created) = self.created {
|
|
metadata = metadata.creation_date(created);
|
|
}
|
|
if let Some(modified) = self.modified {
|
|
metadata = metadata.modification_date(modified);
|
|
}
|
|
metadata
|
|
}
|
|
}
|
|
|
|
/// A writer whose serialization is fallible and consumes the document on every outcome.
|
|
pub struct Writer {
|
|
document: backend::Document,
|
|
}
|
|
|
|
impl Writer {
|
|
/// Keep all backend settings, including colour profiles, compression and validators.
|
|
pub fn new(settings: backend::SerializeSettings, metadata: Metadata) -> Self {
|
|
Self::new_with_language(settings, metadata, None)
|
|
}
|
|
|
|
/// Set an optional document language without changing the common metadata fields.
|
|
/// Empty language is treated as absent. Callers validate nonempty tags, which pass through unchanged.
|
|
pub fn new_with_language(settings: backend::SerializeSettings, metadata: Metadata, language: Option<String>) -> Self {
|
|
let mut metadata = metadata.into_backend();
|
|
if let Some(language) = language.filter(|language| !language.is_empty()) {
|
|
metadata = metadata.language(language);
|
|
}
|
|
let mut document = backend::Document::new_with(settings);
|
|
document.set_metadata(metadata);
|
|
Self { document }
|
|
}
|
|
|
|
/// Advanced drawing, resource, outline and tag-tree access for an application's adapter.
|
|
/// Use [`guard`] around the whole export to cover drawing as well as serialization.
|
|
pub fn document_mut(&mut self) -> &mut backend::Document {
|
|
&mut self.document
|
|
}
|
|
|
|
/// Serialize, preserving validation failures and catching native backend unwinds.
|
|
/// The returned byte vector is not a bound on peak serialization memory.
|
|
pub fn finish(self) -> Result<Vec<u8>, WriteError> {
|
|
guard(|| self.document.finish().map_err(|error| WriteError::Serialization(Box::new(error))))
|
|
}
|
|
}
|
|
|
|
/// The link target that opens `url`, or `None` when [`safe_url`](crate::safe_url) refuses it.
|
|
/// Build URI links with this instead of `backend::action::LinkAction` so a refused target
|
|
/// writes no link annotation; the page content stays as drawn. The URI is written trimmed.
|
|
pub fn uri_target(url: &str) -> Option<backend::annotation::Target> {
|
|
let url = url.trim();
|
|
crate::safe_url(url).then(|| backend::annotation::Target::Action(backend::action::LinkAction::new(url.to_owned()).into()))
|
|
}
|
|
|
|
fn check_font_input(size: usize, variations: Option<&[([u8; 4], f32)]>) -> Result<(), WriteError> {
|
|
if size > MAX_FONT_BYTES {
|
|
return Err(WriteError::FontLimit);
|
|
}
|
|
if variations.is_some_and(|coords| coords.len() > MAX_FONT_VARIATIONS || coords.iter().any(|(_, value)| !value.is_finite())) {
|
|
return Err(WriteError::FontVariations);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Copy and prepare an already selected, licensed font for Krilla's subset embedding.
|
|
/// `None` retains static-font construction; `Some` retains variable-font construction,
|
|
/// including an empty coordinate list. Selection, caching, shaping and fallback belong
|
|
/// to the app. An error never substitutes another font or drops text silently.
|
|
pub fn font(data: &[u8], index: u32, variations: Option<&[([u8; 4], f32)]>) -> Result<Font, WriteError> {
|
|
check_font_input(data.len(), variations)?;
|
|
let mut owned = Vec::new();
|
|
owned.try_reserve_exact(data.len()).map_err(|_| WriteError::Allocation)?;
|
|
owned.extend_from_slice(data);
|
|
guard(|| {
|
|
let font = match variations {
|
|
None => Font::new(owned.into(), index),
|
|
Some(coords) => {
|
|
let coords: Vec<_> = coords.iter().map(|(tag, value)| (Tag::new(tag), *value)).collect();
|
|
Font::new_variable(owned.into(), index, &coords)
|
|
}
|
|
};
|
|
font.ok_or(WriteError::InvalidFont)
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
|
fn font_bounds_are_checked_without_allocating_the_input() {
|
|
assert!(check_font_input(MAX_FONT_BYTES, None).is_ok());
|
|
assert!(matches!(check_font_input(MAX_FONT_BYTES + 1, None), Err(WriteError::FontLimit)));
|
|
assert!(matches!(check_font_input(usize::MAX, None), Err(WriteError::FontLimit)));
|
|
let coords = vec![(*b"wght", 400.0); MAX_FONT_VARIATIONS + 1];
|
|
assert!(matches!(check_font_input(0, Some(&coords)), Err(WriteError::FontVariations)));
|
|
}
|
|
}
|