diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/export/pdf.rs | 95 | ||||
| -rw-r--r-- | src/image.rs | 105 |
2 files changed, 157 insertions, 43 deletions
diff --git a/src/export/pdf.rs b/src/export/pdf.rs index 8df31660..100a53f9 100644 --- a/src/export/pdf.rs +++ b/src/export/pdf.rs @@ -10,13 +10,14 @@ use pdf_writer::types::{ ActionType, AnnotationType, CidFontType, FontFlags, SystemInfo, UnicodeCmap, }; use pdf_writer::{Content, Filter, Finish, Name, PdfWriter, Rect, Ref, Str, TextStr}; +use svg2pdf::{convert_tree_into, Options}; use ttf_parser::{name_id, GlyphId, Tag}; use super::subset; use crate::font::{find_name, FaceId, FontStore}; use crate::frame::{Element, Frame, Geometry, Group, Shape, Stroke, Text}; use crate::geom::{self, Color, Em, Length, Paint, Point, Size, Transform}; -use crate::image::{Image, ImageId, ImageStore}; +use crate::image::{Image, ImageId, ImageStore, RasterImage}; use crate::Context; /// Export a collection of frames into a PDF file. @@ -90,7 +91,7 @@ impl<'a> PdfExporter<'a> { let postscript_name = find_name(ttf.names(), name_id::POST_SCRIPT_NAME) .unwrap_or_else(|| "unknown".to_string()); - let base_font = format!("ABCDEF+{}", postscript_name); + let base_font = format_eco!("ABCDEF+{}", postscript_name); let base_font = Name(base_font.as_bytes()); let cmap_name = Name(b"Custom"); let system_info = SystemInfo { @@ -218,44 +219,58 @@ impl<'a> PdfExporter<'a> { let height = img.height(); // Add the primary image. - if let Ok((data, filter, has_color)) = encode_image(img) { - let mut image = self.writer.image_xobject(image_ref, &data); - image.filter(filter); - image.width(width as i32); - image.height(height as i32); - image.bits_per_component(8); - - let space = image.color_space(); - if has_color { - space.device_rgb(); - } else { - space.device_gray(); + match img { + Image::Raster(img) => { + if let Ok((data, filter, has_color)) = encode_image(img) { + let mut image = self.writer.image_xobject(image_ref, &data); + image.filter(filter); + image.width(width as i32); + image.height(height as i32); + image.bits_per_component(8); + + let space = image.color_space(); + if has_color { + space.device_rgb(); + } else { + space.device_gray(); + } + + // Add a second gray-scale image containing the alpha values if + // this image has an alpha channel. + if img.buf.color().has_alpha() { + let (alpha_data, alpha_filter) = encode_alpha(img); + let mask_ref = self.alloc.bump(); + image.s_mask(mask_ref); + image.finish(); + + let mut mask = + self.writer.image_xobject(mask_ref, &alpha_data); + mask.filter(alpha_filter); + mask.width(width as i32); + mask.height(height as i32); + mask.color_space().device_gray(); + mask.bits_per_component(8); + } + } else { + // TODO: Warn that image could not be encoded. + self.writer + .image_xobject(image_ref, &[]) + .width(0) + .height(0) + .bits_per_component(1) + .color_space() + .device_gray(); + } } - - // Add a second gray-scale image containing the alpha values if - // this image has an alpha channel. - if img.buf.color().has_alpha() { - let (alpha_data, alpha_filter) = encode_alpha(img); - let mask_ref = self.alloc.bump(); - image.s_mask(mask_ref); - image.finish(); - - let mut mask = self.writer.image_xobject(mask_ref, &alpha_data); - mask.filter(alpha_filter); - mask.width(width as i32); - mask.height(height as i32); - mask.color_space().device_gray(); - mask.bits_per_component(8); + Image::Svg(img) => { + let next_ref = convert_tree_into( + &img.0, + Options::default(), + &mut self.writer, + image_ref, + ); + self.alloc = next_ref; } - } else { - // TODO: Warn that image could not be encoded. - self.writer - .image_xobject(image_ref, &[]) - .width(0) - .height(0) - .bits_per_component(1) - .color_space() - .device_gray(); } } } @@ -636,7 +651,7 @@ impl<'a> PageExporter<'a> { /// whether the image has color. /// /// Skips the alpha channel as that's encoded separately. -fn encode_image(img: &Image) -> ImageResult<(Vec<u8>, Filter, bool)> { +fn encode_image(img: &RasterImage) -> ImageResult<(Vec<u8>, Filter, bool)> { Ok(match (img.format, &img.buf) { // 8-bit gray JPEG. (ImageFormat::Jpeg, DynamicImage::ImageLuma8(_)) => { @@ -677,7 +692,7 @@ fn encode_image(img: &Image) -> ImageResult<(Vec<u8>, Filter, bool)> { } /// Encode an image's alpha channel if present. -fn encode_alpha(img: &Image) -> (Vec<u8>, Filter) { +fn encode_alpha(img: &RasterImage) -> (Vec<u8>, Filter) { let pixels: Vec<_> = img.buf.pixels().map(|(_, _, Rgba([_, _, _, a]))| a).collect(); (deflate(&pixels), Filter::FlateDecode) } diff --git a/src/image.rs b/src/image.rs index 512b24b1..f6574045 100644 --- a/src/image.rs +++ b/src/image.rs @@ -9,6 +9,7 @@ use std::rc::Rc; use image::io::Reader as ImageReader; use image::{DynamicImage, GenericImageView, ImageFormat}; use serde::{Deserialize, Serialize}; +use usvg::{Error as USvgError, Tree}; use crate::loading::{FileHash, Loader}; @@ -88,14 +89,112 @@ impl ImageStore { } /// A loaded image. -pub struct Image { +#[derive(Debug)] +pub enum Image { + Raster(RasterImage), + Svg(Svg), +} + +impl Image { + /// Parse an image from raw data. This will prioritize SVG images and then + /// try to decode a supported raster format. + pub fn parse(data: &[u8]) -> io::Result<Self> { + match Svg::parse(data) { + Ok(svg) => Ok(Self::Svg(svg)), + Err(e) if e.kind() == io::ErrorKind::InvalidData => { + Ok(Self::Raster(RasterImage::parse(data)?)) + } + Err(e) => Err(e), + } + } + + /// The width of the image in pixels. + pub fn width(&self) -> u32 { + match self { + Self::Raster(image) => image.width(), + Self::Svg(image) => image.width(), + } + } + + /// The height of the image in pixels. + pub fn height(&self) -> u32 { + match self { + Self::Raster(image) => image.height(), + Self::Svg(image) => image.height(), + } + } + + pub fn is_vector(&self) -> bool { + match self { + Self::Raster(_) => false, + Self::Svg(_) => true, + } + } +} + +/// An SVG image, supported through the usvg crate. +pub struct Svg(pub Tree); + +impl Svg { + /// Parse an SVG file from a data buffer. This also handles `.svgz` + /// compressed files. + pub fn parse(data: &[u8]) -> io::Result<Self> { + let usvg_opts = usvg::Options::default(); + let tree = Tree::from_data(data, &usvg_opts.to_ref()).map_err(|e| match e { + USvgError::NotAnUtf8Str => { + io::Error::new(io::ErrorKind::InvalidData, "file is not valid utf-8") + } + USvgError::MalformedGZip => io::Error::new( + io::ErrorKind::InvalidData, + "could not extract gzipped SVG", + ), + USvgError::ElementsLimitReached => io::Error::new( + io::ErrorKind::Other, + "SVG file has more than 1 million elements", + ), + USvgError::InvalidSize => io::Error::new( + io::ErrorKind::InvalidData, + "SVG width or height not greater than zero", + ), + USvgError::ParsingFailed(error) => io::Error::new( + io::ErrorKind::InvalidData, + format!("SVG parsing error: {}", error.to_string()), + ), + })?; + + Ok(Self(tree)) + } + + /// The width of the image in rounded-up nominal SVG pixels. + pub fn width(&self) -> u32 { + self.0.svg_node().size.width().ceil() as u32 + } + + /// The height of the image in rounded-up nominal SVG pixels. + pub fn height(&self) -> u32 { + self.0.svg_node().size.height().ceil() as u32 + } +} + +impl Debug for Svg { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + f.debug_struct("Svg") + .field("width", &self.0.svg_node().size.width()) + .field("height", &self.0.svg_node().size.height()) + .field("viewBox", &self.0.svg_node().view_box) + .finish() + } +} + +/// A raster image, supported through the image crate. +pub struct RasterImage { /// The original format the image was encoded in. pub format: ImageFormat, /// The decoded image. pub buf: DynamicImage, } -impl Image { +impl RasterImage { /// Parse an image from raw data in a supported format (PNG or JPEG). /// /// The image format is determined automatically. @@ -124,7 +223,7 @@ impl Image { } } -impl Debug for Image { +impl Debug for RasterImage { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_struct("Image") .field("format", &self.format) |
