964 lines
34 KiB
Rust
964 lines
34 KiB
Rust
//! Native image XObjects and the resource objects reachable from their content.
|
|
mod bmp;
|
|
mod jpeg;
|
|
mod icc;
|
|
mod imported_fonts;
|
|
pub(crate) use imported_fonts::ImportedType1Use;
|
|
mod png;
|
|
use crate::{
|
|
pdf_device::Affine,
|
|
resources::{LoadedResource, ResourceVersion},
|
|
};
|
|
use lopdf::{Dictionary, Document, Object, ObjectId};
|
|
use std::{
|
|
collections::{BTreeMap, BTreeSet},
|
|
io::Write,
|
|
sync::Arc,
|
|
};
|
|
|
|
#[derive(Clone, Copy, Debug, Default)]
|
|
pub(crate) enum PageBox {
|
|
Media,
|
|
#[default]
|
|
Crop,
|
|
Bleed,
|
|
Trim,
|
|
Art,
|
|
}
|
|
impl PageBox {
|
|
fn keys(self) -> &'static [&'static [u8]] {
|
|
match self {
|
|
Self::Media => &[b"MediaBox"],
|
|
Self::Crop => &[b"CropBox", b"MediaBox"],
|
|
Self::Bleed => &[b"BleedBox", b"CropBox", b"MediaBox"],
|
|
Self::Trim => &[b"TrimBox", b"CropBox", b"MediaBox"],
|
|
Self::Art => &[b"ArtBox", b"CropBox", b"MediaBox"],
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct PdfImage {
|
|
pub version: ResourceVersion,
|
|
pub page: usize,
|
|
pub page_count: usize,
|
|
pub natural: [i64; 2],
|
|
extent: [u64; 2],
|
|
objects: Vec<Vec<Part>>,
|
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
|
imported_fonts: Vec<imported_fonts::ImportedType1>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct PdfImageUse {
|
|
pub id: usize,
|
|
pub image: Arc<PdfImage>,
|
|
pub width: i64,
|
|
pub height: i64,
|
|
pub depth: i64,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(crate) xdv: Option<XdvPdfPlacement>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub(crate) struct XdvPdfPlacement {
|
|
pub(crate) page_request: i32,
|
|
matrix: [u64; 6],
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
clip: Option<[u64; 4]>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
annotation_box: Option<[u64; 4]>,
|
|
#[serde(default)]
|
|
pub(crate) layout_offset: [i64; 2],
|
|
}
|
|
|
|
impl XdvPdfPlacement {
|
|
pub(crate) fn paint_matrix(&self) -> [f64; 6] {
|
|
self.matrix.map(f64::from_bits)
|
|
}
|
|
|
|
pub(crate) fn clip(&self) -> Option<[f64; 4]> {
|
|
self.clip.map(|rect| rect.map(f64::from_bits))
|
|
}
|
|
|
|
pub(crate) fn annotation_box(&self) -> [f64; 4] {
|
|
self.annotation_box.or(self.clip)
|
|
.map_or([0.0, 0.0, 1.0, 1.0], |rect| rect.map(f64::from_bits))
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct PdfImageObject {
|
|
pub image: Arc<PdfImageUse>,
|
|
pub attributes: Vec<u8>,
|
|
#[serde(default)]
|
|
pub compression: u8,
|
|
}
|
|
|
|
impl PdfImageUse {
|
|
pub(crate) fn new(
|
|
id: usize,
|
|
image: PdfImage,
|
|
requested: [Option<i32>; 3],
|
|
) -> Result<Self, String> {
|
|
let [w, h] = image.natural;
|
|
let raster = image.raster_frame().map(|(size, _)| size);
|
|
let [aspect_width, aspect_height] = raster.unwrap_or([w, h]);
|
|
let [width, height, depth] = requested.map(|value| value.map(i64::from));
|
|
let ratio = |value: i64, numerator: i64, denominator: i64| -> Result<i64, String> {
|
|
let product = i128::from(value) * i128::from(numerator);
|
|
let denominator = i128::from(denominator);
|
|
let rounded = product.signum() * ((product.abs() + denominator / 2) / denominator);
|
|
i64::try_from(rounded)
|
|
.map_err(|_| "native PDF image dimension capacity exceeded".into())
|
|
};
|
|
let depth = depth.unwrap_or(0);
|
|
let (width, height) = match (width, height) {
|
|
(None, None) if raster.is_some() && requested[2].is_some() => {
|
|
(ratio(h, aspect_width, aspect_height)?, h - depth)
|
|
}
|
|
(None, None) => (w, h - depth),
|
|
(Some(width), None) => (width, ratio(width, aspect_height, aspect_width)? - depth),
|
|
(None, Some(height)) => (ratio(height + depth, aspect_width, aspect_height)?, height),
|
|
(Some(width), Some(height)) => (width, height),
|
|
};
|
|
if [width, height, depth].iter().any(|v| v.abs() > 1073741823) {
|
|
return Err("native PDF image dimension capacity exceeded".into());
|
|
}
|
|
Ok(Self {
|
|
id,
|
|
image: Arc::new(image),
|
|
width,
|
|
height,
|
|
depth,
|
|
xdv: None,
|
|
})
|
|
}
|
|
|
|
pub(crate) fn new_xdv(
|
|
id: usize,
|
|
image: Arc<PdfImage>,
|
|
placement: XdvImagePlacement,
|
|
page_request: i32,
|
|
) -> Result<Self, String> {
|
|
let [left, bottom, right, top] = placement.bounds();
|
|
let dimensions = [(right - left), (top - bottom)].map(|points| points * 65536.0);
|
|
if dimensions.iter().any(|&value| !(0.0..=1073741823.0).contains(&value)) {
|
|
return Err("native XDV image dimension capacity exceeded".into());
|
|
}
|
|
let [width, height] = dimensions.map(|value| (value + 0.5) as i64);
|
|
// XeTeX passes the whole-point minima to its coordinate conversion.
|
|
let transform = Affine::translation(
|
|
-left.trunc() * 800.0 / 803.0,
|
|
-bottom.trunc() * 800.0 / 803.0,
|
|
)
|
|
.concatenate(placement.transform)
|
|
.0
|
|
.map(|coefficient| coefficient * 65536.0 + 0.5);
|
|
if transform
|
|
.iter()
|
|
.any(|&value| !(f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&value))
|
|
{
|
|
return Err("native XDV image transform capacity exceeded".into());
|
|
}
|
|
// The device consumes the printed 16.16 matrix.
|
|
let matrix = transform.map(|value| {
|
|
crate::execution::print_scaled(value as i32)
|
|
.parse()
|
|
.expect("printed 16.16 value")
|
|
});
|
|
let matrix = if image.raster_frame().is_some() {
|
|
let [width, height] = image.extent();
|
|
Affine(matrix)
|
|
.concatenate(Affine([width, 0.0, 0.0, height, 0.0, 0.0]))
|
|
.0
|
|
.map(|value| (value * 100_000.0).round() / 100_000.0)
|
|
} else {
|
|
matrix
|
|
};
|
|
Ok(Self {
|
|
id,
|
|
image,
|
|
width,
|
|
height,
|
|
depth: 0,
|
|
xdv: Some(XdvPdfPlacement {
|
|
page_request,
|
|
matrix: matrix.map(f64::to_bits),
|
|
clip: None,
|
|
annotation_box: None,
|
|
layout_offset: [0, 0],
|
|
}),
|
|
})
|
|
}
|
|
|
|
pub(crate) fn new_xdv_raster_special(
|
|
id: usize,
|
|
image: Arc<PdfImage>,
|
|
matrix: Affine,
|
|
annotation_box: Option<[f64; 4]>,
|
|
clip: bool,
|
|
) -> Result<Self, String> {
|
|
if matrix.0.iter().any(|value| !value.is_finite())
|
|
|| annotation_box.is_some_and(|rect| rect.iter().any(|value| !value.is_finite()))
|
|
{
|
|
return Err("XDV raster image transform exceeds capacity".into());
|
|
}
|
|
let clip = if clip { annotation_box } else { None };
|
|
let [x, y, w, h] = clip.unwrap_or([0.0, 0.0, 1.0, 1.0]);
|
|
let [x0, y0, x1, y1] = [x, y, x + w, y + h].map(|value| value.clamp(0.0, 1.0));
|
|
let [left, bottom] = matrix.point(x0, y0);
|
|
let bounds = [(x0, y1), (x1, y0), (x1, y1)].iter().fold(
|
|
[left, bottom, left, bottom],
|
|
|[left, bottom, right, top], &(x, y)| {
|
|
let [x, y] = matrix.point(x, y);
|
|
[left.min(x), bottom.min(y), right.max(x), top.max(y)]
|
|
},
|
|
);
|
|
let [left, bottom, right, top] =
|
|
bounds.map(|value| (value * 803.0 / 800.0 * 65536.0).round());
|
|
if [left, bottom, right, top].iter().any(|value| value.abs() > 1_073_741_823.0) {
|
|
return Err("XDV raster image bounds exceed capacity".into());
|
|
}
|
|
let matrix = matrix.0.map(|value| (value * 100_000.0).round() / 100_000.0);
|
|
Ok(Self {
|
|
id,
|
|
image,
|
|
width: (right - left) as i64,
|
|
height: (top - bottom) as i64,
|
|
depth: 0,
|
|
xdv: Some(XdvPdfPlacement {
|
|
page_request: 0,
|
|
matrix: matrix.map(f64::to_bits),
|
|
clip: clip.map(|rect| rect.map(f64::to_bits)),
|
|
annotation_box: annotation_box.map(|rect| rect.map(f64::to_bits)),
|
|
layout_offset: [left as i64, bottom as i64],
|
|
}),
|
|
})
|
|
}
|
|
|
|
pub(crate) fn dimensions(&self) -> (i64, i64, i64) {
|
|
(self.width, self.height, self.depth)
|
|
}
|
|
}
|
|
|
|
pub(crate) struct XdvImagePlacement {
|
|
corners: [[f32; 2]; 4],
|
|
transform: Affine,
|
|
requested: [Option<f64>; 2],
|
|
}
|
|
|
|
impl XdvImagePlacement {
|
|
pub(crate) fn new(image: &PdfImage, source_origin: [f64; 2]) -> Self {
|
|
// XeTeX's realrect and realpoint store coordinates as float.
|
|
let points = |bp| (bp * 803.0 / 800.0) as f32;
|
|
let [width, height] = image.extent().map(points);
|
|
let [left, bottom] = source_origin.map(points);
|
|
Self {
|
|
corners: Self::rectangle([left, bottom, left + width, bottom + height]),
|
|
transform: Affine::IDENTITY,
|
|
requested: [None; 2],
|
|
}
|
|
}
|
|
|
|
fn rectangle([left, bottom, right, top]: [f32; 4]) -> [[f32; 2]; 4] {
|
|
[[left, bottom], [left, top], [right, top], [right, bottom]]
|
|
}
|
|
|
|
fn bounds(&self) -> [f64; 4] {
|
|
let [x, y] = self.corners[0];
|
|
self.corners[1..]
|
|
.iter()
|
|
.fold([x, y, x, y], |[left, bottom, right, top], &[x, y]| {
|
|
[left.min(x), bottom.min(y), right.max(x), top.max(y)]
|
|
})
|
|
.map(f64::from)
|
|
}
|
|
|
|
fn apply(&mut self, transform: Affine) {
|
|
self.corners = self.corners.map(|[x, y]| {
|
|
transform
|
|
.point(f64::from(x), f64::from(y))
|
|
.map(|coordinate| coordinate as f32)
|
|
});
|
|
self.transform = transform.concatenate(self.transform);
|
|
}
|
|
|
|
pub(crate) fn scale(&mut self, x: f64, y: f64) {
|
|
if self.requested == [None; 2] {
|
|
self.apply(Affine([x, 0.0, 0.0, y, 0.0, 0.0]));
|
|
}
|
|
}
|
|
|
|
pub(crate) fn request_size(&mut self, axis: usize, size: i32) {
|
|
self.requested[axis] = Some(f64::from(size) / 65536.0);
|
|
}
|
|
|
|
pub(crate) fn fit(&mut self) -> Result<(), &'static str> {
|
|
let [left, bottom, right, top] = self.bounds();
|
|
let [x, y] = std::mem::take(&mut self.requested);
|
|
let x = x.map(|width| width / (right - left));
|
|
let y = y.map(|height| height / (top - bottom));
|
|
if let Some(scale) = x.or(y) {
|
|
let (x, y) = (x.unwrap_or(scale), y.unwrap_or(scale));
|
|
if !x.is_finite() || !y.is_finite() {
|
|
return Err("cannot resize an XDV image with collapsed bounds");
|
|
}
|
|
self.scale(x, y);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) fn rotate(&mut self, degrees: i32) -> Result<(), &'static str> {
|
|
self.fit()?;
|
|
let angle = (f64::from(degrees) / 65536.0).to_radians();
|
|
let (s, c) = angle.sin_cos();
|
|
self.apply(Affine([c, s, -s, c, 0.0, 0.0]));
|
|
self.corners = Self::rectangle(self.bounds().map(|coordinate| coordinate as f32));
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
enum Part {
|
|
Bytes(Vec<u8>),
|
|
Ref(usize),
|
|
Jpeg {
|
|
size: [u16; 2],
|
|
precision: u8,
|
|
#[serde(default)]
|
|
components: u8,
|
|
bytes: Vec<u8>,
|
|
},
|
|
Png(png::SampledImage),
|
|
Bmp(png::SampledImage),
|
|
XdvCmykDecode,
|
|
MappedType1(Arc<ImportedType1Use>),
|
|
}
|
|
|
|
pub(crate) enum RasterProcSet {
|
|
Gray,
|
|
Color,
|
|
Indexed,
|
|
}
|
|
|
|
pub(crate) fn real(value: f64) -> String {
|
|
let body = format!("{value:.15}");
|
|
body.trim_end_matches('0').trim_end_matches('.').to_owned()
|
|
}
|
|
|
|
impl PdfImage {
|
|
pub(crate) fn is_jpeg(resource: &LoadedResource) -> bool {
|
|
resource.data.starts_with(jpeg::SIGNATURE)
|
|
|| (!resource.data.starts_with(b"%PDF-")
|
|
&& resource.version.path.extension().is_some_and(|extension| {
|
|
extension.eq_ignore_ascii_case("jpg") || extension.eq_ignore_ascii_case("jpeg")
|
|
}))
|
|
}
|
|
|
|
pub(crate) fn read_jpeg(
|
|
resource: LoadedResource,
|
|
fallback_resolution: i32,
|
|
pdf_version: (i32, i32),
|
|
) -> Result<(Self, Option<&'static str>), String> {
|
|
let header = jpeg::read(&resource.data).map_err(|error| {
|
|
format!(
|
|
"could not parse JPEG image {}: {error}",
|
|
resource.version.path.display()
|
|
)
|
|
})?;
|
|
if header.progressive && pdf_version.0 == 1 && pdf_version.1 <= 2 {
|
|
return Err("cannot use progressive DCT with PDF-1.2".into());
|
|
}
|
|
let mut density = header.density;
|
|
let warning = if density.iter().any(|&dpi| dpi > 65_535) {
|
|
Some("too large image resolution ignored")
|
|
} else if density != [0, 0] && density.contains(&0) {
|
|
Some("too small image resolution ignored")
|
|
} else {
|
|
None
|
|
};
|
|
if warning.is_some() || density == [0, 0] {
|
|
let default = fallback_resolution.clamp(0, 65_535) as u32;
|
|
density = [if default == 0 { 72 } else { default }; 2];
|
|
}
|
|
let natural = std::array::from_fn(|axis| {
|
|
// One hundred inches in TeX scaled points.
|
|
let numerator = 473_628_672_i64 * i64::from(header.size[axis]);
|
|
let denominator = 100 * i64::from(density[axis]);
|
|
(numerator + denominator / 2) / denominator
|
|
});
|
|
Ok((Self::jpeg_xobject(resource, header, natural, [1.0; 2], false), warning))
|
|
}
|
|
|
|
fn jpeg_xobject(
|
|
resource: LoadedResource,
|
|
header: jpeg::Header,
|
|
natural: [i64; 2],
|
|
extent: [f64; 2],
|
|
xdv: bool,
|
|
) -> Self {
|
|
let [width, height] = header.size;
|
|
let color = match header.components {
|
|
1 => "/DeviceGray",
|
|
3 => "/DeviceRGB",
|
|
4 => "/DeviceCMYK",
|
|
_ => unreachable!("JPEG component count was checked"),
|
|
};
|
|
let profile = header.icc.as_ref()
|
|
.filter(|_| xdv)
|
|
.and_then(|bytes| icc::intent(bytes, header.components).map(|intent| (bytes, intent)));
|
|
let mut parts = vec![Part::Bytes(
|
|
format!("/Type /XObject /Subtype /Image /Width {width} /Height {height}").into_bytes(),
|
|
)];
|
|
if let Some((_, intent)) = profile {
|
|
parts.push(Part::Bytes(format!(" /Intent /{intent} /ColorSpace [/ICCBased ").into_bytes()));
|
|
parts.push(Part::Ref(1));
|
|
parts.push(Part::Bytes(b"]".to_vec()));
|
|
} else {
|
|
parts.push(Part::Bytes(format!(" /ColorSpace {color}").into_bytes()));
|
|
}
|
|
if header.components == 4 {
|
|
if xdv && header.adobe {
|
|
parts.push(Part::XdvCmykDecode);
|
|
} else if !xdv {
|
|
parts.push(Part::Bytes(b" /Decode [1 0 1 0 1 0 1 0]".to_vec()));
|
|
}
|
|
}
|
|
parts.push(Part::Bytes(format!(
|
|
" /BitsPerComponent {} /Filter /DCTDecode /Length {} >>\nstream\n",
|
|
header.precision,
|
|
resource.data.len()
|
|
).into_bytes()));
|
|
parts.push(Part::Jpeg {
|
|
size: header.size,
|
|
precision: header.precision,
|
|
components: header.components,
|
|
bytes: resource.data,
|
|
});
|
|
parts.push(Part::Bytes(b"\nendstream".to_vec()));
|
|
let mut objects = vec![parts];
|
|
if let Some((bytes, _)) = profile {
|
|
objects.push(vec![Part::Bytes(crate::pdf::objects::stream(
|
|
&format!("/N {} /Alternate {color}", header.components),
|
|
bytes,
|
|
6,
|
|
))]);
|
|
}
|
|
Self {
|
|
version: resource.version,
|
|
page: 1,
|
|
page_count: 1,
|
|
natural,
|
|
extent: extent.map(f64::to_bits),
|
|
objects,
|
|
imported_fonts: Vec::new(),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn read_xdv_raster(resource: LoadedResource) -> Result<Self, String> {
|
|
let invalid = |error: &str| format!(
|
|
"could not parse XDV raster {}: {error}",
|
|
resource.version.path.display()
|
|
);
|
|
let extent = |size: [u32; 2], density: [f64; 2]| -> Result<[f64; 2], String> {
|
|
let bp = std::array::from_fn(|axis| f64::from(size[axis]) * 72.0 / density[axis]);
|
|
if bp.iter().any(|&value| !value.is_finite() || value <= 0.0) {
|
|
return Err(invalid("invalid dimensions or density"));
|
|
}
|
|
Ok(bp)
|
|
};
|
|
let natural =
|
|
|bp: [f64; 2]| bp.map(|value| (value * 803.0 / 800.0 * 65536.0).round() as i64);
|
|
if resource.data.starts_with(jpeg::SIGNATURE) {
|
|
let header = jpeg::read(&resource.data).map_err(invalid)?;
|
|
let bp = extent(header.size.map(u32::from), header.xdv_density)?;
|
|
return Ok(Self::jpeg_xobject(resource, header, natural(bp), bp, true));
|
|
}
|
|
let (part, bp) = if Self::is_png(&resource) {
|
|
let (image, physical) = png::decode(&resource.data).map_err(|error| invalid(&error))?;
|
|
let density = physical.map_or([72.0; 2], |physical| {
|
|
[physical.xppu, physical.yppu].map(|ppm| {
|
|
if ppm == 0 { 72.0 } else { f64::from(ppm) * 0.0254 }
|
|
})
|
|
});
|
|
let bp = extent(image.size, density)?;
|
|
(Part::Png(image), bp)
|
|
} else if resource.data.starts_with(bmp::SIGNATURE) {
|
|
let (image, density) = bmp::decode(&resource.data).map_err(|error| invalid(&error))?;
|
|
let bp = extent(image.size, density)?;
|
|
(Part::Bmp(image), bp)
|
|
} else {
|
|
return Err(invalid("expected PNG, JPEG, or BMP"));
|
|
};
|
|
Ok(Self {
|
|
version: resource.version,
|
|
page: 1,
|
|
page_count: 1,
|
|
natural: natural(bp),
|
|
extent: bp.map(f64::to_bits),
|
|
objects: vec![vec![part]],
|
|
imported_fonts: Vec::new(),
|
|
})
|
|
}
|
|
|
|
pub(crate) fn is_png(resource: &LoadedResource) -> bool {
|
|
resource.data.starts_with(png::SIGNATURE)
|
|
}
|
|
|
|
pub(crate) fn read_png(
|
|
resource: LoadedResource,
|
|
fallback_resolution: i32,
|
|
) -> Result<(Self, Option<&'static str>), String> {
|
|
png::read(resource, fallback_resolution)
|
|
}
|
|
|
|
pub(crate) fn raster_frame(&self) -> Option<([i64; 2], u8)> {
|
|
self.objects.first()?.iter().find_map(|part| match part {
|
|
Part::Jpeg {
|
|
size, precision, ..
|
|
} => Some((size.map(i64::from), *precision)),
|
|
Part::Png(samples) | Part::Bmp(samples) => {
|
|
Some((samples.size.map(i64::from), samples.source_depth))
|
|
}
|
|
_ => None,
|
|
})
|
|
}
|
|
|
|
pub(crate) fn raster_procset(&self) -> Option<RasterProcSet> {
|
|
self.objects.first()?.iter().find_map(|part| match part {
|
|
Part::Jpeg { components, bytes, .. } => {
|
|
let components = if *components == 0 {
|
|
jpeg::read(bytes).ok()?.components
|
|
} else {
|
|
*components
|
|
};
|
|
Some(if components == 1 { RasterProcSet::Gray } else { RasterProcSet::Color })
|
|
}
|
|
Part::Png(samples) => Some(samples.procset()),
|
|
_ => None,
|
|
})
|
|
}
|
|
|
|
fn sampled_image(&self) -> Option<&png::SampledImage> {
|
|
match self.objects.first()?.as_slice() {
|
|
[Part::Png(samples) | Part::Bmp(samples)] => Some(samples),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn png_transparency(&self, pdf_version: (i32, i32)) -> bool {
|
|
self.sampled_image().is_some_and(|samples| samples.has_alpha(pdf_version))
|
|
}
|
|
|
|
pub(crate) fn read(
|
|
resource: LoadedResource,
|
|
page: usize,
|
|
kind: PageBox,
|
|
remap_type1: bool,
|
|
) -> Result<Self, String> {
|
|
Self::read_page(resource, kind.keys(), false, remap_type1, |pages| {
|
|
u32::try_from(page)
|
|
.ok()
|
|
.filter(|&page| page > 0 && page as usize <= pages)
|
|
})
|
|
.map(|(image, _)| image)
|
|
}
|
|
|
|
pub(crate) fn read_xdv(
|
|
resource: LoadedResource,
|
|
page: i32,
|
|
kind: PageBox,
|
|
) -> Result<(Self, [f64; 2]), String> {
|
|
let keys = [
|
|
kind.keys()[0],
|
|
b"CropBox",
|
|
b"MediaBox",
|
|
b"BleedBox",
|
|
b"TrimBox",
|
|
b"ArtBox",
|
|
];
|
|
Self::read_page(resource, &keys, true, false, |pages| {
|
|
let pages = i64::try_from(pages).ok()?;
|
|
let page = match page {
|
|
0 => 1,
|
|
page if page < 0 => pages + i64::from(page) + 1,
|
|
page => i64::from(page),
|
|
};
|
|
(pages > 0).then(|| page.clamp(1, pages) as u32)
|
|
})
|
|
}
|
|
|
|
pub(crate) fn count_pages(resource: &LoadedResource) -> usize {
|
|
Self::open_pdf(resource).map_or(0, |doc| doc.get_pages().len())
|
|
}
|
|
|
|
fn open_pdf(resource: &LoadedResource) -> Result<Document, String> {
|
|
let doc = Document::load_mem(&resource.data).map_err(|error| {
|
|
format!(
|
|
"could not parse PDF image {}: {error}",
|
|
resource.version.path.display()
|
|
)
|
|
})?;
|
|
if doc.trailer.has(b"Encrypt") {
|
|
return Err("encrypted PDF image requires a decryption key".into());
|
|
}
|
|
Ok(doc)
|
|
}
|
|
|
|
fn read_page(
|
|
resource: LoadedResource,
|
|
box_keys: &[&[u8]],
|
|
keep_page_origin: bool,
|
|
remap_type1: bool,
|
|
select_page: impl FnOnce(usize) -> Option<u32>,
|
|
) -> Result<(Self, [f64; 2]), String> {
|
|
let doc = Self::open_pdf(&resource)?;
|
|
let pages = doc.get_pages();
|
|
let page = select_page(pages.len()).ok_or("required page does not exist")?;
|
|
let page_id = pages
|
|
.get(&page)
|
|
.copied()
|
|
.ok_or("required page does not exist")?;
|
|
let chain = page_chain(&doc, page_id)?;
|
|
let inherited = |name: &[u8]| chain.iter().find_map(|dict| dict.get(name).ok());
|
|
let bounds = box_keys
|
|
.iter()
|
|
.find_map(|key| inherited(key))
|
|
.ok_or("PDF image has no page bounding box")?;
|
|
let bounds = resolved(&doc, bounds)?
|
|
.as_array()
|
|
.map_err(|error| error.to_string())?;
|
|
let [a, b, c, d] = bounds.as_slice() else {
|
|
return Err("PDF image bounding box must contain four coordinates".into());
|
|
};
|
|
let (a, b, c, d) = (
|
|
number(&doc, a)?,
|
|
number(&doc, b)?,
|
|
number(&doc, c)?,
|
|
number(&doc, d)?,
|
|
);
|
|
let [left, bottom, right, top] = [a.min(c), b.min(d), a.max(c), b.max(d)];
|
|
let rotation = inherited(b"Rotate")
|
|
.map(|rotate| {
|
|
resolved(&doc, rotate)?
|
|
.as_i64()
|
|
.map_err(|error| error.to_string())
|
|
})
|
|
.transpose()?
|
|
.unwrap_or(0)
|
|
.rem_euclid(360);
|
|
let (mut matrix, width, height) = match rotation {
|
|
0 => (
|
|
[1.0, 0.0, 0.0, 1.0, -left, -bottom],
|
|
right - left,
|
|
top - bottom,
|
|
),
|
|
90 => (
|
|
[0.0, -1.0, 1.0, 0.0, -bottom, right],
|
|
top - bottom,
|
|
right - left,
|
|
),
|
|
180 => (
|
|
[-1.0, 0.0, 0.0, -1.0, right, top],
|
|
right - left,
|
|
top - bottom,
|
|
),
|
|
270 => (
|
|
[0.0, 1.0, -1.0, 0.0, top, -left],
|
|
top - bottom,
|
|
right - left,
|
|
),
|
|
_ => return Err("PDF image rotation must be a multiple of 90 degrees".into()),
|
|
};
|
|
if keep_page_origin {
|
|
// XDV pictures place the PDF page using a matrix that already
|
|
// accounts for the selected page-box origin.
|
|
matrix[4] += left;
|
|
matrix[5] += bottom;
|
|
}
|
|
let sp = |bp: f64| -> Result<i64, String> {
|
|
let value = (bp * 65536.0 * 803.0 / 800.0).round();
|
|
if !(1.0..=1073741823.0).contains(&value) {
|
|
return Err("invalid image dimensions".into());
|
|
}
|
|
Ok(value as i64)
|
|
};
|
|
let natural = [sp(width)?, sp(height)?];
|
|
let mut contents = Vec::new();
|
|
if let Ok(content) = chain[0].get(b"Contents") {
|
|
read_contents(&doc, content, &mut contents, 0)?;
|
|
}
|
|
let array = |values: &[f64]| {
|
|
values
|
|
.iter()
|
|
.map(|&v| real(v))
|
|
.collect::<Vec<_>>()
|
|
.join(" ")
|
|
};
|
|
let mut graph = Graph {
|
|
doc: &doc,
|
|
ids: BTreeMap::new(),
|
|
bodies: vec![Vec::new()],
|
|
};
|
|
let mut form = Vec::new();
|
|
let header = format!(
|
|
"/Type /XObject /Subtype /Form /FormType 1 /BBox [{}] /Matrix [{}] /Resources ",
|
|
array(&[left, bottom, right, top]),
|
|
array(&matrix)
|
|
);
|
|
form.push(Part::Bytes(header.into_bytes()));
|
|
match inherited(b"Resources") {
|
|
Some(resources) => graph.render(resources, &mut form, 0)?,
|
|
None => form.push(Part::Bytes(b"<<>>".to_vec())),
|
|
}
|
|
if let Ok(group) = chain[0].get(b"Group") {
|
|
form.push(Part::Bytes(b" /Group ".to_vec()));
|
|
graph.render(group, &mut form, 0)?;
|
|
}
|
|
let mut stream = format!(" /Length {} >>\nstream\n", contents.len()).into_bytes();
|
|
stream.extend(contents);
|
|
stream.extend_from_slice(b"\nendstream");
|
|
form.push(Part::Bytes(stream));
|
|
graph.bodies[0] = form;
|
|
let imported_fonts = if remap_type1 {
|
|
imported_fonts::capture(&mut graph, inherited(b"Resources"))?
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
Ok((
|
|
Self {
|
|
version: resource.version,
|
|
page: page as usize,
|
|
page_count: pages.len(),
|
|
natural,
|
|
extent: [width.to_bits(), height.to_bits()],
|
|
objects: graph.bodies,
|
|
imported_fonts,
|
|
},
|
|
[left, bottom],
|
|
))
|
|
}
|
|
|
|
pub(crate) fn extent(&self) -> [f64; 2] {
|
|
self.extent.map(f64::from_bits)
|
|
}
|
|
|
|
pub(crate) fn append_to(
|
|
&self,
|
|
pdf: &mut Vec<Vec<u8>>,
|
|
attributes: &[u8],
|
|
compression: u8,
|
|
pdf_version: (i32, i32),
|
|
fonts: &crate::pdf::type1_fonts::References<'_>,
|
|
) -> usize {
|
|
if let Some(samples) = self.sampled_image() {
|
|
return samples.append(pdf, attributes, compression, pdf_version);
|
|
}
|
|
let base = pdf.len() + 1;
|
|
pdf.extend(self.objects.iter().enumerate().map(|(index, parts)| {
|
|
let mut body = Vec::new();
|
|
if index == 0 {
|
|
body.extend_from_slice(b"<< ");
|
|
if !attributes.is_empty() {
|
|
body.extend_from_slice(attributes);
|
|
body.push(b'\n');
|
|
}
|
|
}
|
|
for part in parts {
|
|
match part {
|
|
Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes),
|
|
Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(),
|
|
Part::MappedType1(font) => {
|
|
let reference = &fonts[&font.mapped.key()];
|
|
body.extend_from_slice(b" /BaseFont ");
|
|
body.extend(pdf_name(reference.name.as_bytes()));
|
|
write!(body, " /FontDescriptor {} 0 R", reference.object).unwrap();
|
|
}
|
|
Part::Png(_) | Part::Bmp(_) => unreachable!("sampled image owns its objects"),
|
|
Part::XdvCmykDecode => {
|
|
if !attributes
|
|
.split(|byte| byte.is_ascii_whitespace())
|
|
.any(|part| part == b"/Decode")
|
|
{
|
|
body.extend_from_slice(b" /Decode [1 0 1 0 1 0 1 0]");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
body
|
|
}));
|
|
base
|
|
}
|
|
}
|
|
|
|
fn page_chain(doc: &Document, mut id: ObjectId) -> Result<Vec<&Dictionary>, String> {
|
|
let mut chain = Vec::new();
|
|
let mut seen = BTreeSet::new();
|
|
loop {
|
|
if chain.len() >= 64 || !seen.insert(id) {
|
|
return Err("PDF image page tree is cyclic or too deep".into());
|
|
}
|
|
let dict = doc.get_dictionary(id).map_err(|error| error.to_string())?;
|
|
chain.push(dict);
|
|
let Ok(parent) = dict.get(b"Parent") else {
|
|
return Ok(chain);
|
|
};
|
|
id = parent.as_reference().map_err(|error| error.to_string())?;
|
|
}
|
|
}
|
|
|
|
fn resolved<'a>(doc: &'a Document, mut object: &'a Object) -> Result<&'a Object, String> {
|
|
for _ in 0..64 {
|
|
let Object::Reference(id) = object else {
|
|
return Ok(object);
|
|
};
|
|
object = doc.objects.get(id).ok_or("missing object in PDF image")?;
|
|
}
|
|
Err("PDF image object reference chain is too deep".into())
|
|
}
|
|
|
|
fn number(doc: &Document, object: &Object) -> Result<f64, String> {
|
|
let value = match resolved(doc, object)? {
|
|
Object::Integer(value) => *value as f64,
|
|
Object::Real(value) => *value,
|
|
_ => return Err("PDF image bounding box contains a non-numeric value".into()),
|
|
};
|
|
if !value.is_finite() {
|
|
return Err("PDF image bounding box contains a non-finite value".into());
|
|
}
|
|
Ok(value)
|
|
}
|
|
|
|
fn read_contents(
|
|
doc: &Document,
|
|
object: &Object,
|
|
out: &mut Vec<u8>,
|
|
depth: usize,
|
|
) -> Result<(), String> {
|
|
if depth >= 64 {
|
|
return Err("PDF image contents are too deeply nested".into());
|
|
}
|
|
match resolved(doc, object)? {
|
|
Object::Null => {}
|
|
Object::Stream(stream) => {
|
|
if stream.dict.has(b"Filter") {
|
|
out.extend(
|
|
stream
|
|
.decompressed_content()
|
|
.map_err(|error| error.to_string())?,
|
|
);
|
|
} else {
|
|
out.extend_from_slice(&stream.content);
|
|
}
|
|
out.push(b'\n');
|
|
}
|
|
Object::Array(items) => {
|
|
for item in items {
|
|
read_contents(doc, item, out, depth + 1)?;
|
|
}
|
|
}
|
|
_ => return Err("PDF image contents must be a stream or array of streams".into()),
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
struct Graph<'a> {
|
|
doc: &'a Document,
|
|
ids: BTreeMap<ObjectId, usize>,
|
|
bodies: Vec<Vec<Part>>,
|
|
}
|
|
|
|
impl Graph<'_> {
|
|
fn render(&mut self, value: &Object, out: &mut Vec<Part>, depth: usize) -> Result<(), String> {
|
|
if depth >= 128 {
|
|
return Err("PDF image resource graph is too deeply nested".into());
|
|
}
|
|
let bytes = |out: &mut Vec<Part>, bytes: &[u8]| {
|
|
if let Some(Part::Bytes(last)) = out.last_mut() {
|
|
last.extend_from_slice(bytes);
|
|
} else {
|
|
out.push(Part::Bytes(bytes.to_vec()));
|
|
}
|
|
};
|
|
match value {
|
|
Object::Null => bytes(out, b"null"),
|
|
Object::Boolean(true) => bytes(out, b"true"),
|
|
Object::Boolean(false) => bytes(out, b"false"),
|
|
Object::Integer(n) => bytes(out, n.to_string().as_bytes()),
|
|
Object::Real(n) if n.is_finite() => bytes(out, real(*n).as_bytes()),
|
|
Object::Real(_) => return Err("non-finite number in PDF image".into()),
|
|
Object::Name(name) => {
|
|
bytes(out, &pdf_name(name));
|
|
}
|
|
Object::String(data, _) => {
|
|
let mut encoded = vec![b'<'];
|
|
for &ch in data {
|
|
write!(encoded, "{ch:02X}").unwrap();
|
|
}
|
|
encoded.push(b'>');
|
|
bytes(out, &encoded);
|
|
}
|
|
Object::Array(values) => {
|
|
bytes(out, b"[");
|
|
for child in values {
|
|
self.render(child, out, depth + 1)?;
|
|
bytes(out, b" ");
|
|
}
|
|
bytes(out, b"]");
|
|
}
|
|
Object::Dictionary(dict) => {
|
|
bytes(out, b"<<");
|
|
for (key, child) in dict.iter() {
|
|
self.render(&Object::Name(key.clone()), out, depth + 1)?;
|
|
bytes(out, b" ");
|
|
self.render(child, out, depth + 1)?;
|
|
bytes(out, b" ");
|
|
}
|
|
bytes(out, b">>");
|
|
}
|
|
Object::Stream(stream) => {
|
|
let mut dict = stream.dict.clone();
|
|
dict.set("Length", stream.content.len() as i64);
|
|
self.render(&Object::Dictionary(dict), out, depth + 1)?;
|
|
bytes(out, b"\nstream\n");
|
|
bytes(out, &stream.content);
|
|
bytes(out, b"\nendstream");
|
|
}
|
|
Object::Reference(id) => {
|
|
let index = match self.ids.get(id) {
|
|
Some(index) => *index,
|
|
None => {
|
|
let new_index = self.bodies.len();
|
|
self.ids.insert(*id, new_index);
|
|
self.bodies.push(Vec::new());
|
|
let mut body = Vec::new();
|
|
let object = self
|
|
.doc
|
|
.objects
|
|
.get(id)
|
|
.ok_or("missing resource object in PDF image")?;
|
|
self.render(object, &mut body, depth + 1)?;
|
|
self.bodies[new_index] = body;
|
|
new_index
|
|
}
|
|
};
|
|
out.push(Part::Ref(index));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn pdf_name(name: &[u8]) -> Vec<u8> {
|
|
let mut encoded = vec![b'/'];
|
|
for &byte in name {
|
|
if (33..=126).contains(&byte) && !b"#%()<>[]{}/".contains(&byte) {
|
|
encoded.push(byte);
|
|
} else {
|
|
write!(encoded, "#{byte:02X}").unwrap();
|
|
}
|
|
}
|
|
encoded
|
|
}
|