use std::collections::BTreeMap;
use lopdf::StringFormat;
use serde_derive::{Deserialize, Serialize};
use crate::{
date::OffsetDateTime,
deserialize::PageState,
graphics::Rect,
image_types::RawImage,
matrix::CurTransMat,
units::{Pt, Px},
Op, PdfResources,
};
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "type", content = "data")]
pub enum XObject {
Image(RawImage),
Form(FormXObject),
External(ExternalXObject),
}
impl XObject {
pub fn get_width_height(&self) -> Option<(Px, Px)> {
match self {
XObject::Image(raw_image) => Some((Px(raw_image.width), Px(raw_image.height))),
XObject::Form(form_xobject) => form_xobject.size,
XObject::External(external_xobject) => {
Some((external_xobject.width?, external_xobject.height?))
}
}
}
}
const MAX_DECODED_STREAM_BYTES: usize = 256 * 1024 * 1024;
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalXObject {
pub stream: ExternalStream,
#[serde(default)]
pub width: Option<Px>,
#[serde(default)]
pub height: Option<Px>,
#[serde(default)]
pub dpi: Option<f32>,
}
#[derive(Debug, PartialEq, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalStream {
pub dict: BTreeMap<String, DictItem>,
pub content: Vec<u8>,
pub compress: bool,
}
impl ExternalStream {
pub(crate) fn into_lopdf(&self) -> lopdf::Stream {
lopdf::Stream::new(build_dict(&self.dict), self.content.clone())
.with_compression(self.compress)
}
pub(crate) fn into_lopdf_with_indirect_streams(
&self,
doc: &mut lopdf::Document,
) -> lopdf::Stream {
let dict = lopdf::Dictionary::from_iter(
self.dict
.iter()
.map(|(k, v)| (k.clone(), v.to_lopdf_with_indirect_streams(doc))),
);
lopdf::Stream::new(dict, self.content.clone()).with_compression(self.compress)
}
pub fn decompressed_content(&self) -> Vec<u8> {
self.into_lopdf()
.decompressed_content_with_limit(MAX_DECODED_STREAM_BYTES)
.unwrap_or(self.content.clone())
}
pub fn decode_ops(s: &str) -> Result<Vec<Op>, String> {
Self::get_ops_internal(s.as_bytes())
}
pub fn get_ops(&self) -> Result<Vec<Op>, String> {
Self::get_ops_internal(&self.decompressed_content())
}
fn get_ops_internal(s: &[u8]) -> Result<Vec<Op>, String> {
let content = lopdf::content::Content::decode(s)
.map_err(|e| format!("Failed to decode content stream: {}", e))?;
let mut page_state = PageState::default();
let mut printpdf_ops = Vec::new();
for (op_id, op) in content.operations.iter().enumerate() {
let parsed_op = crate::deserialize::parse_op(
0,
op_id,
op,
&mut page_state,
&BTreeMap::new(),
&mut Vec::new(),
)?;
printpdf_ops.extend(parsed_op);
}
Ok(printpdf_ops)
}
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "type", content = "data")]
pub enum DictItem {
Array(Vec<DictItem>),
String {
data: Vec<u8>,
literal: bool,
},
Bytes(Vec<u8>),
Bool(bool),
Float(f32),
Int(i64),
Real(f32),
Name(Vec<u8>),
Ref {
obj: u32,
gen: u16,
},
Dict {
map: BTreeMap<String, DictItem>,
},
Stream {
stream: ExternalStream,
},
Null,
}
impl DictItem {
pub fn to_lopdf(&self) -> lopdf::Object {
use lopdf::{Object, StringFormat};
match self {
DictItem::Array(items) => {
let objs = items.iter().map(|item| item.to_lopdf()).collect();
Object::Array(objs)
}
DictItem::String { data, literal } => {
let format = if *literal {
StringFormat::Literal
} else {
StringFormat::Hexadecimal
};
Object::String(data.clone(), format)
}
DictItem::Bytes(data) => {
Object::String(data.clone(), StringFormat::Hexadecimal)
}
DictItem::Bool(b) => Object::Boolean(*b),
DictItem::Float(f) => Object::Real(*f),
DictItem::Int(i) => Object::Integer(*i),
DictItem::Real(f) => Object::Real(*f),
DictItem::Name(name) => Object::Name(name.clone()),
DictItem::Ref { obj, gen } => Object::Reference((*obj, *gen)),
DictItem::Dict { map } => {
let dict = map
.iter()
.map(|(k, v)| (k.as_bytes().to_vec(), v.to_lopdf()))
.collect();
Object::Dictionary(dict)
}
DictItem::Stream { stream } => {
let stream_obj = stream.into_lopdf();
Object::Stream(stream_obj)
}
DictItem::Null => Object::Null,
}
}
pub(crate) fn to_lopdf_with_indirect_streams(
&self,
doc: &mut lopdf::Document,
) -> lopdf::Object {
use lopdf::Object;
match self {
DictItem::Array(items) => Object::Array(
items
.iter()
.map(|item| item.to_lopdf_with_indirect_streams(doc))
.collect(),
),
DictItem::Dict { map } => Object::Dictionary(lopdf::Dictionary::from_iter(
map.iter().map(|(k, v)| {
(k.as_bytes().to_vec(), v.to_lopdf_with_indirect_streams(doc))
}),
)),
DictItem::Stream { stream } => {
let stream_obj = stream.into_lopdf_with_indirect_streams(doc);
Object::Reference(doc.add_object(stream_obj))
}
other => other.to_lopdf(),
}
}
pub fn from_lopdf(o: &lopdf::Object) -> Self {
use lopdf::Object;
match o {
Object::Null => DictItem::Null,
Object::Boolean(t) => DictItem::Bool(*t),
Object::Integer(i) => DictItem::Int(*i),
Object::Real(r) => DictItem::Real(*r),
Object::Name(items) => DictItem::Name(items.clone()),
Object::String(items, string_format) => DictItem::String {
data: items.clone(),
literal: *string_format == StringFormat::Literal,
},
Object::Array(objects) => {
DictItem::Array(objects.iter().map(DictItem::from_lopdf).collect())
}
Object::Dictionary(dictionary) => DictItem::Dict {
map: dictionary
.iter()
.map(|s| {
(
String::from_utf8_lossy(s.0).to_string(),
DictItem::from_lopdf(s.1),
)
})
.collect(),
},
Object::Stream(stream) => DictItem::Stream {
stream: ExternalStream {
compress: stream.allows_compression,
content: stream.content.clone(),
dict: stream
.dict
.iter()
.map(|s| {
(
String::from_utf8_lossy(s.0).to_string(),
DictItem::from_lopdf(s.1),
)
})
.collect(),
},
},
Object::Reference((a, b)) => DictItem::Ref { obj: *a, gen: *b },
}
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum ImageFilter {
Ascii85,
Lzw,
DCT,
JPX,
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FormXObject {
pub form_type: FormType,
pub size: Option<(Px, Px)>,
#[serde(default = "empty_bbox")]
pub bbox: Rect,
pub matrix: Option<CurTransMat>,
#[serde(default)]
pub ops: Vec<Op>,
#[serde(default)]
pub resources: Option<PdfResources>,
pub group: Option<GroupXObject>,
pub ref_dict: Option<BTreeMap<String, DictItem>>,
pub metadata: Option<BTreeMap<String, DictItem>>,
pub piece_info: Option<BTreeMap<String, DictItem>>,
pub last_modified: Option<OffsetDateTime>,
pub struct_parent: Option<i64>,
pub struct_parents: Option<i64>,
pub opi: Option<BTreeMap<String, DictItem>>,
pub oc: Option<BTreeMap<String, DictItem>>,
pub name: Option<String>,
#[serde(default)]
pub extra: BTreeMap<String, DictItem>,
}
fn empty_bbox() -> Rect {
Rect::from_wh(Pt(0.0), Pt(0.0))
}
impl FormXObject {
pub fn new(bbox: Rect, ops: Vec<Op>) -> Self {
FormXObject {
form_type: FormType::Type1,
size: None,
bbox,
matrix: None,
ops,
resources: None,
group: None,
ref_dict: None,
metadata: None,
piece_info: None,
last_modified: None,
struct_parent: None,
struct_parents: None,
opi: None,
oc: None,
name: None,
extra: BTreeMap::new(),
}
}
pub fn from_content_stream(bbox: Rect, content: &[u8]) -> Result<Self, String> {
let ops = ExternalStream::get_ops_internal(content)?;
Ok(FormXObject::new(bbox, ops))
}
pub fn with_matrix(mut self, matrix: CurTransMat) -> Self {
self.matrix = Some(matrix);
self
}
pub fn with_resources(mut self, resources: PdfResources) -> Self {
self.resources = Some(resources);
self
}
pub fn with_group(mut self, group: GroupXObject) -> Self {
self.group = Some(group);
self
}
}
pub fn build_dict(r: &BTreeMap<String, DictItem>) -> lopdf::Dictionary {
lopdf::Dictionary::from_iter(r.iter().map(|(k, v)| (k.clone(), v.to_lopdf())))
}
#[derive(Debug, PartialEq, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FormType {
Type1,
}
impl FormType {
pub(crate) fn number(&self) -> i64 {
match self {
FormType::Type1 => 1,
}
}
}
#[derive(Debug, PartialEq, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GroupXObject {
#[serde(default)]
pub group_type: GroupXObjectType,
}
#[derive(Debug, Default, PartialEq, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GroupXObjectType {
#[default]
TransparencyGroup,
}
impl GroupXObjectType {
pub fn get_id(&self) -> &'static str {
match self {
GroupXObjectType::TransparencyGroup => "Transparency",
}
}
}
#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
pub struct ReferenceXObject {
pub file: Vec<u8>,
pub page: i64,
pub id: [i64; 2],
}
#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
pub struct PostScriptXObject {
#[allow(dead_code)]
pub level1: Option<Vec<u8>>,
}
#[derive(Debug, Copy, Clone, Default, PartialEq, Deserialize, Serialize)]
pub struct XObjectTransform {
#[serde(default)]
pub translate_x: Option<Pt>,
#[serde(default)]
pub translate_y: Option<Pt>,
#[serde(default)]
pub rotate: Option<XObjectRotation>,
#[serde(default)]
pub scale_x: Option<f32>,
#[serde(default)]
pub scale_y: Option<f32>,
#[serde(default)]
pub dpi: Option<f32>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub no_auto_scale: bool,
}
impl XObjectTransform {
pub fn get_ctms(&self, wh: Option<(Px, Px)>) -> Vec<CurTransMat> {
let mut transforms = Vec::new();
let dpi = self.dpi.unwrap_or(300.0);
if let Some((w, h)) = wh {
transforms.push(CurTransMat::Scale(w.into_pt(dpi).0, h.into_pt(dpi).0));
}
if self.scale_x.is_some() || self.scale_y.is_some() {
let scale_x = self.scale_x.unwrap_or(1.0);
let scale_y = self.scale_y.unwrap_or(1.0);
transforms.push(CurTransMat::Scale(scale_x, scale_y));
}
if let Some(rotate) = self.rotate.as_ref() {
transforms.push(CurTransMat::Translate(
Pt(-rotate.rotation_center_x.into_pt(dpi).0),
Pt(-rotate.rotation_center_y.into_pt(dpi).0),
));
transforms.push(CurTransMat::Rotate(rotate.angle_ccw_degrees));
transforms.push(CurTransMat::Translate(
rotate.rotation_center_x.into_pt(dpi),
rotate.rotation_center_y.into_pt(dpi),
));
}
if self.translate_x.is_some() || self.translate_y.is_some() {
transforms.push(CurTransMat::Translate(
self.translate_x.unwrap_or(Pt(0.0)),
self.translate_y.unwrap_or(Pt(0.0)),
));
}
transforms
}
pub(crate) fn placement_matrix(&self, wh: Option<(Px, Px)>) -> [f32; 6] {
self.get_ctms(wh)
.into_iter()
.fold(CurTransMat::Identity.as_array(), |m, q| {
CurTransMat::combine_matrix(m, q.as_array())
})
}
pub fn as_svg_transform(&self) -> String {
let ctms = self.get_ctms(None);
let mut combined = CurTransMat::Identity;
for t in ctms {
let new_arr = CurTransMat::combine_matrix(combined.as_array(), t.as_array());
combined = CurTransMat::Raw(new_arr);
}
let arr = combined.as_array();
format!(
"matrix({} {} {} {} {} {})",
arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]
)
}
}
#[derive(Debug, Copy, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct XObjectRotation {
#[serde(default)]
pub angle_ccw_degrees: f32,
#[serde(default)]
pub rotation_center_x: Px,
#[serde(default)]
pub rotation_center_y: Px,
}