pdfpurr 0.4.0

A comprehensive pure-Rust PDF library for reading, writing, rendering, and validating PDF documents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! PDF/X validation (ISO 15930).
//!
//! Checks whether a [`Document`] conforms to PDF/X print production standards.
//! Each check function returns a [`StandardsCheck`]; the top-level
//! [`validate_pdfx`] aggregates them into a [`StandardsReport`].

use crate::core::objects::DictExt;
use crate::document::Document;

use super::common::{
    PdfXLevel, StandardsCheck, StandardsReport, CHECK_OUTPUT_INTENT_PDFX, CHECK_TRIM_OR_ART_BOX,
};
use super::pdfa;

const DESC_OUTPUT_INTENT: &str = "OutputIntents with GTS_PDFX must be present";
const DESC_TRIM_OR_ART_BOX: &str = "Every page must have /TrimBox or /ArtBox";

/// Validates a document against PDF/X requirements.
pub fn validate_pdfx(doc: &Document, level: PdfXLevel) -> StandardsReport {
    let mut checks = vec![
        pdfa::check_no_encryption(doc),
        check_output_intent_pdfx(doc),
        check_trim_or_art_box(doc),
        pdfa::check_fonts_embedded(doc),
    ];
    if level == PdfXLevel::X1a {
        checks.push(pdfa::check_no_transparency(doc));
    }
    StandardsReport {
        standard: format!("{}", level),
        checks,
    }
}

/// Checks for `/OutputIntents` with `/S /GTS_PDFX`.
fn check_output_intent_pdfx(doc: &Document) -> StandardsCheck {
    let fail =
        |detail: &str| StandardsCheck::fail(CHECK_OUTPUT_INTENT_PDFX, DESC_OUTPUT_INTENT, detail);

    let catalog = match doc.catalog() {
        Ok(c) => c,
        Err(_) => return fail("Cannot access catalog"),
    };

    let intents = match catalog
        .get_str("OutputIntents")
        .and_then(|o| doc.resolve(o))
        .and_then(|o| o.as_array())
    {
        Some(arr) => arr,
        None => return fail("Catalog has no /OutputIntents"),
    };

    let has_pdfx = intents.iter().any(|intent_obj| {
        doc.resolve(intent_obj)
            .and_then(|o| o.as_dict())
            .and_then(|d| d.get_name("S"))
            .map(|s| s == "GTS_PDFX")
            .unwrap_or(false)
    });

    if has_pdfx {
        StandardsCheck::pass(CHECK_OUTPUT_INTENT_PDFX, DESC_OUTPUT_INTENT)
    } else {
        fail("No OutputIntent with /S /GTS_PDFX found")
    }
}

