Files
Pictor-public/crates/doc/src/export.rs
T

935 lines
37 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Exports: PNG at a scale, JPG on white, SVG (vector layers as SVG, pixels embedded as PNG) and PDF with pdf-writer
//! (vectors stay vectors, text is real text in subset fonts with a ToUnicode map, each page at its exact size).
//! All of them walk the display list (`display::build`), the same one the screen is painted from.
use crate::display::{self, DGlyph, DPaint, DisplayList, Item, Tf};
use crate::model::*;
use crate::path;
use crate::text::{Embedding, FontBook, FontKey};
use pdf_writer::{Content, Filter, Finish, Name, Pdf, Rect as PRect, Ref, Str};
use std::collections::{BTreeMap, HashMap};
use std::fmt::Write as _;
use std::io::Write as _;
#[derive(Debug, thiserror::Error)]
pub enum ExportError {
#[error("The font \u{201c}{family}\u{201d} cannot be put in a PDF: {reason}. Choose another font for that text.")]
FontNotEmbeddable { family: String, reason: &'static str },
#[error("The font \u{201c}{0}\u{201d} could not be prepared for the PDF.")]
FontBroken(String),
#[error("The picture is too large to export at this scale.")]
TooLarge,
#[error("Could not encode the picture: {0}")]
Encode(String),
}
/// A page as PNG at `scale` pixels per point.
pub fn png(doc: &Document, page: &Page, book: &FontBook, scale: f32) -> Result<Vec<u8>, ExportError> {
let r = raster(doc, page, book, scale)?;
crate::format::encode_png(&r).map_err(|e| ExportError::Encode(e.to_string()))
}
/// A page as JPG (quality 0–100) at `scale`, on white where the page is transparent.
pub fn jpg(doc: &Document, page: &Page, book: &FontBook, scale: f32, quality: u8) -> Result<Vec<u8>, ExportError> {
use image::ImageEncoder;
let r = raster(doc, page, book, scale)?;
let mut rgb = Vec::with_capacity(r.rgba.len() / 4 * 3);
for p in r.rgba.as_chunks::<4>().0 {
let a = p[3] as u32;
for c in &p[..3] {
rgb.push(((*c as u32 * a + 255 * (255 - a) + 127) / 255) as u8);
}
}
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100))
.write_image(&rgb, r.width, r.height, image::ExtendedColorType::Rgb8)
.map_err(|e| ExportError::Encode(e.to_string()))?;
Ok(out)
}
fn raster(doc: &Document, page: &Page, book: &FontBook, scale: f32) -> Result<Raster, ExportError> {
let px = (page.width * scale) as u64 * (page.height * scale) as u64;
if scale.is_nan() || scale <= 0.0 || px > 200_000_000 {
return Err(ExportError::TooLarge);
}
crate::render::page(doc, page, book, scale).ok_or(ExportError::TooLarge)
}
// ---- SVG ----------------------------------------------------------------------------------------------------------
fn hex(c: [u8; 4]) -> String {
format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2])
}
fn esc(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
fn mat(t: Tf) -> String {
format!("matrix({} {} {} {} {} {})", t[0], t[1], t[2], t[3], t[4], t[5])
}
/// A page as SVG. Text is written as `<text>` with each character's x, so it stays text.
pub fn svg(doc: &Document, page: &Page, book: &FontBook) -> String {
use base64::Engine as _;
let list = display::build(doc, page, book);
let mut defs = String::new();
let mut body = String::new();
let mut n = 0;
let mut paint = |p: &DPaint, defs: &mut String| -> (String, Option<f32>) {
match p {
DPaint::Solid { c } => (hex(*c), (c[3] < 255).then_some(c[3] as f32 / 255.0)),
DPaint::Linear { x1, y1, x2, y2, stops } => {
n += 1;
let _ = write!(
defs,
r#"<linearGradient id="g{n}" gradientUnits="userSpaceOnUse" x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}">"#
);
for (o, c) in stops {
let _ = write!(
defs,
r#"<stop offset="{o}" stop-color="{}" stop-opacity="{}"/>"#,
hex(*c),
c[3] as f32 / 255.0
);
}
defs.push_str("</linearGradient>");
(format!("url(#g{n})"), None)
}
DPaint::Radial { cx, cy, r, stops } => {
n += 1;
let _ = write!(
defs,
r#"<radialGradient id="g{n}" gradientUnits="userSpaceOnUse" cx="{cx}" cy="{cy}" r="{r}">"#
);
for (o, c) in stops {
let _ = write!(
defs,
r#"<stop offset="{o}" stop-color="{}" stop-opacity="{}"/>"#,
hex(*c),
c[3] as f32 / 255.0
);
}
defs.push_str("</radialGradient>");
(format!("url(#g{n})"), None)
}
}
};
let mut clips = 0;
let mut pngs: HashMap<&str, String> = HashMap::new();
for item in &list.items {
match item {
Item::Push { opacity } => {
let _ = write!(body, r#"<g opacity="{opacity}">"#);
}
Item::Pop => body.push_str("</g>"),
Item::Fill { d, t, paint: p, even_odd, .. } => {
let (f, a) = paint(p, &mut defs);
let _ = write!(body, r#"<path d="{d}" transform="{}" fill="{f}""#, mat(*t));
if let Some(a) = a {
let _ = write!(body, r#" fill-opacity="{a}""#);
}
if *even_odd {
body.push_str(r#" fill-rule="evenodd""#);
}
body.push_str("/>");
}
Item::Stroke { d, t, paint: p, width, cap, join, dash, .. } => {
let (s, a) = paint(p, &mut defs);
let _ = write!(
body,
r#"<path d="{d}" transform="{}" fill="none" stroke="{s}" stroke-width="{width}""#,
mat(*t)
);
if let Some(a) = a {
let _ = write!(body, r#" stroke-opacity="{a}""#);
}
let cap = match cap {
Cap::Butt => "butt",
Cap::Round => "round",
Cap::Square => "square",
};
let join = match join {
Join::Miter => "miter",
Join::Round => "round",
Join::Bevel => "bevel",
};
let _ = write!(body, r#" stroke-linecap="{cap}" stroke-linejoin="{join}""#);
if !dash.is_empty() {
let d: Vec<String> = dash.iter().map(|v| v.to_string()).collect();
let _ = write!(body, r#" stroke-dasharray="{}""#, d.join(" "));
}
body.push_str("/>");
}
Item::Image { asset, t, clip, clip_t, .. } => {
let Some(r) = doc.assets.get(asset) else { continue };
let href = pngs.entry(asset.as_str()).or_insert_with(|| {
let png = crate::format::encode_png(r).unwrap_or_default();
format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(png))
});
if let Some(cd) = clip {
clips += 1;
let _ = write!(
defs,
r#"<clipPath id="c{clips}"><path d="{cd}" transform="{}"/></clipPath>"#,
mat(*clip_t)
);
let _ = write!(body, r#"<g clip-path="url(#c{clips})">"#);
}
let _ = write!(
body,
r#"<image href="{href}" width="{}" height="{}" transform="{}" preserveAspectRatio="none"/>"#,
r.width,
r.height,
mat(*t)
);
if clip.is_some() {
body.push_str("</g>");
}
}
Item::Text { t, color, size, glyphs, family, weight, italic, .. } => {
// One <text> per line (glyphs that share a baseline), every character placed at its glyph's x.
let mut lines: BTreeMap<i64, Vec<&DGlyph>> = BTreeMap::new();
for g in glyphs {
lines.entry((g.y * 100.0) as i64).or_default().push(g);
}
let _ = write!(
body,
r#"<g transform="{}" font-family="{}" font-size="{size}" font-weight="{weight}"{} fill="{}"{}>"#,
mat(*t),
esc(family),
if *italic { r#" font-style="italic""# } else { "" },
hex(*color),
if color[3] < 255 {
format!(r#" fill-opacity="{}""#, color[3] as f32 / 255.0)
} else {
String::new()
}
);
for gs in lines.values() {
let mut xs = Vec::new();
let mut s = String::new();
for g in gs {
for (i, ch) in g.text.chars().enumerate() {
xs.push(format!(
"{}",
g.x + if i == 0 { 0.0 } else { g.advance * i as f32 / g.text.chars().count() as f32 }
));
s.push(ch);
}
}
if s.trim().is_empty() {
continue;
}
let _ = write!(
body,
r#"<text xml:space="preserve" x="{}" y="{}">{}</text>"#,
xs.join(" "),
gs[0].y,
esc(&s)
);
}
body.push_str("</g>");
}
}
}
let mut out = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w}pt" height="{h}pt" viewBox="0 0 {w} {h}">"#,
w = list.width,
h = list.height
);
if !defs.is_empty() {
let _ = write!(out, "<defs>{defs}</defs>");
}
if let Some(bg) = list.background {
let _ = write!(out, r#"<rect width="{}" height="{}" fill="{}"/>"#, list.width, list.height, hex(bg));
}
out.push_str(&body);
out.push_str("</svg>");
out
}
// ---- PDF ----------------------------------------------------------------------------------------------------------
fn deflate(data: &[u8]) -> Vec<u8> {
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(6));
let _ = e.write_all(data);
e.finish().unwrap_or_default()
}
struct FontUse {
name: String,
/// Subset fonts are addressed by the subset's glyph ids (CID = new gid); others by their own ids.
subset: bool,
remapper: subsetter::GlyphRemapper,
/// CID → (original glyph id, the text it stands for).
glyphs: BTreeMap<u16, (u16, String)>,
}
/// The fonts a set of display lists uses, and whether each may be embedded.
pub fn check_fonts(lists: &[DisplayList], book: &FontBook) -> Result<(), ExportError> {
for l in lists {
for it in &l.items {
if let Item::Text { glyphs, .. } = it {
for g in glyphs {
let f = book.font(g.font);
if let Embedding::Forbidden(reason) = f.embedding {
return Err(ExportError::FontNotEmbeddable { family: f.family.clone(), reason });
}
}
}
}
}
Ok(())
}
struct Writer<'a> {
pdf: Pdf,
next: i32,
book: &'a FontBook,
fonts: BTreeMap<FontKey, (Ref, FontUse)>,
images: BTreeMap<String, (Ref, String)>,
alphas: BTreeMap<(u8, u8), (Ref, String)>,
patterns: Vec<(Ref, String, DPaint, Tf)>,
forms: Vec<(Ref, String, Vec<u8>)>,
}
impl Writer<'_> {
fn alloc(&mut self) -> Ref {
self.next += 1;
Ref::new(self.next)
}
fn alpha(&mut self, fill: u8, stroke: u8) -> String {
if let Some((_, n)) = self.alphas.get(&(fill, stroke)) {
return n.clone();
}
let r = self.alloc();
let n = format!("A{}", self.alphas.len());
self.alphas.insert((fill, stroke), (r, n.clone()));
n
}
fn pattern(&mut self, p: &DPaint, full: Tf) -> String {
let r = self.alloc();
let n = format!("P{}", self.patterns.len());
self.patterns.push((r, n.clone(), p.clone(), full));
n
}
fn image(&mut self, asset: &str) -> String {
if let Some((_, n)) = self.images.get(asset) {
return n.clone();
}
let r = self.alloc();
let n = format!("Im{}", self.images.len());
self.images.insert(asset.to_string(), (r, n.clone()));
n
}
fn font(&mut self, key: FontKey) -> String {
if let Some((_, u)) = self.fonts.get(&key) {
return u.name.clone();
}
let r = self.alloc();
let n = format!("F{}", self.fonts.len());
let f = self.book.font(key);
let subset = ttf_parser::Face::parse(&f.data, f.index).map(|fc| fc.is_subsetting_allowed()).unwrap_or(false);
let u = FontUse { name: n.clone(), subset, remapper: subsetter::GlyphRemapper::new(), glyphs: BTreeMap::new() };
self.fonts.insert(key, (r, u));
n
}
}
/// The names a page or form refers to, copied out of the writer so the PDF can be written while they are used.
#[derive(Default)]
struct ResTable {
fonts: Vec<(String, Ref)>,
xobjects: Vec<(String, Ref)>,
states: Vec<(String, Ref)>,
patterns: Vec<(String, Ref)>,
}
impl Writer<'_> {
fn table(&self) -> ResTable {
ResTable {
fonts: self.fonts.values().map(|(r, u)| (u.name.clone(), *r)).collect(),
xobjects: self
.images
.values()
.map(|(r, n)| (n.clone(), *r))
.chain(self.forms.iter().map(|(r, n, _)| (n.clone(), *r)))
.collect(),
states: self.alphas.values().map(|(r, n)| (n.clone(), *r)).collect(),
patterns: self.patterns.iter().map(|(r, n, _, _)| (n.clone(), *r)).collect(),
}
}
}
fn write_resources(t: &ResTable, res: &mut pdf_writer::writers::Resources) {
let mut f = res.fonts();
for (n, r) in &t.fonts {
f.pair(Name(n.as_bytes()), *r);
}
f.finish();
let mut x = res.x_objects();
for (n, r) in &t.xobjects {
x.pair(Name(n.as_bytes()), *r);
}
x.finish();
let mut g = res.ext_g_states();
for (n, r) in &t.states {
g.pair(Name(n.as_bytes()), *r);
}
g.finish();
let mut p = res.patterns();
for (n, r) in &t.patterns {
p.pair(Name(n.as_bytes()), *r);
}
p.finish();
}
fn path_ops(c: &mut Content, d: &str) {
let Ok(segs) = path::parse(d) else { return };
let (mut cx, mut cy) = (0.0f32, 0.0f32);
for s in segs {
match s {
path::Seg::Move(x, y) => {
c.move_to(x, y);
(cx, cy) = (x, y);
}
path::Seg::Line(x, y) => {
c.line_to(x, y);
(cx, cy) = (x, y);
}
path::Seg::Quad(a, b, x, y) => {
// Quadratic → cubic.
let (c1x, c1y) = (cx + 2.0 / 3.0 * (a - cx), cy + 2.0 / 3.0 * (b - cy));
let (c2x, c2y) = (x + 2.0 / 3.0 * (a - x), y + 2.0 / 3.0 * (b - y));
c.cubic_to(c1x, c1y, c2x, c2y, x, y);
(cx, cy) = (x, y);
}
path::Seg::Cubic(a, b, e, f, x, y) => {
c.cubic_to(a, b, e, f, x, y);
(cx, cy) = (x, y);
}
path::Seg::Close => {
c.close_path();
}
}
}
}
fn rgb(c: [u8; 4]) -> (f32, f32, f32) {
(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0)
}
/// The alpha a paint is drawn with (a gradient's stops share one: the average of theirs).
fn paint_alpha(p: &DPaint) -> u8 {
match p {
DPaint::Solid { c } => c[3],
DPaint::Linear { stops, .. } | DPaint::Radial { stops, .. } => {
if stops.is_empty() {
255
} else {
(stops.iter().map(|(_, c)| c[3] as u32).sum::<u32>() / stops.len() as u32) as u8
}
}
}
}
fn set_paint(w: &mut Writer, c: &mut Content, p: &DPaint, full: Tf, stroke: bool) {
match p {
DPaint::Solid { c: col } => {
let (r, g, b) = rgb(*col);
if stroke {
c.set_stroke_rgb(r, g, b);
} else {
c.set_fill_rgb(r, g, b);
}
}
_ => {
let n = w.pattern(p, full);
if stroke {
c.set_stroke_color_space(pdf_writer::types::ColorSpaceOperand::Pattern);
c.set_stroke_pattern(None, Name(n.as_bytes()));
} else {
c.set_fill_color_space(pdf_writer::types::ColorSpaceOperand::Pattern);
c.set_fill_pattern(None, Name(n.as_bytes()));
}
}
}
}
/// The document as PDF: every page at its size, vectors as vectors, real text, pictures with their alpha.
pub fn pdf(doc: &Document, book: &FontBook) -> Result<Vec<u8>, ExportError> {
let lists: Vec<DisplayList> = doc.pages.iter().map(|p| display::build(doc, p, book)).collect();
check_fonts(&lists, book)?;
let mut w = Writer {
pdf: Pdf::new(),
next: 0,
book,
fonts: BTreeMap::new(),
images: BTreeMap::new(),
alphas: BTreeMap::new(),
patterns: Vec::new(),
forms: Vec::new(),
};
let catalog = w.alloc();
let pages_id = w.alloc();
let mut page_refs = Vec::new();
let mut contents = Vec::new();
for list in &lists {
let flip: Tf = [1.0, 0.0, 0.0, -1.0, 0.0, list.height];
let mut stack: Vec<(Content, f32)> = vec![(Content::new(), 1.0)];
{
let c = &mut stack[0].0;
c.transform(flip);
if let Some(bg) = list.background {
let (r, g, b) = rgb(bg);
c.set_fill_rgb(r, g, b);
c.rect(0.0, 0.0, list.width, list.height);
c.fill_nonzero();
}
}
for item in &list.items {
match item {
Item::Push { opacity } => stack.push((Content::new(), *opacity)),
Item::Pop => {
if stack.len() > 1 {
let (inner, opacity) = stack.pop().unwrap();
let r = w.alloc();
let n = format!("X{}", w.forms.len());
w.forms.push((r, n.clone(), inner.finish().to_vec()));
let a = w.alpha((opacity * 255.0).round() as u8, (opacity * 255.0).round() as u8);
let c = &mut stack.last_mut().unwrap().0;
c.save_state();
c.set_parameters(Name(a.as_bytes()));
c.x_object(Name(n.as_bytes()));
c.restore_state();
}
}
Item::Fill { d, t, paint, even_odd, .. } => {
let full = display::mul(flip, *t);
let alpha = paint_alpha(paint);
let a = (alpha < 255).then(|| w.alpha(alpha, 255));
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
c.save_state();
if let Some(a) = &a {
c.set_parameters(Name(a.as_bytes()));
}
c.transform(*t);
set_paint(&mut w, &mut c, paint, full, false);
path_ops(&mut c, d);
if *even_odd {
c.fill_even_odd();
} else {
c.fill_nonzero();
}
c.restore_state();
stack.last_mut().unwrap().0 = c;
}
Item::Stroke { d, t, paint, width, cap, join, dash, .. } => {
let full = display::mul(flip, *t);
let alpha = paint_alpha(paint);
let a = (alpha < 255).then(|| w.alpha(255, alpha));
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
c.save_state();
if let Some(a) = &a {
c.set_parameters(Name(a.as_bytes()));
}
c.transform(*t);
set_paint(&mut w, &mut c, paint, full, true);
c.set_line_width(*width);
c.set_line_cap(match cap {
Cap::Butt => pdf_writer::types::LineCapStyle::ButtCap,
Cap::Round => pdf_writer::types::LineCapStyle::RoundCap,
Cap::Square => pdf_writer::types::LineCapStyle::ProjectingSquareCap,
});
c.set_line_join(match join {
Join::Miter => pdf_writer::types::LineJoinStyle::MiterJoin,
Join::Round => pdf_writer::types::LineJoinStyle::RoundJoin,
Join::Bevel => pdf_writer::types::LineJoinStyle::BevelJoin,
});
c.set_miter_limit(10.0);
if dash.len() >= 2 && dash.iter().any(|v| *v > 0.0) {
c.set_dash_pattern(dash.iter().copied(), 0.0);
}
path_ops(&mut c, d);
c.stroke();
c.restore_state();
stack.last_mut().unwrap().0 = c;
}
Item::Image { asset, t, clip, clip_t, .. } => {
let Some(r) = doc.assets.get(asset) else { continue };
let (pw, ph) = (r.width as f32, r.height as f32);
let n = w.image(asset);
let c = &mut stack.last_mut().unwrap().0;
c.save_state();
let rel = match clip {
Some(cd) => {
c.transform(*clip_t);
path_ops(c, cd);
c.clip_nonzero();
c.end_path();
display::mul(display::invert(*clip_t), *t)
}
None => *t,
};
c.transform(rel);
// The image's unit square, its first row at the top (the page runs y down here).
c.transform([pw, 0.0, 0.0, -ph, 0.0, ph]);
c.x_object(Name(n.as_bytes()));
c.restore_state();
}
Item::Text { t, color, size, glyphs, .. } => {
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
c.save_state();
if color[3] < 255 {
let a = w.alpha(color[3], 255);
c.set_parameters(Name(a.as_bytes()));
}
c.transform(*t);
let (r, g, b) = rgb(*color);
c.set_fill_rgb(r, g, b);
c.begin_text();
// Runs of glyphs that share a line and a font.
let mut i = 0;
while i < glyphs.len() {
let font = glyphs[i].font;
let y = glyphs[i].y;
let mut j = i + 1;
while j < glyphs.len() && glyphs[j].font == font && glyphs[j].y == y {
j += 1;
}
let run = &glyphs[i..j];
let fname = w.font(font);
let f = book.font(font);
let face = ttf_parser::Face::parse(&f.data, f.index).ok();
let width_of = |gid: u16| -> f32 {
face.as_ref()
.and_then(|fc| fc.glyph_hor_advance(ttf_parser::GlyphId(gid)))
.map(|a| a as f32 * 1000.0 / f.units_per_em)
.unwrap_or(0.0)
};
let cids: Vec<u16> = {
let u = &mut w.fonts.get_mut(&font).unwrap().1;
run.iter()
.map(|g| {
let cid = if u.subset { u.remapper.remap(g.gid) } else { g.gid };
let e = u.glyphs.entry(cid).or_insert_with(|| (g.gid, String::new()));
if e.1.is_empty() {
e.1.push_str(&g.text);
}
cid
})
.collect()
};
c.set_font(Name(fname.as_bytes()), *size);
c.set_text_matrix([1.0, 0.0, 0.0, -1.0, run[0].x, y]);
let mut items_buf: Vec<(Vec<u8>, f32)> = Vec::new();
let mut x = run[0].x;
for (k, g) in run.iter().enumerate() {
// Where the PDF would put the next glyph vs where the layout put it.
let adv = width_of(g.gid) * size / 1000.0;
let next_x = run.get(k + 1).map(|n| n.x).unwrap_or(x + adv);
let adjust = (next_x - (x + adv)) * 1000.0 / size;
items_buf.push((cids[k].to_be_bytes().to_vec(), adjust));
x = next_x;
}
{
let mut sp = c.show_positioned();
let mut its = sp.items();
for (bytes, adjust) in &items_buf {
its.show(Str(bytes));
if adjust.abs() > 0.01 {
its.adjust(-adjust);
}
}
}
i = j;
}
c.end_text();
c.restore_state();
stack.last_mut().unwrap().0 = c;
}
}
}
while stack.len() > 1 {
let (inner, opacity) = stack.pop().unwrap();
let r = w.alloc();
let n = format!("X{}", w.forms.len());
w.forms.push((r, n.clone(), inner.finish().to_vec()));
let a = w.alpha((opacity * 255.0).round() as u8, (opacity * 255.0).round() as u8);
let c = &mut stack.last_mut().unwrap().0;
c.save_state();
c.set_parameters(Name(a.as_bytes()));
c.x_object(Name(n.as_bytes()));
c.restore_state();
}
let page_ref = w.alloc();
let content_ref = w.alloc();
page_refs.push(page_ref);
contents.push((page_ref, content_ref, stack.pop().unwrap().0.finish().to_vec(), list.width, list.height));
}
type FontJob = (FontKey, Ref, bool, subsetter::GlyphRemapper, BTreeMap<u16, (u16, String)>);
let font_list: Vec<FontJob> =
w.fonts.iter().map(|(k, (r, u))| (*k, *r, u.subset, u.remapper.clone(), u.glyphs.clone())).collect();
for (key, type0, subset, remapper, glyphs) in font_list {
write_font(&mut w, key, type0, subset, &remapper, &glyphs)?;
}
let images: Vec<(String, Ref)> = w.images.iter().map(|(a, (r, _))| (a.clone(), *r)).collect();
for (asset, r) in images {
let raster = &doc.assets[&asset];
let mut rgb_data = Vec::with_capacity(raster.rgba.len() / 4 * 3);
let mut alpha = Vec::with_capacity(raster.rgba.len() / 4);
for p in raster.rgba.as_chunks::<4>().0 {
rgb_data.extend_from_slice(&p[..3]);
alpha.push(p[3]);
}
let has_alpha = alpha.iter().any(|a| *a < 255);
let mask_ref = has_alpha.then(|| w.alloc());
let data = deflate(&rgb_data);
let mut im = w.pdf.image_xobject(r, &data);
im.filter(Filter::FlateDecode);
im.width(raster.width as i32);
im.height(raster.height as i32);
im.color_space().device_rgb();
im.bits_per_component(8);
if let Some(m) = mask_ref {
im.s_mask(m);
}
im.finish();
if let Some(m) = mask_ref {
let data = deflate(&alpha);
let mut sm = w.pdf.image_xobject(m, &data);
sm.filter(Filter::FlateDecode);
sm.width(raster.width as i32);
sm.height(raster.height as i32);
sm.color_space().device_gray();
sm.bits_per_component(8);
sm.finish();
}
}
let alphas: Vec<((u8, u8), Ref)> = w.alphas.iter().map(|(k, (r, _))| (*k, *r)).collect();
for ((fa, sa), r) in alphas {
w.pdf.ext_graphics(r).non_stroking_alpha(fa as f32 / 255.0).stroking_alpha(sa as f32 / 255.0);
}
let patterns = std::mem::take(&mut w.patterns);
for (r, _, p, full) in &patterns {
let shading = w.alloc();
let func = w.alloc();
let (stops, kind, coords): (&Vec<(f32, [u8; 4])>, _, Vec<f32>) = match p {
DPaint::Linear { x1, y1, x2, y2, stops } => {
(stops, pdf_writer::types::FunctionShadingType::Axial, vec![*x1, *y1, *x2, *y2])
}
DPaint::Radial { cx, cy, r, stops } => {
(stops, pdf_writer::types::FunctionShadingType::Radial, vec![*cx, *cy, 0.0, *cx, *cy, *r])
}
DPaint::Solid { .. } => continue,
};
write_stops(&mut w, func, stops);
{
let mut sh = w.pdf.function_shading(shading);
sh.shading_type(kind);
sh.color_space().device_rgb();
sh.coords(coords);
sh.function(func);
sh.extend([true, true]);
}
let mut pat = w.pdf.shading_pattern(*r);
pat.pair(Name(b"Shading"), shading);
pat.matrix(*full);
}
w.patterns = patterns;
let table = w.table();
let forms = std::mem::take(&mut w.forms);
let (pw, ph) = lists.first().map(|l| (l.width, l.height)).unwrap_or((1.0, 1.0));
for (r, _, content) in &forms {
let data = deflate(content);
let mut f = w.pdf.form_xobject(*r, &data);
f.filter(Filter::FlateDecode);
let maxw = lists.iter().map(|l| l.width).fold(pw, f32::max);
let maxh = lists.iter().map(|l| l.height).fold(ph, f32::max);
f.bbox(PRect::new(-1.0, -1.0, maxw + 1.0, maxh + 1.0));
f.group().transparency().isolated(true);
let mut res = f.resources();
write_resources(&table, &mut res);
res.finish();
f.finish();
}
w.forms = forms;
for (page_ref, content_ref, content, width, height) in &contents {
let data = deflate(content);
w.pdf.stream(*content_ref, &data).filter(Filter::FlateDecode);
let mut page = w.pdf.page(*page_ref);
page.media_box(PRect::new(0.0, 0.0, *width, *height));
page.parent(pages_id);
page.contents(*content_ref);
let mut res = page.resources();
write_resources(&table, &mut res);
res.finish();
page.finish();
}
w.pdf.pages(pages_id).kids(page_refs.iter().copied()).count(page_refs.len() as i32);
w.pdf.catalog(catalog).pages(pages_id);
let info = w.alloc();
w.pdf.document_info(info).producer(pdf_writer::TextStr("Pictor"));
Ok(w.pdf.finish())
}
fn write_stops(w: &mut Writer, func: Ref, stops: &[(f32, [u8; 4])]) {
let col = |c: [u8; 4]| {
let (r, g, b) = rgb(c);
[r, g, b]
};
let mut stops: Vec<(f32, [u8; 4])> = stops.to_vec();
if stops.is_empty() {
stops.push((0.0, [0, 0, 0, 255]));
}
if stops.len() == 1 {
stops.push(stops[0]);
}
if stops.len() == 2 {
w.pdf.exponential_function(func).domain([0.0, 1.0]).c0(col(stops[0].1)).c1(col(stops[1].1)).n(1.0);
return;
}
// Stitch one exponential function per pair of stops.
let mut parts = Vec::new();
for pair in stops.windows(2) {
let r = w.alloc();
w.pdf.exponential_function(r).domain([0.0, 1.0]).c0(col(pair[0].1)).c1(col(pair[1].1)).n(1.0);
parts.push(r);
}
let bounds: Vec<f32> = stops[1..stops.len() - 1].iter().map(|s| s.0).collect();
let encode: Vec<f32> = parts.iter().flat_map(|_| [0.0, 1.0]).collect();
let mut s = w.pdf.stitching_function(func);
s.domain([0.0, 1.0]);
s.functions(parts);
s.bounds(bounds);
s.encode(encode);
}
/// Writes a Type 0 font: the font program (a subset when its licence allows), its descriptor, widths and the
/// ToUnicode map. CIDs are the subset's glyph ids (or the font's own when it is embedded whole), so CIDToGIDMap is
/// the identity.
fn write_font(
w: &mut Writer,
key: FontKey,
type0: Ref,
subset: bool,
remapper: &subsetter::GlyphRemapper,
glyphs: &BTreeMap<u16, (u16, String)>,
) -> Result<(), ExportError> {
let f = w.book.font(key);
let face = ttf_parser::Face::parse(&f.data, f.index).map_err(|_| ExportError::FontBroken(f.family.clone()))?;
let program: Vec<u8> = if subset {
subsetter::subset(&f.data, f.index, remapper).map_err(|_| ExportError::FontBroken(f.family.clone()))?
} else {
f.data.to_vec()
};
let cid_ref = w.alloc();
let desc_ref = w.alloc();
let file_ref = w.alloc();
let cmap_ref = w.alloc();
// A subset tag from the glyph set, so two subsets of one font get different names.
let tag: String = {
use sha2::Digest;
let mut h = sha2::Sha256::new();
for (cid, (gid, _)) in glyphs {
h.update(cid.to_be_bytes());
h.update(gid.to_be_bytes());
}
h.update(f.post_script_name.as_bytes());
h.finalize().iter().take(6).map(|b| (b'A' + b % 26) as char).collect()
};
let ps: String = f.post_script_name.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
let ps = if ps.is_empty() { "Font".to_string() } else { ps };
let base = if subset { format!("{tag}+{ps}") } else { ps };
let s = 1000.0 / f.units_per_em;
w.pdf
.type0_font(type0)
.base_font(Name(base.as_bytes()))
.encoding_predefined(Name(b"Identity-H"))
.descendant_font(cid_ref)
.to_unicode(cmap_ref);
{
let mut cid = w.pdf.cid_font(cid_ref);
cid.subtype(if f.cff { pdf_writer::types::CidFontType::Type0 } else { pdf_writer::types::CidFontType::Type2 });
cid.base_font(Name(base.as_bytes()));
cid.system_info(pdf_writer::types::SystemInfo {
registry: Str(b"Adobe"),
ordering: Str(b"Identity"),
supplement: 0,
});
cid.font_descriptor(desc_ref);
cid.default_width(0.0);
if !f.cff {
cid.cid_to_gid_map_predefined(Name(b"Identity"));
}
{
let mut ws = cid.widths();
for (cid_v, (gid, _)) in glyphs {
let adv = face.glyph_hor_advance(ttf_parser::GlyphId(*gid)).unwrap_or(0) as f32 * s;
ws.consecutive(*cid_v, [adv]);
}
}
cid.finish();
}
let bbox = face.global_bounding_box();
{
let mut fd = w.pdf.font_descriptor(desc_ref);
fd.name(Name(base.as_bytes()));
let mut flags = pdf_writer::types::FontFlags::SYMBOLIC;
if f.italic {
flags |= pdf_writer::types::FontFlags::ITALIC;
}
fd.flags(flags);
fd.bbox(PRect::new(bbox.x_min as f32 * s, bbox.y_min as f32 * s, bbox.x_max as f32 * s, bbox.y_max as f32 * s));
fd.italic_angle(face.italic_angle());
fd.ascent(f.ascender * s);
fd.descent(f.descender * s);
fd.cap_height(f.cap_height * s);
fd.stem_v(80.0 + (f.weight as f32 - 400.0).max(0.0) / 5.0);
if f.cff {
fd.font_file3(file_ref);
} else {
fd.font_file2(file_ref);
}
fd.finish();
}
{
let data = deflate(&program);
let mut st = w.pdf.stream(file_ref, &data);
st.filter(Filter::FlateDecode);
if f.cff {
st.pair(Name(b"Subtype"), Name(b"OpenType"));
} else {
st.pair(Name(b"Length1"), program.len() as i32);
}
st.finish();
}
{
let mut cmap = pdf_writer::types::UnicodeCmap::new(
Name(b"Custom"),
pdf_writer::types::SystemInfo { registry: Str(b"Adobe"), ordering: Str(b"UCS"), supplement: 0 },
);
for (cid, (_, text)) in glyphs {
if !text.is_empty() {
cmap.pair_with_multiple(*cid, text.chars());
}
}
let data = cmap.finish();
w.pdf.cmap(cmap_ref, &data);
}
Ok(())
}