Bind pdfTeX image color spaces to written PDF objects
This commit is contained in:
1 parent
e10e0cce53
commit
520e8eede2
8 files changed
+147
-32
No files matched your search
@@ -74,9 +74,12 @@ impl Executor {
|
||||
} else {
|
||||
PageSelection::Number(1)
|
||||
};
|
||||
if self.keyword("colorspace", files)? {
|
||||
return self.fail("native PDF image colorspace requires PDF object support");
|
||||
}
|
||||
let color_space = if self.keyword("colorspace", files)? {
|
||||
let number = self.integer(files)?;
|
||||
(number != 0).then_some(number)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut page_box = 0;
|
||||
for (keyword, kind) in [
|
||||
("mediabox", PageBox::Media),
|
||||
@@ -125,9 +128,9 @@ impl Executor {
|
||||
|header| (header.major, i32::from(header.minor)),
|
||||
);
|
||||
let decoded = if png {
|
||||
PdfImage::read_png(source, resolution)
|
||||
PdfImage::read_png(source, resolution, color_space)
|
||||
} else {
|
||||
PdfImage::read_jpeg(source, resolution, version)
|
||||
PdfImage::read_jpeg(source, resolution, version, color_space)
|
||||
};
|
||||
let (image, warning) = decoded.map_err(|error| self.error(error, token.span))?;
|
||||
if let Some(warning) = warning {
|
||||
|
||||
@@ -2397,7 +2397,9 @@ fn write_pdf(
|
||||
} else {
|
||||
resources
|
||||
};
|
||||
let remapped = resources.map(|resources| resources.append(&mut objects, diagnostics));
|
||||
let remapped = resources
|
||||
.map(|resources| resources.append(&mut objects, diagnostics))
|
||||
.transpose()?;
|
||||
if let Some(resources) = &remapped {
|
||||
for (font, entries) in &resources.fonts {
|
||||
if !entries.is_empty() {
|
||||
@@ -2417,8 +2419,26 @@ fn write_pdf(
|
||||
.first()
|
||||
.and_then(|page| page.pdf.as_ref())
|
||||
.map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor)));
|
||||
let mut unwritten_color_spaces = BTreeMap::new();
|
||||
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(id, image, attributes, compression)| {
|
||||
(id, image.append_to(&mut objects, attributes, compression, pdf_version, &type1_references))
|
||||
let color_space = image.color_space.map(|number| {
|
||||
let Ok(reference) = u32::try_from(number) else {
|
||||
return i64::from(number);
|
||||
};
|
||||
if let Some(mapped) = remapped.as_ref().and_then(|r| r.object_numbers.get(&reference)) {
|
||||
return i64::from(*mapped);
|
||||
}
|
||||
// A colorspace number is a reference only. Keep an unwritten target
|
||||
// free rather than materializing it or colliding with a device object.
|
||||
*unwritten_color_spaces.entry(reference).or_insert_with(|| {
|
||||
objects.push(Vec::new());
|
||||
objects.len() as i64
|
||||
})
|
||||
});
|
||||
let object = image.append_to(
|
||||
&mut objects, attributes, compression, pdf_version, &type1_references, color_space,
|
||||
);
|
||||
(id, object)
|
||||
}).collect();
|
||||
let mut png_group = None;
|
||||
for (page_index, list) in pages.iter().enumerate() {
|
||||
|
||||
@@ -428,6 +428,7 @@ pub(crate) struct ResourceOutput {
|
||||
page_references: BTreeMap<u32, u32>,
|
||||
link_references: BTreeMap<u32, Option<(usize, usize)>>,
|
||||
structure_references: BTreeSet<u32>,
|
||||
image_color_space_objects: BTreeSet<u32>,
|
||||
page_entries: Vec<Dictionary>,
|
||||
font_opacities: Vec<BTreeMap<u8, String>>,
|
||||
page_attributes: Vec<Dictionary>,
|
||||
@@ -447,6 +448,7 @@ pub(crate) struct RemappedResources {
|
||||
pub page_objects: BTreeMap<usize, usize>,
|
||||
pub link_objects: BTreeMap<(usize, usize), usize>,
|
||||
pub structure_objects: BTreeMap<u32, usize>,
|
||||
pub object_numbers: BTreeMap<u32, u32>,
|
||||
pub annotations: Vec<Vec<Option<Vec<u8>>>>,
|
||||
pub catalog: Option<Vec<u8>>,
|
||||
pub info: Option<Vec<u8>>,
|
||||
@@ -463,6 +465,7 @@ impl ResourceOutput {
|
||||
) -> Result<Self, String> {
|
||||
let empty = PdfObjects::default();
|
||||
let objects = objects.unwrap_or(&empty);
|
||||
let mut image_color_spaces = BTreeSet::new();
|
||||
let (page_entries, font_opacities): (Vec<_>, Vec<_>) = pages
|
||||
.iter()
|
||||
.map(|page| {
|
||||
@@ -472,16 +475,24 @@ impl ResourceOutput {
|
||||
"additional PDF resources overlap generated Font or XObject entries".into(),
|
||||
);
|
||||
}
|
||||
let alphas = page
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
crate::render::DisplayItem::OpenTypeColor(Some([_, _, _, alpha])) => {
|
||||
Some(*alpha)
|
||||
use crate::render::DisplayItem;
|
||||
let mut alphas = BTreeSet::new();
|
||||
for item in &page.items {
|
||||
let image = match item {
|
||||
DisplayItem::OpenTypeColor(Some([_, _, _, alpha])) => {
|
||||
alphas.insert(*alpha);
|
||||
continue;
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
DisplayItem::PdfImage { image, .. } => image,
|
||||
DisplayItem::PdfImageObject(object) => &object.image,
|
||||
_ => continue,
|
||||
};
|
||||
if let Some(number) = image.image.color_space
|
||||
&& let Ok(number) = u32::try_from(number)
|
||||
{
|
||||
image_color_spaces.insert(number);
|
||||
}
|
||||
}
|
||||
let names = add_font_opacities(&mut entries, alphas, objects)?;
|
||||
Ok((entries, names))
|
||||
})
|
||||
@@ -572,11 +583,22 @@ impl ResourceOutput {
|
||||
references(&value, &mut pending)?;
|
||||
values.insert(number, value);
|
||||
}
|
||||
// An image reference does not schedule an object for writing. Keep
|
||||
// full numeric precision in the written color space and its graph.
|
||||
let mut image_color_space_objects = BTreeSet::new();
|
||||
while let Some(number) = image_color_spaces.pop_first() {
|
||||
if let Some(value) = values.get(&number)
|
||||
&& image_color_space_objects.insert(number)
|
||||
{
|
||||
references(value, &mut image_color_spaces)?;
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
values,
|
||||
page_references: objects.page_references.clone(),
|
||||
link_references,
|
||||
structure_references,
|
||||
image_color_space_objects,
|
||||
page_entries,
|
||||
font_opacities,
|
||||
page_attributes,
|
||||
@@ -592,7 +614,7 @@ impl ResourceOutput {
|
||||
self,
|
||||
output: &mut Vec<Vec<u8>>,
|
||||
diagnostics: &mut Vec<String>,
|
||||
) -> RemappedResources {
|
||||
) -> Result<RemappedResources, String> {
|
||||
let mut ids = BTreeMap::new();
|
||||
let mut page_objects = BTreeMap::new();
|
||||
for (page, number) in self.page_references {
|
||||
@@ -625,9 +647,14 @@ impl ResourceOutput {
|
||||
.enumerate()
|
||||
.map(|(i, number)| (number, (output.len() + i + 1) as u32)),
|
||||
);
|
||||
for (_, mut object) in self.values {
|
||||
for (number, mut object) in self.values {
|
||||
remap(&mut object, &ids);
|
||||
output.push(encode_value(object).expect("valid PDF object in memory"));
|
||||
let body = if self.image_color_space_objects.contains(&number) {
|
||||
super::xdv_object::encode_device_value(object)
|
||||
} else {
|
||||
encode_value(object)
|
||||
};
|
||||
output.push(body?);
|
||||
}
|
||||
let structure_objects = self
|
||||
.structure_references
|
||||
@@ -659,7 +686,7 @@ impl ResourceOutput {
|
||||
bytes[2..bytes.len() - 2].to_vec()
|
||||
};
|
||||
let encode = |dictionary| encode_dictionary(dictionary, false);
|
||||
RemappedResources {
|
||||
Ok(RemappedResources {
|
||||
pages: self
|
||||
.page_entries
|
||||
.into_iter()
|
||||
@@ -680,7 +707,8 @@ impl ResourceOutput {
|
||||
.collect(),
|
||||
catalog: self.catalog.map(&encode),
|
||||
info: self.info.map(encode),
|
||||
}
|
||||
object_numbers: ids,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -314,7 +314,7 @@ pub(super) fn encode_device_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
fn append(bytes: &mut Vec<u8>, object: Object) -> Result<(), String> {
|
||||
match object {
|
||||
Object::Real(value) if value.is_finite() => write!(bytes, "{value}").unwrap(),
|
||||
Object::Real(_) => return Err("non-finite number in XDV PDF object".into()),
|
||||
Object::Real(_) => return Err("non-finite number in PDF object".into()),
|
||||
Object::Array(values) => {
|
||||
bytes.push(b'[');
|
||||
for value in values {
|
||||
@@ -333,6 +333,12 @@ pub(super) fn encode_device_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
}
|
||||
bytes.extend_from_slice(b">>");
|
||||
}
|
||||
Object::Stream(stream) => {
|
||||
append(bytes, Object::Dictionary(stream.dict))?;
|
||||
bytes.extend_from_slice(b"\nstream\n");
|
||||
bytes.extend_from_slice(&stream.content);
|
||||
bytes.extend_from_slice(b"\nendstream");
|
||||
}
|
||||
_ => bytes.extend(encode_value(object)?),
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -47,6 +47,8 @@ pub struct PdfImage {
|
||||
pub natural: [i64; 2],
|
||||
extent: [u64; 2],
|
||||
objects: Vec<Vec<Part>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) color_space: Option<i32>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
imported_fonts: Vec<imported_fonts::ImportedType1>,
|
||||
}
|
||||
@@ -336,6 +338,7 @@ enum Part {
|
||||
Bmp(png::SampledImage),
|
||||
XdvCmykDecode,
|
||||
MappedType1(Arc<ImportedType1Use>),
|
||||
ImageColorSpace,
|
||||
}
|
||||
|
||||
pub(crate) enum RasterProcSet {
|
||||
@@ -362,6 +365,7 @@ impl PdfImage {
|
||||
resource: LoadedResource,
|
||||
fallback_resolution: i32,
|
||||
pdf_version: (i32, i32),
|
||||
color_space: Option<i32>,
|
||||
) -> Result<(Self, Option<&'static str>), String> {
|
||||
let header = jpeg::read(&resource.data).map_err(|error| {
|
||||
format!(
|
||||
@@ -390,7 +394,10 @@ impl PdfImage {
|
||||
let denominator = 100 * i64::from(density[axis]);
|
||||
(numerator + denominator / 2) / denominator
|
||||
});
|
||||
Ok((Self::jpeg_xobject(resource, header, natural, [1.0; 2], false), warning))
|
||||
Ok((
|
||||
Self::jpeg_xobject(resource, header, natural, [1.0; 2], false, color_space),
|
||||
warning,
|
||||
))
|
||||
}
|
||||
|
||||
fn jpeg_xobject(
|
||||
@@ -399,6 +406,7 @@ impl PdfImage {
|
||||
natural: [i64; 2],
|
||||
extent: [f64; 2],
|
||||
xdv: bool,
|
||||
color_space: Option<i32>,
|
||||
) -> Self {
|
||||
let [width, height] = header.size;
|
||||
let color = match header.components {
|
||||
@@ -413,14 +421,17 @@ impl PdfImage {
|
||||
let mut parts = vec![Part::Bytes(
|
||||
format!("/Type /XObject /Subtype /Image /Width {width} /Height {height}").into_bytes(),
|
||||
)];
|
||||
if let Some((_, intent)) = profile {
|
||||
if color_space.is_some() {
|
||||
parts.push(Part::Bytes(b" /ColorSpace ".to_vec()));
|
||||
parts.push(Part::ImageColorSpace);
|
||||
} else 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 header.components == 4 && color_space.is_none() {
|
||||
if xdv && header.adobe {
|
||||
parts.push(Part::XdvCmykDecode);
|
||||
} else if !xdv {
|
||||
@@ -454,6 +465,7 @@ impl PdfImage {
|
||||
natural,
|
||||
extent: extent.map(f64::to_bits),
|
||||
objects,
|
||||
color_space,
|
||||
imported_fonts: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -475,7 +487,7 @@ impl PdfImage {
|
||||
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));
|
||||
return Ok(Self::jpeg_xobject(resource, header, natural(bp), bp, true, None));
|
||||
}
|
||||
let (part, bp) = if Self::is_png(&resource) {
|
||||
let (image, physical) = png::decode(&resource.data).map_err(|error| invalid(&error))?;
|
||||
@@ -500,6 +512,7 @@ impl PdfImage {
|
||||
natural: natural(bp),
|
||||
extent: bp.map(f64::to_bits),
|
||||
objects: vec![vec![part]],
|
||||
color_space: None,
|
||||
imported_fonts: Vec::new(),
|
||||
})
|
||||
}
|
||||
@@ -511,8 +524,9 @@ impl PdfImage {
|
||||
pub(crate) fn read_png(
|
||||
resource: LoadedResource,
|
||||
fallback_resolution: i32,
|
||||
color_space: Option<i32>,
|
||||
) -> Result<(Self, Option<&'static str>), String> {
|
||||
png::read(resource, fallback_resolution)
|
||||
png::read(resource, fallback_resolution, color_space)
|
||||
}
|
||||
|
||||
pub(crate) fn raster_frame(&self) -> Option<([i64; 2], u8)> {
|
||||
@@ -723,6 +737,7 @@ impl PdfImage {
|
||||
natural,
|
||||
extent: [width.to_bits(), height.to_bits()],
|
||||
objects: graph.bodies,
|
||||
color_space: None,
|
||||
imported_fonts,
|
||||
},
|
||||
[left, bottom],
|
||||
@@ -740,9 +755,10 @@ impl PdfImage {
|
||||
compression: u8,
|
||||
pdf_version: (i32, i32),
|
||||
fonts: &crate::pdf::type1_fonts::References<'_>,
|
||||
color_space: Option<i64>,
|
||||
) -> usize {
|
||||
if let Some(samples) = self.sampled_image() {
|
||||
return samples.append(pdf, attributes, compression, pdf_version);
|
||||
return samples.append(pdf, attributes, compression, pdf_version, color_space);
|
||||
}
|
||||
let base = pdf.len() + 1;
|
||||
pdf.extend(self.objects.iter().enumerate().map(|(index, parts)| {
|
||||
@@ -758,6 +774,10 @@ 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::ImageColorSpace => {
|
||||
let id = color_space.expect("mapped image color space");
|
||||
write!(body, "{id} 0 R").unwrap();
|
||||
}
|
||||
Part::MappedType1(font) => {
|
||||
let reference = &fonts[&font.mapped.key()];
|
||||
body.extend_from_slice(b" /BaseFont ");
|
||||
|
||||
@@ -106,6 +106,7 @@ pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, Option<PixelDimensio
|
||||
pub(super) fn read(
|
||||
resource: LoadedResource,
|
||||
fallback_resolution: i32,
|
||||
color_space: Option<i32>,
|
||||
) -> Result<(PdfImage, Option<&'static str>), String> {
|
||||
let (image, physical) = decode(&resource.data).map_err(|error| {
|
||||
format!(
|
||||
@@ -140,6 +141,7 @@ pub(super) fn read(
|
||||
natural,
|
||||
extent: [1.0_f64.to_bits(); 2],
|
||||
objects: vec![vec![Part::Png(image)]],
|
||||
color_space,
|
||||
imported_fonts: Vec::new(),
|
||||
},
|
||||
warning,
|
||||
@@ -180,13 +182,15 @@ impl SampledImage {
|
||||
attributes: &[u8],
|
||||
compression: u8,
|
||||
pdf_version: (i32, i32),
|
||||
color_space: Option<i64>,
|
||||
) -> usize {
|
||||
let id = pdf.len() + 1;
|
||||
let [width, height] = self.size;
|
||||
let mut color = match &self.color {
|
||||
ColorSpace::Gray => "/DeviceGray".to_owned(),
|
||||
ColorSpace::Rgb => "/DeviceRGB".to_owned(),
|
||||
ColorSpace::Indexed(table) => {
|
||||
let mut color = match (color_space, &self.color) {
|
||||
(Some(id), _) => format!("{id} 0 R"),
|
||||
(None, ColorSpace::Gray) => "/DeviceGray".to_owned(),
|
||||
(None, ColorSpace::Rgb) => "/DeviceRGB".to_owned(),
|
||||
(None, ColorSpace::Indexed(table)) => {
|
||||
let mut color = format!("[/Indexed /DeviceRGB {} <", table.len() / 3 - 1);
|
||||
for byte in table {
|
||||
write!(color, "{byte:02X}").expect("writing to a string");
|
||||
|
||||
Reference in new issue
Block a user