/// Checks that every page has a `/TrimBox` or `/ArtBox`.
fn check_trim_or_art_box(doc: &Document) -> StandardsCheck {
    let mut details = Vec::new();

    if let Ok(pages) = doc.pages() {
        for (i, page) in pages.iter().enumerate() {
            let has_trim = page.get_str("TrimBox").is_some();
            let has_art = page.get_str("ArtBox").is_some();
            if !has_trim && !has_art {
                details.push(format!("Page {} has no /TrimBox or /ArtBox", i + 1));
            }
        }
    }

    StandardsCheck::from_details(CHECK_TRIM_OR_ART_BOX, DESC_TRIM_OR_ART_BOX, details)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::objects::{Dictionary, IndirectRef, Object, PdfName, PdfStream, PdfString};

    fn test_doc() -> Document {
        Document::new()
    }

    /// Adds OutputIntents with given /S value to the catalog.
    fn add_output_intent(doc: &mut Document, subtype: &str) {
        let mut intent = Dictionary::new();
        intent.insert(PdfName::new("S"), Object::Name(PdfName::new(subtype)));
        intent.insert(
            PdfName::new("OutputConditionIdentifier"),
            Object::String(PdfString::from_literal("CGATS TR 001")),
        );
        let intent_id = doc.add_object(Object::Dictionary(intent));

        let catalog_id = (1u32, 0u16);
        if let Some(Object::Dictionary(ref mut catalog)) = doc.get_object_mut(catalog_id) {
            catalog.insert(
                PdfName::new("OutputIntents"),
                Object::Array(vec![Object::Reference(IndirectRef::new(
                    intent_id.0,
                    intent_id.1,
                ))]),
            );
        }
    }

    /// Creates a document with a page that has the given boxes.
    fn doc_with_page_box(box_name: Option<&str>) -> Document {
        let mut doc = Document::new();

        let mut page = Dictionary::new();
        page.insert(PdfName::new("Type"), Object::Name(PdfName::new("Page")));
        page.insert(
            PdfName::new("Parent"),
            Object::Reference(IndirectRef::new(2, 0)),
        );
        page.insert(
            PdfName::new("MediaBox"),
            Object::Array(vec![
                Object::Integer(0),
                Object::Integer(0),
                Object::Integer(612),
                Object::Integer(792),
            ]),
        );
        if let Some(name) = box_name {
            page.insert(
                PdfName::new(name),
                Object::Array(vec![
                    Object::Integer(10),
                    Object::Integer(10),
                    Object::Integer(602),
                    Object::Integer(782),
                ]),
            );
        }
        let page_id = doc.add_object(Object::Dictionary(page));

        if let Some(Object::Dictionary(ref mut pages)) = doc.get_object_mut((2, 0)) {
            pages.insert(
                PdfName::new("Kids"),
                Object::Array(vec![Object::Reference(IndirectRef::new(
                    page_id.0, page_id.1,
                ))]),
            );
            pages.insert(PdfName::new("Count"), Object::Integer(1));
        }

        doc
    }

    /// Creates a document with transparency on a page.
    fn doc_with_transparency() -> Document {
        let mut doc = Document::new();

        let mut group = Dictionary::new();
        group.insert(
            PdfName::new("S"),
            Object::Name(PdfName::new("Transparency")),
        );
        let group_id = doc.add_object(Object::Dictionary(group));

        let mut page = Dictionary::new();
        page.insert(PdfName::new("Type"), Object::Name(PdfName::new("Page")));
        page.insert(
            PdfName::new("Parent"),
            Object::Reference(IndirectRef::new(2, 0)),
        );
        page.insert(
            PdfName::new("MediaBox"),
            Object::Array(vec![
                Object::Integer(0),
                Object::Integer(0),
                Object::Integer(612),
                Object::Integer(792),
            ]),
        );
        page.insert(
            PdfName::new("Group"),
            Object::Reference(IndirectRef::new(group_id.0, group_id.1)),
        );
        let page_id = doc.add_object(Object::Dictionary(page));

        if let Some(Object::Dictionary(ref mut pages)) = doc.get_object_mut((2, 0)) {
            pages.insert(
                PdfName::new("Kids"),
                Object::Array(vec![Object::Reference(IndirectRef::new(
                    page_id.0, page_id.1,
                ))]),
            );
            pages.insert(PdfName::new("Count"), Object::Integer(1));
        }

        doc
    }

    /// Creates a document with an embedded font on a page.
    fn doc_with_embedded_font() -> Document {
        let mut doc = Document::new();

        let font_stream = PdfStream::new(Dictionary::new(), vec![0u8; 100]);
        let file_id = doc.add_object(Object::Stream(font_stream));

        let mut desc = Dictionary::new();
        desc.insert(
            PdfName::new("Type"),
            Object::Name(PdfName::new("FontDescriptor")),
        );
        desc.insert(
            PdfName::new("FontFile2"),
            Object::Reference(IndirectRef::new(file_id.0, file_id.1)),
        );
        let desc_id = doc.add_object(Object::Dictionary(desc));

        let mut font = Dictionary::new();
        font.insert(PdfName::new("Type"), Object::Name(PdfName::new("Font")));
        font.insert(
            PdfName::new("FontDescriptor"),
            Object::Reference(IndirectRef::new(desc_id.0, desc_id.1)),
        );
        let font_id = doc.add_object(Object::Dictionary(font));

        let mut font_res = Dictionary::new();
        font_res.insert(
            PdfName::new("F1"),
            Object::Reference(IndirectRef::new(font_id.0, font_id.1)),
        );
        let font_res_id = doc.add_object(Object::Dictionary(font_res));

        let mut resources = Dictionary::new();
        resources.insert(
            PdfName::new("Font"),
            Object::Reference(IndirectRef::new(font_res_id.0, font_res_id.1)),
        );
        let res_id = doc.add_object(Object::Dictionary(resources));

        let mut page = Dictionary::new();
        page.insert(PdfName::new("Type"), Object::Name(PdfName::new("Page")));
        page.insert(
            PdfName::new("Parent"),
            Object::Reference(IndirectRef::new(2, 0)),
        );
        page.insert(
            PdfName::new("MediaBox"),
            Object::Array(vec![
                Object::Integer(0),
                Object::Integer(0),
                Object::Integer(612),
                Object::Integer(792),
            ]),
        );
        page.insert(
            PdfName::new("Resources"),
            Object::Reference(IndirectRef::new(res_id.0, res_id.1)),
        );
        let page_id = doc.add_object(Object::Dictionary(page));

        if let Some(Object::Dictionary(ref mut pages)) = doc.get_object_mut((2, 0)) {
            pages.insert(
                PdfName::new("Kids"),
                Object::Array(vec![Object::Reference(IndirectRef::new(
                    page_id.0, page_id.1,
                ))]),
            );
            pages.insert(PdfName::new("Count"), Object::Integer(1));
        }

        doc
    }

    // --- 8F Tests: OutputIntent ---

    #[test]
    fn pdfx_output_intent_present_passes() {
        let mut doc = test_doc();
        add_output_intent(&mut doc, "GTS_PDFX");
        let check = check_output_intent_pdfx(&doc);
        assert!(check.passed);
    }

    #[test]
    fn pdfx_output_intent_missing_fails() {
        let doc = test_doc();
        let check = check_output_intent_pdfx(&doc);
        assert!(!check.passed);
        assert!(check.details[0].contains("no /OutputIntents"));
    }

    #[test]
    fn pdfx_output_intent_wrong_subtype_fails() {
        let mut doc = test_doc();
        add_output_intent(&mut doc, "GTS_PDFA1");
        let check = check_output_intent_pdfx(&doc);
        assert!(!check.passed);
        assert!(check.details[0].contains("GTS_PDFX"));
    }

    // --- 8F Tests: TrimBox / ArtBox ---

    #[test]
    fn pdfx_trimbox_present_passes() {
        let doc = doc_with_page_box(Some("TrimBox"));
        let check = check_trim_or_art_box(&doc);
        assert!(check.passed);
    }

    #[test]
    fn pdfx_artbox_accepted() {
        let doc = doc_with_page_box(Some("ArtBox"));
        let check = check_trim_or_art_box(&doc);
        assert!(check.passed);
    }

    #[test]
    fn pdfx_no_trimbox_or_artbox_fails() {
        let doc = doc_with_page_box(None);
        let check = check_trim_or_art_box(&doc);
        assert!(!check.passed);
        assert!(check.details[0].contains("no /TrimBox or /ArtBox"));
    }

    // --- 8F Tests: Encryption ---

    #[test]
    fn pdfx_no_encryption_passes() {
        let doc = test_doc();
        let check = pdfa::check_no_encryption(&doc);
        assert!(check.passed);
    }

    #[test]
    fn pdfx_encryption_fails() {
        let mut doc = test_doc();
        let mut encrypt = Dictionary::new();
        encrypt.insert(
            PdfName::new("Filter"),
            Object::Name(PdfName::new("Standard")),
        );
        let id = doc.add_object(Object::Dictionary(encrypt));
        doc.trailer.insert(
            PdfName::new("Encrypt"),
            Object::Reference(IndirectRef::new(id.0, id.1)),
        );
        let check = pdfa::check_no_encryption(&doc);
        assert!(!check.passed);
    }

    // --- 8G Tests: Transparency ---

    #[test]
    fn pdfx1a_no_transparency_passes() {
        let doc = test_doc();
        let report = validate_pdfx(&doc, PdfXLevel::X1a);
        let check = report.checks.iter().find(|c| c.id == "no-transparency");
        assert!(check.is_some());
        assert!(check.unwrap().passed);
    }

    #[test]
    fn pdfx1a_transparency_fails() {
        let doc = doc_with_transparency();
        let report = validate_pdfx(&doc, PdfXLevel::X1a);
        let check = report
            .checks
            .iter()
            .find(|c| c.id == "no-transparency")
            .unwrap();
        assert!(!check.passed);
    }

    #[test]
    fn pdfx4_transparency_allowed() {
        let doc = doc_with_transparency();
        let report = validate_pdfx(&doc, PdfXLevel::X4);
        let check = report.checks.iter().find(|c| c.id == "no-transparency");
        // PDF/X-4 doesn't include transparency check
        assert!(check.is_none());
    }

    // --- 8G Tests: Fonts ---

    #[test]
    fn pdfx_fonts_embedded_passes() {
        let doc = doc_with_embedded_font();
        let check = pdfa::check_fonts_embedded(&doc);
        assert!(check.passed);
    }

    #[test]
    fn pdfx_fonts_not_embedded_fails() {
        let mut doc = Document::new();
        // Add a page with an unembedded font
        let mut font = Dictionary::new();
        font.insert(PdfName::new("Type"), Object::Name(PdfName::new("Font")));
        font.insert(
            PdfName::new("BaseFont"),
            Object::Name(PdfName::new("Helvetica")),
        );
        let font_id = doc.add_object(Object::Dictionary(font));

        let mut font_res = Dictionary::new();
        font_res.insert(
            PdfName::new("F1"),
            Object::Reference(IndirectRef::new(font_id.0, font_id.1)),
        );
        let font_res_id = doc.add_object(Object::Dictionary(font_res));

        let mut resources = Dictionary::new();
        resources.insert(
            PdfName::new("Font"),
            Object::Reference(IndirectRef::new(font_res_id.0, font_res_id.1)),
        );
        let res_id = doc.add_object(Object::Dictionary(resources));

        let mut page = Dictionary::new();
        page.insert(PdfName::new("Type"), Object::Name(PdfName::new("Page")));
        page.insert(
            PdfName::new("Parent"),
            Object::Reference(IndirectRef::new(2, 0)),
        );
        page.insert(
            PdfName::new("MediaBox"),
            Object::Array(vec![
                Object::Integer(0),
                Object::Integer(0),
                Object::Integer(612),
                Object::Integer(792),
            ]),
        );
        page.insert(
            PdfName::new("Resources"),
            Object::Reference(IndirectRef::new(res_id.0, res_id.1)),
        );
        let page_id = doc.add_object(Object::Dictionary(page));

        if let Some(Object::Dictionary(ref mut pages)) = doc.get_object_mut((2, 0)) {
            pages.insert(
                PdfName::new("Kids"),
                Object::Array(vec![Object::Reference(IndirectRef::new(
                    page_id.0, page_id.1,
                ))]),
            );
            pages.insert(PdfName::new("Count"), Object::Integer(1));
        }

        let check = pdfa::check_fonts_embedded(&doc);
        assert!(!check.passed);
    }

    // --- 8G Tests: Top-level Validator ---

    #[test]
    fn validate_pdfx_1a_full_report() {
        let mut doc = doc_with_page_box(Some("TrimBox"));
        add_output_intent(&mut doc, "GTS_PDFX");
        let report = validate_pdfx(&doc, PdfXLevel::X1a);
        // Should have: encryption, output intent, trim box, fonts, transparency = 5
        assert_eq!(report.total_checks(), 5);
        assert_eq!(report.standard, "PDF/X-1a:2001");
    }

    #[test]
    fn document_validate_pdfx_method() {
        let doc = test_doc();
        let report = validate_pdfx(&doc, PdfXLevel::X3);
        assert!(report.total_checks() > 0);
        assert_eq!(report.standard, "PDF/X-3:2002");
    }
}