Merge pull request #8299 from dotCooCoo/fix/pdfx-xmp-metadata-date

PDF/X: PDF/X-4 files carry xmp:MetadataDate, equal to xmp:ModifyDate
This commit is contained in:
BFlat
2026-11-17 18:49:07 +07:00
committed by GitHub
4 changed files with 69 additions and 6 deletions
+20 -3
View File
@@ -6,7 +6,7 @@
//! transparency (the app flattens it before writing), no layers, PDF 1.3.
//! - PDF/X-3:2002: colours are ICC-based (always tagged), no transparency, no layers, PDF 1.3.
//! - PDF/X-4:2010: transparency and layers are kept, colours are tagged, PDF 1.6 at most, and the
//! XMP metadata names the standard too.
//! XMP metadata names the standard too and carries `xmp:MetadataDate`.
//! - All of them: a `/GTS_PDFX` output intent (blank, the CMYK profile in effect, embedded), a
//! TrimBox on every page (the artboard), `/Trapped` True or False, `/GTS_PDFXVersion` in the
//! document information, a title and dates, embedded fonts (or text as outlines), no editing
@@ -120,8 +120,9 @@ pub(crate) fn info_entries(standard: Standard) -> String {
}
/// Edit the XMP metadata of a PDF/X file (the catalog's `/Metadata` stream; `root` is the
/// catalog dictionary's contents) into `patch`: PDF/X-4 adds the standard, Trapped and a version
/// id (PDF 1.3 files say so in [`finish`]). Files without metadata are left as they are.
/// catalog dictionary's contents) into `patch`: PDF/X-4 adds the standard, Trapped, a version id
/// and the metadata date (PDF 1.3 files say so in [`finish`]). Files without metadata are left as
/// they are.
pub(crate) fn xmp(pdf: &[u8], xref: &Xref, root: (usize, usize), patch: &mut Patch, standard: Standard, trapped: bool) -> Result<(), PdfError> {
if !standard.is_pdfx() {
return Ok(());
@@ -145,6 +146,22 @@ pub(crate) fn xmp(pdf: &[u8], xref: &Xref, root: (usize, usize), patch: &mut Pat
"<pdfxid:GTS_PDFXVersion xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\">{version}</pdfxid:GTS_PDFXVersion><pdf:Trapped>{trapped}</pdf:Trapped><xmpMM:VersionID>1</xmpMM:VersionID>"
);
edits.push((close, close, props.into_bytes()));
// When the packet has no `<xmp:MetadataDate>` element, this adds one after the writer's
// `<xmp:ModifyDate>` element with the same value. The search expects the writer's form:
// properties written as elements with the `xmp` prefix, and `<` in text written as `&lt;`.
// The writer's description declares the `xmp` prefix there, and
// [`crate::post::modification_date`] keeps the two dates equal.
if find(xml, b"<xmp:MetadataDate>", 0).is_none()
&& let Some(at) = find(xml, b"<xmp:ModifyDate>", 0).map(|i| i + b"<xmp:ModifyDate>".len())
&& let Some(to) = find(xml, b"</xmp:ModifyDate>", at)
{
let date = xml.get(at..to).ok_or_else(bad)?;
let mut prop = b"<xmp:MetadataDate>".to_vec();
prop.extend_from_slice(date);
prop.extend_from_slice(b"</xmp:MetadataDate>");
let after = to + b"</xmp:ModifyDate>".len();
edits.push((after, after, prop));
}
}
// Every edit grows the stream (or keeps its length).
let grown: usize = edits.iter().map(|(s, e, new)| new.len().saturating_sub(e - s)).sum();
+3 -2
View File
@@ -84,8 +84,9 @@ pub(crate) fn user_units(pdf: Vec<u8>, units: &[f64]) -> Result<Vec<u8>, PdfErro
/// `pdf` dated as modified at `modified` (Unix seconds, UTC), its creation dates kept: the
/// document information's `/ModDate` (a PDF date, ISO 32000-1 §7.9.4) and every `xmp:ModifyDate`,
/// `xmp:MetadataDate` and `stEvt:when` of the catalog's XMP metadata (ISO 8601 dates), in UTC as
/// the PDF writer writes the creation date. The writer gives `/ModDate`, `xmp:ModifyDate` and
/// `stEvt:when` the creation date.
/// the PDF writer writes the creation date. The writer gives `/ModDate`, `xmp:ModifyDate`,
/// `stEvt:when` and, in a PDF/X-4 file, `xmp:MetadataDate` ([`crate::pdfx::xmp`]) the creation
/// date.
pub(crate) fn modification_date(pdf: Vec<u8>, modified: i64) -> Result<Vec<u8>, PdfError> {
let failed = |why: &str| PdfError::Write(format!("can't write the file's modification date: {why}"));
let Parsed { xref, objects, trailer, root, .. } = linearize::parse(&pdf).map_err(failed)?;
+45
View File
@@ -42,6 +42,51 @@ fn text(pdf: &[u8]) -> String {
String::from_utf8_lossy(pdf).into_owned()
}
/// The XMP packet of `pdf`, read as its stream's `/Length` says: the packet's end must be inside
/// those bytes and nothing but the end of line may follow them before `endstream`.
fn xmp_packet(pdf: &[u8]) -> String {
use crate::lab_spot::{find, rfind};
let begin = find(pdf, b"<?xpacket begin", 0).expect("an XMP packet");
let head = &pdf[..begin];
let obj = rfind(head, b" obj").expect("the packet's object");
let dict = &head[obj..];
let at = find(dict, b"/Length ", 0).expect("its length") + b"/Length ".len();
let digits: Vec<u8> = dict[at..].iter().copied().take_while(u8::is_ascii_digit).collect();
let length: usize = String::from_utf8(digits).unwrap().parse().unwrap();
let mut data = obj + rfind(dict, b"stream").unwrap() + b"stream".len();
data += pdf[data..].iter().take(2).take_while(|b| matches!(b, b'\r' | b'\n')).count();
let stream = &pdf[data..data + length];
let close = find(stream, b"<?xpacket end=", 0).expect("the packet ends inside the stream's length");
assert!(find(stream, b"?>", close).is_some(), "the packet ends inside the stream's length");
let rest = String::from_utf8_lossy(&pdf[data + length..]);
assert!(rest.trim_start_matches(['\r', '\n']).starts_with("endstream"), "the stream ends at its length");
String::from_utf8(stream.to_vec()).unwrap()
}
/// The value of the XMP element `tag` in `xmp`.
fn xmp_value<'a>(xmp: &'a str, tag: &str) -> Option<&'a str> {
let open = format!("<{tag}>");
let rest = &xmp[xmp.find(&open)? + open.len()..];
Some(&rest[..rest.find(&format!("</{tag}>"))?])
}
#[test]
fn pdfx4_metadata_has_a_metadata_date_equal_to_the_modification_date() {
let d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0)]);
// Dated by the writer (created), then dated again after writing (modified later).
for modified in [None, Some(1_800_000_000)] {
let mut o = opts(Standard::PdfX4, |_| {});
o.modified = modified;
let xmp = xmp_packet(&export(&d, &o).unwrap());
let modify = xmp_value(&xmp, "xmp:ModifyDate").expect("xmp:ModifyDate");
assert_eq!(xmp_value(&xmp, "xmp:MetadataDate"), Some(modify), "{modified:?}: {xmp}");
assert_eq!(xmp.matches("<xmp:MetadataDate>").count(), 1, "{modified:?}");
if modified.is_some() {
assert!(modify.starts_with("2027-01-15T"), "the later date: {modify}");
}
}
}
#[test]
fn each_standard_writes_its_header_output_intent_boxes_and_identification() {
let mut d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::rgb(0.2, 0.4, 0.9)]);
+1 -1
View File
@@ -9393,7 +9393,7 @@ layers are refused.
destination or output intent is refused. Transparency is flattened before writing.
- **pdfX3** (PDF/X-3:2002, written as PDF 1.3): colours are tagged with ICC profiles; transparency is flattened.
- **pdfX4** (PDF/X-4:2010, PDF 1.6 at most): transparency and layers are kept, colours are tagged, and the XMP metadata
names the standard.
names the standard and has an `xmp:MetadataDate` equal to its `xmp:ModifyDate`.
Flattening uses `flattenerPreset` (default High Resolution, see PDF 1.3 above) on a copy (the document is untouched; a
warning says so), and images with see-through pixels count as transparency. The written file is checked against