Bind pdfTeX image color spaces to written PDF objects

This commit is contained in:
gloamxun committed 2026-11-26 18:16:31 +08:00
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 {
+22 -2
View File
@@ -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(())
+26 -6
View File
@@ -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 ");
+8 -4
View File
@@ -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");
+26
View File
@@ -2175,6 +2175,32 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### pdfTeX 光栅图像的颜色空间对象
`\pdfximage colorspace` 扫描带符号的 TeX 整数。PNG 和 JPEG 在实际写出时
引用同一作业的 PDF 对象,原样 PDF 页面导入忽略这个选项。零值保留自动
选择,CMYK JPEG 的缺省 Decode 反转也仅在自动选择时写入。没有写出的
正数目标在输出保留空闲引用,图像引用本身不会提前写出对象。对象编号在
导出时映射,支持延迟写出及出页后补写。
[参考 PNG 写出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writepng.c#L572-L611) · [参考 JPEG 写出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writejpg.c#L371-L405)
25 个定向用例覆盖实际颜色空间对象、文件对象、未写出目标、透明遮罩、
灰度与 CMYK JPEG、Indexed 和 ICC。原有通用写出器曾把 CalGray 白点
0.9505、1.089 舍入到 0.95、1.09。现在沿实际对象引用图保存数值精度,
包括间接字典、ICC 流字典的 1.0123 和原始 ICC 字节。十个结果的
144 DPI 光栅逐像素一致,含原样 Elsevier CAS 的 5333 × 3000 JPEG。
三页 XDV 数字选页与前版 PDF 逐字节一致。
同一会话替换外部颜色对象、移除后恢复。两轮成功修订各复用 108 步,只
替换第二页,PDF、SVG、来源映射与 aux 等于独立全量。缺失对象时保留
已有产物。修改入口前缀和删除资源的修订也保留产物,此修订走会话内的
暂存重编路径。已保留此前独立全量作业写出 aux 的观察。
三页探针在第三页另放一张图片。改变第二页的颜色对象后,第三页本次及
前版的 SVG 字节相同,现有交付仍重新发送第二、三页。回执保留了该额外
工作和与独立全量的一致性,用于后续精确页失效。回执
`target/p3-pdf-image-colorspace/receipt.json` 的 SHA-256 为 `3ea8083760d7a26bdc4d453cd39e0ad339f0a4c0f9069abcf318911bdd4b07cf`。
### pdfTeX 页框设置与继承裁边
`\pdfximage` 支持 `\pdfpagebox` 的默认选择、显式页框、
+8
View File
@@ -995,6 +995,14 @@ LaTeX 的 aux 与冻结参考逐字节相同,引用已收敛。三页的 635
词保持顺序和词框,144 DPI 灰度图逐像素一致。
[阶段记录](P2_M1_PROGRESS.md#pdftex-导入版本检查与设备初始化时机)
### Elsevier CAS 双栏原样 JPEG 的颜色空间对照
从既有原样归档取未修改的 `figs/cas-munnar-2024.jpg`,冻结输入指纹。
以同样的 PDF 颜色空间对象单独比较该插图。两端保留同一份 5333 × 3000
JPEG 的压缩字节与解码设置,生成页的 144 DPI 灰度图相同。
此前整篇双栏复验与同版统一矩阵的记录分别保留。
[阶段记录](P2_M1_PROGRESS.md#pdftex-光栅图像的颜色空间对象)
### Elsevier CAS 双栏导入页框复验
原样 30 项交付沿用冻结的 schema51、真实字体映射及参考。三轮