Render native XeTeX PNG, JPEG and BMP graphics
This commit is contained in:
1 parent
794c2f9b2c
commit
2bd6e19519
22 files changed
+821
-120
No files matched your search
@@ -1,5 +1,7 @@
|
||||
//! Native image XObjects and the resource objects reachable from their content.
|
||||
mod bmp;
|
||||
mod jpeg;
|
||||
mod icc;
|
||||
mod png;
|
||||
use crate::{
|
||||
pdf_device::Affine,
|
||||
@@ -58,12 +60,20 @@ pub struct PdfImageUse {
|
||||
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)]
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -116,7 +126,7 @@ impl PdfImageUse {
|
||||
|
||||
pub(crate) fn new_xdv(
|
||||
id: usize,
|
||||
image: PdfImage,
|
||||
image: Arc<PdfImage>,
|
||||
placement: XdvImagePlacement,
|
||||
page_request: i32,
|
||||
) -> Result<Self, String> {
|
||||
@@ -146,15 +156,68 @@ impl PdfImageUse {
|
||||
.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: Arc::new(image),
|
||||
image,
|
||||
width,
|
||||
height,
|
||||
depth: 0,
|
||||
xdv: Some(XdvPdfPlacement {
|
||||
page_request,
|
||||
matrix: matrix.map(f64::to_bits),
|
||||
clip: None,
|
||||
layout_offset: [0, 0],
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn new_xdv_raster_special(
|
||||
id: usize,
|
||||
image: Arc<PdfImage>,
|
||||
matrix: Affine,
|
||||
clip: Option<[f64; 4]>,
|
||||
) -> Result<Self, String> {
|
||||
if matrix.0.iter().any(|value| !value.is_finite())
|
||||
|| clip.is_some_and(|rect| rect.iter().any(|value| !value.is_finite()))
|
||||
{
|
||||
return Err("XDV raster image transform exceeds capacity".into());
|
||||
}
|
||||
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)),
|
||||
layout_offset: [left as i64, bottom as i64],
|
||||
}),
|
||||
})
|
||||
}
|
||||
@@ -250,7 +313,9 @@ enum Part {
|
||||
precision: u8,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
Png(png::PngImage),
|
||||
Png(png::SampledImage),
|
||||
Bmp(png::SampledImage),
|
||||
XdvCmykDecode,
|
||||
}
|
||||
|
||||
pub(crate) fn real(value: f64) -> String {
|
||||
@@ -281,13 +346,6 @@ impl PdfImage {
|
||||
if header.progressive && pdf_version.0 == 1 && pdf_version.1 <= 2 {
|
||||
return Err("cannot use progressive DCT with PDF-1.2".into());
|
||||
}
|
||||
let [width, height] = header.size;
|
||||
let color = match header.components {
|
||||
1 => "/DeviceGray",
|
||||
3 => "/DeviceRGB",
|
||||
4 => "/DeviceCMYK /Decode [1 0 1 0 1 0 1 0]",
|
||||
_ => unreachable!("JPEG component count was checked"),
|
||||
};
|
||||
let mut density = header.density;
|
||||
let warning = if density.iter().any(|&dpi| dpi > 65_535) {
|
||||
Some("too large image resolution ignored")
|
||||
@@ -306,31 +364,115 @@ impl PdfImage {
|
||||
let denominator = 100 * i64::from(density[axis]);
|
||||
(numerator + denominator / 2) / denominator
|
||||
});
|
||||
let dictionary = format!(
|
||||
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \
|
||||
/ColorSpace {color} /BitsPerComponent {} /Filter /DCTDecode /Length {} >>\nstream\n",
|
||||
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,
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
);
|
||||
Ok((
|
||||
Self {
|
||||
version: resource.version,
|
||||
page: 1,
|
||||
page_count: 1,
|
||||
natural,
|
||||
extent: [1.0_f64.to_bits(); 2],
|
||||
objects: vec![vec![
|
||||
Part::Bytes(dictionary.into_bytes()),
|
||||
Part::Jpeg {
|
||||
size: header.size,
|
||||
precision: header.precision,
|
||||
bytes: resource.data,
|
||||
},
|
||||
Part::Bytes(b"\nendstream".to_vec()),
|
||||
]],
|
||||
},
|
||||
warning,
|
||||
))
|
||||
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]],
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_png(resource: &LoadedResource) -> bool {
|
||||
@@ -349,20 +491,22 @@ impl PdfImage {
|
||||
Part::Jpeg {
|
||||
size, precision, ..
|
||||
} => Some((size.map(i64::from), *precision)),
|
||||
Part::Png(png) => Some((png.size.map(i64::from), png.source_depth)),
|
||||
Part::Png(samples) | Part::Bmp(samples) => {
|
||||
Some((samples.size.map(i64::from), samples.source_depth))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn png(&self) -> Option<&png::PngImage> {
|
||||
fn sampled_image(&self) -> Option<&png::SampledImage> {
|
||||
match self.objects.first()?.as_slice() {
|
||||
[Part::Png(png)] => Some(png),
|
||||
[Part::Png(samples) | Part::Bmp(samples)] => Some(samples),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn png_transparency(&self, pdf_version: (i32, i32)) -> bool {
|
||||
self.png().is_some_and(|png| png.has_alpha(pdf_version))
|
||||
self.sampled_image().is_some_and(|samples| samples.has_alpha(pdf_version))
|
||||
}
|
||||
|
||||
pub(crate) fn read(
|
||||
@@ -557,8 +701,8 @@ impl PdfImage {
|
||||
compression: u8,
|
||||
pdf_version: (i32, i32),
|
||||
) -> usize {
|
||||
if let Some(png) = self.png() {
|
||||
return png.append(pdf, attributes, compression, pdf_version);
|
||||
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)| {
|
||||
@@ -574,7 +718,15 @@ impl PdfImage {
|
||||
match part {
|
||||
Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes),
|
||||
Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(),
|
||||
Part::Png(_) => unreachable!("PNG owns its image objects"),
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user