DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Read PDF/X output intent and Info as parsed objects in validate-pdf
NetterSilver52232fc2c7d2
diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rsindex 9ce15674c..a9839fcd3 100644--- a/apps/designcraft-cli/src/main.rs+++ b/apps/designcraft-cli/src/main.rs@@ -156,7 +156,6 @@ fn report(r: Result<(), String>) -> ExitCode {fn validate_pdf(args: &[String]) -> Result<(), String> {const USAGE: &str = "usage: designcraft-cli validate-pdf FILE.pdf [--standard x4|x1a]";- const X1A: &[u8] = b"/GTS_PDFXVersion(PDF/X-1:";let mut path = None;let mut standard = None;let mut it = args.iter();@@ -172,7 +171,7 @@ fn validate_pdf(args: &[String]) -> Result<(), String> {let standard = match standard.map(designcraft_pdf::Standard::parse) {Some(Some(s)) => s,Some(None) => return Err(USAGE.into()),- None if bytes.windows(X1A.len()).any(|w| w == X1A) => designcraft_pdf::Standard::PdfX1a,+ None if designcraft_pdf::pdfx_version(&bytes).is_some_and(|v| v.starts_with("PDF/X-1:")) => designcraft_pdf::Standard::PdfX1a,None => designcraft_pdf::Standard::PdfX4,};let (name, issues) = match standard {diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rsindex 987e7ea97..37909a1f5 100644--- a/crates/pdf/src/lib.rs+++ b/crates/pdf/src/lib.rs@@ -51,7 +51,7 @@ mod transitions;pub use export::{BookletKind, BookletOptions, booklet_pairs, export_booklet, export_pdf, export_pdf_with_report, merge_pdfs, print_color, sheet_spreads,};-pub use pdfx::{check_pdfx4, has_rgb_groups, make_pdfx4};+pub use pdfx::{check_pdfx4, has_rgb_groups, make_pdfx4, pdfx_version};pub use pdfx1a::check_pdfx1a;pub use transitions::{add_blend_space, add_catalog_entries, add_page_entries, add_transitions};diff --git a/crates/pdf/src/optional_content.rs b/crates/pdf/src/optional_content.rsindex 7857d36d7..374c0d1f1 100644--- a/crates/pdf/src/optional_content.rs+++ b/crates/pdf/src/optional_content.rs@@ -58,7 +58,7 @@ fn edited(dict: &Dict<'_>, replacements: &[(&[u8], &[u8])]) -> Result<Vec<u8>> {/// The trailer of the cross-reference section at `offset`: a table's `trailer` dictionary or an/// xref stream's own. A table is read entry by entry rather than searched for the keyword, so a/// `trailer` in a comment can't stand in for the real one; reading is bounded either way.-fn trailer_at(bytes: &[u8], offset: usize) -> Option<Dict<'_>> {+pub(crate) fn trailer_at(bytes: &[u8], offset: usize) -> Option<Dict<'_>> {const MAX_SECTION_BYTES: usize = 4 * 1024 * 1024;let data = bytes.get(offset..)?;let mut reader = Reader::new(data.get(..data.len().min(MAX_SECTION_BYTES))?);diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rsindex e20247813..6d7a3714f 100644--- a/crates/pdf/src/pdfx.rs+++ b/crates/pdf/src/pdfx.rs@@ -8,6 +8,7 @@ use std::collections::HashSet;use hayro_syntax::content::UntypedIter;use hayro_syntax::object::{Array, Dict, Name, Object, ObjectIdentifier, Stream};use hayro_syntax::page::Resources;+use hayro_syntax::reader::ReaderExt;use craft_pdf::write::WriteError;use craft_pdf::write::backend as krilla;@@ -115,16 +116,18 @@ pub fn has_rgb_groups(pdf: &[u8]) -> bool {pub fn check_pdfx4(pdf: &[u8]) -> Vec<String> {let mut issues = Vec::new();let text = String::from_utf8_lossy(pdf);+ let file = hayro_syntax::Pdf::new(pdf.to_vec()).ok();if !pdf.starts_with(b"%PDF-1.") || pdf.get(7).is_none_or(|v| *v > b'6') {issues.push("the PDF version must be 1.6 or lower".into());}- if !text.contains("/S/GTS_PDFX") {+ let intents = file.as_ref().map(pdfx_intents).unwrap_or_default();+ if intents.is_empty() {issues.push("no PDF/X output intent".into());}- if !text.contains("/DestOutputProfile") {+ if !intents.iter().any(|oi| oi.contains_key(b"DestOutputProfile")) {issues.push("the output intent has no destination profile".into());}- if !text.contains("/GTS_PDFXVersion(PDF/X-4)") {+ if file.as_ref().and_then(|f| info_text(pdf, f, b"GTS_PDFXVersion")).as_deref() != Some("PDF/X-4") {issues.push("the document information doesn't name PDF/X-4".into());}if !text.contains("pdfxid:GTS_PDFXVersion>PDF/X-4<") {@@ -150,22 +153,67 @@ pub fn check_pdfx4(pdf: &[u8]) -> Vec<String> {if text.contains("/Subtype/Type3") {issues.push("Type 3 fonts aren't allowed".into());}- issues.extend(device_rgb(pdf));+ issues.extend(device_rgb(file.as_ref()));issues.extend(fonts::unembedded_fonts(pdf));issues}+/// The document information's `GTS_PDFXVersion` (`PDF/X-4`, `PDF/X-1:2003`, …), read as an+/// object; `None` when the file can't be read or doesn't name one.+pub fn pdfx_version(pdf: &[u8]) -> Option<String> {+ info_text(pdf, &hayro_syntax::Pdf::new(pdf.to_vec()).ok()?, b"GTS_PDFXVersion")+}++/// The catalog's `GTS_PDFX` output intents, read as objects (whitespace and object streams+/// don't matter).+pub(crate) fn pdfx_intents<'a>(file: &'a hayro_syntax::Pdf) -> Vec<Dict<'a>> {+ let xref = file.xref();+ let Some(catalog) = xref.get::<Dict<'_>>(xref.root_id()) else { return Vec::new() };+ let Some(intents) = catalog.get::<Array<'_>>(b"OutputIntents") else { return Vec::new() };+ intents.iter::<Dict<'_>>().filter(|oi| oi.get::<Name<'_>>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX")).collect()+}++/// The text entry `key` of the document information dictionary, trimmed: the `/Info` of the+/// newest trailer that has one (classic or cross-reference stream, following `/Prev` a bounded+/// number of times), else of the last `trailer` keyword in the file.+pub(crate) fn info_text(pdf: &[u8], file: &hayro_syntax::Pdf, key: &[u8]) -> Option<String> {+ let lookup = |trailer: &Dict<'_>| -> Option<String> {+ let info = match trailer.get_ref(b"Info") {+ Some(r) => file.xref().get::<Dict<'_>>(r.into())?,+ None => trailer.get::<Dict<'_>>(b"Info")?,+ };+ let value = info.get::<hayro_syntax::object::String<'_>>(key)?;+ Some(String::from_utf8_lossy(value.as_bytes()).trim().to_string())+ };+ let tail = pdf.get(rfind(pdf, b"startxref")?..).unwrap_or_default();+ let mut offset = int_after(&String::from_utf8_lossy(tail), "startxref");+ let mut seen = HashSet::new();+ for _ in 0..32 {+ let Some(at) = offset.filter(|at| seen.insert(*at)) else { break };+ let Some(trailer) = crate::optional_content::trailer_at(pdf, at) else { break };+ if trailer.contains_key(b"Info") {+ return lookup(&trailer);+ }+ offset = trailer.get::<usize>(b"Prev");+ }+ // A damaged cross-reference offset: the dictionary after the last `trailer` keyword.+ let at = rfind(pdf, b"trailer")? + b"trailer".len();+ let mut reader = hayro_syntax::reader::Reader::new(pdf.get(at..)?);+ reader.skip_white_spaces_and_comments();+ lookup(&reader.read_without_context::<Dict<'_>>()?)+}+/// Device-dependent RGB under a CMYK output intent. PDF/X-4 (ISO 15930-7) lets RGB in only when/// it is colour-managed: ICCBased RGB, or DeviceRGB remapped by a `DefaultRGB` colour space in the/// resources. DeviceCMYK and DeviceGray are the output intent's own device values, so they stay./// This walks every page's content, the images, forms, patterns, shadings and soft masks it uses,/// and the transparency groups, and reports each kind of device RGB it finds with the pages it is/// on. Nothing is reported when the file has no CMYK PDF/X output intent.-fn device_rgb(pdf: &[u8]) -> Vec<String> {- let Ok(file) = hayro_syntax::Pdf::new(pdf.to_vec()) else {+fn device_rgb(file: Option<&hayro_syntax::Pdf>) -> Vec<String> {+ let Some(file) = file else {return vec!["the file couldn't be read to check its colour spaces".into()];};- if !cmyk_output_intent(&file) {+ if !cmyk_output_intent(file) {return Vec::new();}let mut found: Vec<(String, Vec<usize>)> = Vec::new();@@ -198,13 +246,7 @@ fn device_rgb(pdf: &[u8]) -> Vec<String> {/// Whether the file's PDF/X output intent has a four-channel (CMYK) destination profile.pub(crate) fn cmyk_output_intent(file: &hayro_syntax::Pdf) -> bool {- let xref = file.xref();- let Some(catalog) = xref.get::<Dict<'_>>(xref.root_id()) else { return false };- let Some(intents) = catalog.get::<Array<'_>>(b"OutputIntents") else { return false };- intents.iter::<Dict<'_>>().any(|oi| {- oi.get::<Name<'_>>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX")- && oi.get::<Stream<'_>>(b"DestOutputProfile").and_then(|p| p.dict().get::<i32>(b"N")) == Some(4)- })+ pdfx_intents(file).iter().any(|oi| oi.get::<Stream<'_>>(b"DestOutputProfile").and_then(|p| p.dict().get::<i32>(b"N")) == Some(4))}/// Whether a colour space is device RGB: `/DeviceRGB` (`/RGB` in inline images), or andiff --git a/crates/pdf/src/pdfx/tests.rs b/crates/pdf/src/pdfx/tests.rsindex edb6aec8f..b35e897c2 100644--- a/crates/pdf/src/pdfx/tests.rs+++ b/crates/pdf/src/pdfx/tests.rs@@ -462,3 +462,106 @@ fn xmp_states_trapped() {assert!(String::from_utf8_lossy(&r.bytes).contains("/Trapped/False"));assert!(r.warnings.is_empty(), "{:?}", r.warnings);}++/// `objects` (from 1) as a PDF 1.6 file with a classic cross-reference table and `trailer`.+fn assemble_x4(objects: &[&str], trailer: &str) -> Vec<u8> {+ let mut out = b"%PDF-1.6\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objects.iter().enumerate() {+ offsets.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());+ }+ let xref = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f\r\n", objects.len() + 1).as_bytes());+ for off in offsets {+ out.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());+ }+ out.extend_from_slice(format!("trailer\n{trailer}\nstartxref\n{xref}\n%%EOF\n").as_bytes());+ out+}++const NO_INTENT: &str = "no PDF/X output intent";+const NO_INFO: &str = "the document information doesn't name PDF/X-4";++/// The output intent and the document information are read as objects: whitespace between+/// tokens (as qpdf and Ghostscript write them) doesn't hide them.+#[test]+fn x4_checks_ignore_whitespace_between_tokens() {+ let pdf = assemble_x4(+ &[+ "<< /Type /Catalog /Pages 2 0 R /OutputIntents [ << /Type /OutputIntent /S /GTS_PDFX /DestOutputProfile 4 0 R >> ] >>",+ "<< /Type /Pages /Kids [ 3 0 R ] /Count 1 >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [ 0 0 100 100 ] /TrimBox [ 0 0 100 100 ] >>",+ "<< /N 4 /Length 0 >>\nstream\n\nendstream",+ "<< /GTS_PDFXVersion (PDF/X-4) /Trapped /False >>",+ ],+ "<< /Size 6 /Root 1 0 R /Info 5 0 R >>",+ );+ let issues = check_pdfx4(&pdf);+ assert!(!issues.iter().any(|i| i == NO_INTENT || i == NO_INFO), "{issues:?}");+ // Without them, both are still reported.+ let bare = assemble_x4(+ &[+ "<< /Type /Catalog /Pages 2 0 R /OutputIntents [ << /Type /OutputIntent /S /GTS_PDFA1 >> ] >>",+ "<< /Type /Pages /Kids [ 3 0 R ] /Count 1 >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [ 0 0 100 100 ] /TrimBox [ 0 0 100 100 ] >>",+ "<< /N 4 /Length 0 >>\nstream\n\nendstream",+ "<< /Title (/S/GTS_PDFX /GTS_PDFXVersion(PDF/X-4)) /GTS_PDFXVersion (PDF/X-3:2002) >>",+ ],+ "<< /Size 6 /Root 1 0 R /Info 5 0 R >>",+ );+ let issues = check_pdfx4(&bare);+ assert!(issues.iter().any(|i| i == NO_INTENT) && issues.iter().any(|i| i == NO_INFO), "{issues:?}");+}++/// The output intent and the document information are found inside a compressed object stream,+/// through a cross-reference stream.+#[test]+fn x4_checks_read_object_streams() {+ let plain = [+ "<</Type/Catalog/Pages 2 0 R/OutputIntents[7 0 R]>>",+ "<</Type/Pages/Kids[3 0 R]/Count 1>>",+ "<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/TrimBox[0 0 100 100]>>",+ "<</N 4/Length 0>>\nstream\n\nendstream",+ ];+ let (info, intent) = ("<</GTS_PDFXVersion(PDF/X-4)/Trapped/False>>", "<</Type/OutputIntent/S/GTS_PDFX/DestOutputProfile 4 0 R>>");+ let mut out = b"%PDF-1.6\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in plain.iter().enumerate() {+ offsets.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());+ }+ // Object 5 is free; 6 and 7 live in object stream 8.+ let header = format!("6 0 7 {} ", info.len() + 1);+ let body = format!("{header}{info} {intent}");+ let objstm = out.len();+ let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());+ std::io::Write::write_all(&mut z, body.as_bytes()).unwrap();+ let packed = z.finish().unwrap();+ out.extend_from_slice(+ format!("8 0 obj\n<</Type/ObjStm/N 2/First {}/Filter/FlateDecode/Length {}>>\nstream\n", header.len(), packed.len()).as_bytes(),+ );+ out.extend_from_slice(&packed);+ out.extend_from_slice(b"\nendstream\nendobj\n");+ let xref = out.len();+ let mut rows = Vec::new();+ let mut row = |kind: u8, field: usize, idx: u16| {+ rows.push(kind);+ rows.extend_from_slice(&u32::try_from(field).unwrap().to_be_bytes());+ rows.extend_from_slice(&idx.to_be_bytes());+ };+ row(0, 0, 65535);+ for off in &offsets {+ row(1, *off, 0);+ }+ row(0, 0, 0);+ row(2, 8, 0);+ row(2, 8, 1);+ row(1, objstm, 0);+ row(1, xref, 0);+ out.extend_from_slice(format!("9 0 obj\n<</Type/XRef/Size 10/W[1 4 2]/Root 1 0 R/Info 6 0 R/Length {}>>\nstream\n", rows.len()).as_bytes());+ out.extend_from_slice(&rows);+ out.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{xref}\n%%EOF\n").as_bytes());+ let issues = check_pdfx4(&out);+ assert!(!issues.iter().any(|i| i == NO_INTENT || i == NO_INFO), "{issues:?}");+}diff --git a/crates/pdf/src/pdfx1a.rs b/crates/pdf/src/pdfx1a.rsindex 88759b071..495a389d8 100644--- a/crates/pdf/src/pdfx1a.rs+++ b/crates/pdf/src/pdfx1a.rs@@ -116,16 +116,18 @@ pub fn check_pdfx1a(pdf: &[u8]) -> Vec<String> {fn checks(pdf: &[u8]) -> (Vec<String>, Vec<String>) {let mut issues = Vec::new();let text = String::from_utf8_lossy(pdf);+ let file = hayro_syntax::Pdf::new(pdf.to_vec()).ok();if !pdf.starts_with(b"%PDF-1.") || pdf.get(7).is_none_or(|v| *v > b'4') {issues.push("the PDF version must be 1.4 or lower".into());}- if !text.contains("/S/GTS_PDFX") {+ if file.as_ref().is_none_or(|f| crate::pdfx::pdfx_intents(f).is_empty()) {issues.push("no PDF/X output intent".into());}- if !text.contains(&format!("/GTS_PDFXVersion({VERSION})")) {+ let info = |key: &[u8]| file.as_ref().and_then(|f| crate::pdfx::info_text(pdf, f, key));+ if info(b"GTS_PDFXVersion").as_deref() != Some(VERSION) {issues.push(format!("the document information doesn't name {VERSION}"));}- if !text.contains(&format!("/GTS_PDFXConformance({CONFORMANCE})")) {+ if info(b"GTS_PDFXConformance").as_deref() != Some(CONFORMANCE) {issues.push(format!("the document information doesn't name the conformance level {CONFORMANCE}"));}if !text.contains("/Trapped/False") && !text.contains("/Trapped/True") && !text.contains("/Trapped /False") && !text.contains("/Trapped /True") {@@ -142,18 +144,18 @@ fn checks(pdf: &[u8]) -> (Vec<String>, Vec<String>) {if pages > 0 && trims < pages {issues.push("every page needs a trim box".into());}- let (content, fonts) = content(pdf);+ let (content, fonts) = content(file.as_ref());issues.extend(fonts);(content, issues)}/// Transparency and color spaces, then the output intent and fonts, walked through every page's/// content and what it uses.-fn content(pdf: &[u8]) -> (Vec<String>, Vec<String>) {- let Ok(file) = hayro_syntax::Pdf::new(pdf.to_vec()) else {+fn content(file: Option<&hayro_syntax::Pdf>) -> (Vec<String>, Vec<String>) {+ let Some(file) = file else {return (vec!["the file couldn't be read to check its transparency and color spaces".into()], Vec::new());};- let mut fonts = intent_issues(&file);+ let mut fonts = intent_issues(file);let mut found: Vec<(String, Vec<usize>)> = Vec::new();let mut font_found: Vec<(String, Vec<usize>)> = Vec::new();for (i, page) in file.pages().iter().enumerate() {@@ -214,13 +216,9 @@ impl Intent {/// The catalog's `GTS_PDFX` output intents.fn pdfx_intents(file: &hayro_syntax::Pdf) -> Vec<Intent> {- let xref = file.xref();- let Some(catalog) = xref.get::<Dict<'_>>(xref.root_id()) else { return Vec::new() };- let Some(intents) = catalog.get::<Array<'_>>(b"OutputIntents") else { return Vec::new() };let number = |n: i32| usize::try_from(n).ok();- intents- .iter::<Dict<'_>>()- .filter(|oi| oi.get::<Name<'_>>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX"))+ crate::pdfx::pdfx_intents(file)+ .into_iter().map(|oi| {let text = |key: &[u8]| {oi.get::<hayro_syntax::object::String<'_>>(key)diff --git a/crates/pdf/src/x1a_tests.rs b/crates/pdf/src/x1a_tests.rsindex 777d1e2a6..c79aaa172 100644--- a/crates/pdf/src/x1a_tests.rs+++ b/crates/pdf/src/x1a_tests.rs@@ -318,3 +318,13 @@ fn x1a_dropped_inks_warning_says_they_wont_print() {assert!(warnings.iter().any(|w| w.contains("3 tint(s)") && w.contains("dropped and won't print")), "{warnings:?}");assert!(warnings.iter().all(|w| !w.contains("converted to process")), "{warnings:?}");}++/// The output intent and the identification are read as objects: whitespace between tokens (as+/// qpdf and Ghostscript write them) doesn't hide them.+#[test]+fn x1a_checks_ignore_whitespace_between_tokens() {+ let mut objects = tiny_objects("/Resources<<>>", "0 0 0 1 k", "/OutputConditionIdentifier(Custom)/DestOutputProfile 4 0 R", &icc_header(2));+ objects[5] = b"<< /GTS_PDFXVersion (PDF/X-1:2003) /GTS_PDFXConformance (PDF/X-1a:2003) /Trapped /False >>".to_vec();+ objects[6] = b"<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (Custom) /DestOutputProfile 4 0 R >>".to_vec();+ assert_eq!(check_pdfx1a(&assemble(&objects)), Vec::<String>::new());+}