mod core_fonts;
mod draw;
mod file;
mod fonts;
mod image;
mod object;
mod pages;
mod resources;
mod state;
mod tex;
mod text;
mod type42;
mod writer;
use pltrs_core::path::convert::{SimplifySettings, SketchParams, StringCodes, StringOptions};
use pltrs_core::{Affine2D, Bbox, Path, Point, Rgba};
use pltrs_text::tex::{TexError, TexText};
use pltrs_text::{AfmDirectory, TextRun};
pub use self::file::{PdfFont, PdfHatch};
pub use self::object::{Obj as PdfObject, line as pdf_line, text_string as pdf_text_string};
pub use self::resources::{
MarkerPaint as PdfMarkerPaint, ShadingColors as PdfShadingColors,
TemplatePaint as PdfTemplatePaint,
};
use self::fonts::FontNames;
use self::object::{Obj, text_string};
use self::pages::{Note, PageParents, Pages, media_box};
use self::resources::{ResourceIds, Resources};
use self::state::{PdfState, StateStack};
use self::tex::DviFonts;
use self::writer::PdfWriter;
use crate::collection::PathCollection;
use crate::gc::GraphicsContext;
use crate::image::RgbaImage;
use crate::renderer::Renderer;
use crate::vector::{
CharacterTracker, FontCache, FontType, Metadata, Problems, VectorError, check_canvas,
};
#[derive(Clone, Debug, PartialEq)]
pub struct PdfOptions {
pub compression: u8,
pub inherit_color: bool,
pub metadata: Metadata,
pub simplify: SimplifySettings,
pub composite_images: bool,
pub fonttype: FontType,
pub subset_fonttype: FontType,
pub core_fonts: bool,
}
impl Default for PdfOptions {
fn default() -> Self {
Self {
compression: 6,
inherit_color: false,
metadata: Metadata::default(),
simplify: SimplifySettings::default(),
composite_images: true,
fonttype: FontType::Type3,
subset_fonttype: FontType::Type3,
core_fonts: false,
}
}
}
impl PdfOptions {
pub fn afm_directory(&self) -> Option<AfmDirectory> {
self.core_fonts.then_some(AfmDirectory::PdfCore)
}
}
#[derive(Clone, Copy, Debug)]
struct Ids {
root: u32,
pages: u32,
resources: ResourceIds,
resource_dictionary: u32,
}
fn path_ops(
path: &Path,
transform: Affine2D,
clip: Option<Bbox>,
simplify: Option<f64>,
sketch: Option<SketchParams>,
) -> Vec<u8> {
path.convert_to_string(&StringOptions {
transform,
clip,
simplify,
sketch,
precision: 6,
codes: StringCodes::PDF,
postfix: true,
})
.into_bytes()
}
#[derive(Debug)]
pub struct PdfRenderer {
writer: PdfWriter,
width: f64,
height: f64,
image_dpi: f64,
ids: Ids,
pages: Pages,
page_open: bool,
resources: Resources,
states: StateStack,
font_names: FontNames,
dvi_fonts: DviFonts,
tracker: CharacterTracker,
fonts: FontCache,
options: PdfOptions,
generation: u64,
group_depth: usize,
problems: Problems,
info: Option<u32>,
}
impl PdfRenderer {
pub fn new(
width: f64,
height: f64,
image_dpi: f64,
options: PdfOptions,
) -> Result<Self, VectorError> {
check_canvas(width, height, image_dpi)?;
let mut document = Self::document(options)?;
document.new_page(width, height, image_dpi)?;
Ok(document)
}
pub fn document(options: PdfOptions) -> Result<Self, VectorError> {
let mut writer = PdfWriter::new(options.compression);
let root = writer.reserve();
let pages = writer.reserve();
let resource_ids = ResourceIds {
fonts: writer.reserve(),
ext_gstates: writer.reserve(),
patterns: writer.reserve(),
shadings: writer.reserve(),
xobjects: writer.reserve(),
};
let resource_dictionary = writer.reserve();
writer.write_object(
root,
&Obj::dict([("Type", Obj::name("Catalog")), ("Pages", Obj::Ref(pages))]),
)?;
let procsets = ["PDF", "Text", "ImageB", "ImageC", "ImageI"].map(Obj::name);
writer.write_object(
resource_dictionary,
&Obj::dict([
("Font", Obj::Ref(resource_ids.fonts)),
("XObject", Obj::Ref(resource_ids.xobjects)),
("ExtGState", Obj::Ref(resource_ids.ext_gstates)),
("Pattern", Obj::Ref(resource_ids.patterns)),
("Shading", Obj::Ref(resource_ids.shadings)),
("ProcSet", Obj::Array(procsets.to_vec())),
]),
)?;
let states = StateStack::new(options.inherit_color);
Ok(Self {
writer,
width: 0.0,
height: 0.0,
image_dpi: 72.0,
ids: Ids {
root,
pages,
resources: resource_ids,
resource_dictionary,
},
pages: Pages::default(),
page_open: false,
resources: Resources::default(),
states,
font_names: FontNames::default(),
dvi_fonts: DviFonts::default(),
tracker: CharacterTracker::new(options.subset_fonttype.subset_size()),
fonts: FontCache::default(),
options,
generation: 0,
group_depth: 0,
problems: Problems::default(),
info: None,
})
}
pub fn new_page(&mut self, width: f64, height: f64, image_dpi: f64) -> Result<(), VectorError> {
self.new_page_spanning(width, height, image_dpi, media_box(width, height))
}
pub fn new_page_spanning(
&mut self,
width: f64,
height: f64,
image_dpi: f64,
media_box: Obj,
) -> Result<(), VectorError> {
if !(image_dpi.is_finite() && image_dpi > 0.0) {
return Err(VectorError::InvalidCanvas {
width,
height,
dpi: image_dpi,
});
}
self.end_page()?;
let parents = PageParents {
pages: self.ids.pages,
resources: self.ids.resource_dictionary,
};
let contents = self.pages.start(&mut self.writer, parents, media_box)?;
let length = self.writer.reserve();
self.writer
.begin_stream(contents, Some(length), Vec::new(), None);
self.writer
.output(&[Obj::name("DeviceRGB"), Obj::op("CS")])?;
self.writer
.output(&[Obj::name("DeviceRGB"), Obj::op("cs")])?;
self.writer.output(&[Obj::Int(1), Obj::op("j")])?;
self.states = StateStack::new(self.options.inherit_color);
(self.width, self.height, self.image_dpi) = (width, height, image_dpi);
self.page_open = true;
Ok(())
}
pub fn attach_note(&mut self, text: &str, rect: [f64; 4]) {
self.attach_note_objects(text_string(text), Obj::reals(rect));
}
pub fn attach_note_objects(&mut self, contents: Obj, rect: Obj) {
self.pages.add_note(Note { contents, rect });
}
pub fn page_count(&self) -> usize {
self.pages.len()
}
pub fn image_names(&self) -> Vec<String> {
self.resources.image_names().map(str::to_owned).collect()
}
pub fn metadata_mut(&mut self) -> &mut Metadata {
&mut self.options.metadata
}
pub fn afm_directory(&self) -> Option<AfmDirectory> {
self.options.afm_directory()
}
fn end_page(&mut self) -> Result<(), VectorError> {
if !self.page_open {
return Ok(());
}
self.restore_gc()?;
self.writer.end_stream()?;
self.page_open = false;
Ok(())
}
pub fn finish(mut self) -> Result<Vec<u8>, VectorError> {
self.finalize()?;
self.close()
}
pub fn restore_gc(&mut self) -> Result<(), VectorError> {
let restore = self.states.finish();
self.writer.output(&restore)
}
fn output(&mut self, objects: &[Obj]) {
let result = self.writer.output(objects);
self.problems.record(result);
}
pub fn check_gc(&mut self, gc: &GraphicsContext, fill: Option<Rgba>) {
let target = PdfState::from_gc(gc, fill, self.generation);
let cmds = self.states.delta(&target, &mut self.resources);
if !cmds.is_empty() {
self.output(&cmds);
}
}
fn begin_draw(&mut self) {
if self.group_depth == 0 {
self.generation += 1;
}
}
fn canvas(&self) -> Bbox {
Bbox::from_extents(0.0, 0.0, self.width * 72.0, self.height * 72.0)
}
}
impl Renderer for PdfRenderer {
fn canvas_size(&self) -> (f64, f64) {
(self.width * 72.0, self.height * 72.0)
}
fn dpi(&self) -> f64 {
self.image_dpi
}
fn points_to_pixels(&self, points: f64) -> f64 {
points
}
fn draw_path(
&mut self,
gc: &GraphicsContext,
path: &Path,
transform: &Affine2D,
fill: Option<Rgba>,
) {
self.begin_draw();
self.pdf_path(gc, path, *transform, fill);
}
fn draw_markers(
&mut self,
gc: &GraphicsContext,
marker: &Path,
marker_transform: &Affine2D,
path: &Path,
transform: &Affine2D,
fill: Option<Rgba>,
) {
self.begin_draw();
self.pdf_markers(gc, marker, *marker_transform, path, *transform, fill);
}
fn draw_path_collection(&mut self, gc: &GraphicsContext, collection: &PathCollection<'_>) {
self.begin_draw();
self.pdf_path_collection(gc, collection);
}
fn draw_gouraud_triangles(
&mut self,
gc: &GraphicsContext,
triangles: &[[Point; 3]],
colors: &[[Rgba; 3]],
transform: &Affine2D,
) {
self.begin_draw();
self.pdf_gouraud_triangles(gc, triangles, colors, *transform);
}
fn draw_image(
&mut self,
gc: &GraphicsContext,
origin: Point,
image: &RgbaImage,
transform: Option<&Affine2D>,
) {
self.begin_draw();
self.pdf_image(gc, origin, image, transform.copied());
}
fn draw_text(&mut self, gc: &GraphicsContext, run: &TextRun, origin: Point, angle: f64) {
self.begin_draw();
self.pdf_text(gc, run, origin, angle);
}
fn draw_tex(
&mut self,
gc: &GraphicsContext,
_run: &TextRun,
tex: &TexText,
origin: Point,
angle: f64,
) -> Result<(), TexError> {
self.begin_draw();
self.pdf_tex(gc, tex, origin, angle)
}
fn open_group(&mut self, _name: &str, _gid: Option<&str>) {
self.group_depth += 1;
self.generation += 1;
}
fn close_group(&mut self, _name: &str) {
self.group_depth = self.group_depth.saturating_sub(1);
self.generation += 1;
}
fn open_part_group(&mut self, _name: &str, _gid: Option<&str>) {
self.group_depth += 1;
}
fn close_part_group(&mut self, _name: &str) {
self.group_depth = self.group_depth.saturating_sub(1);
}
fn option_image_nocomposite(&self) -> bool {
!self.options.composite_images
}
fn option_scale_image(&self) -> bool {
true
}
fn image_magnification(&self) -> f64 {
self.image_dpi / 72.0
}
}
#[cfg(test)]
mod tests;