oxidize-pdf 2.16.2

Pure Rust PDF library for AI/RAG: structure-aware chunking with bounding boxes, heading context, and token estimates. No Python, no ML, no C bindings.
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//! Behaviour coverage for the PDF/A validation engine (`pdfa::validator`).
//!
//! The pre-existing `pdfa_integration_test.rs` only feeds a single clean
//! `Document` + `PdfWriter` PDF, which returns early from every deep check, so
//! the `<R: Read + Seek>` methods (transparency, LZW, fonts, colour spaces,
//! JavaScript, external references, embedded files) were never exercised. These
//! tests hand-build PDFs whose object graph triggers each specific violation and
//! assert the exact `ValidationError` variant — plus a negative control per
//! group proving the validator does **not** flag conforming input.

#[path = "common/mod.rs"]
mod common;

use common::pdf_assembler::{assemble_pdf_with_version, stream_obj};
use oxidize_pdf::parser::PdfReader;
use oxidize_pdf::pdfa::{PdfALevel, PdfAValidator, ValidationError};
use std::io::Cursor;

/// Default content stream body (a no-op text block, Flate-free).
fn plain_contents() -> Vec<u8> {
    stream_obj("", b"BT ET")
}

/// Assemble a one-page PDF with full control over catalog extras, page
/// resources, the content stream body, and any trailing objects (5, 6, ...).
///
/// Layout: 1=Catalog, 2=Pages, 3=Page, 4=Contents, then `extra_objs`.
fn doc(
    version: &str,
    catalog_extra: &str,
    resources: &str,
    contents_body: Vec<u8>,
    extra_objs: &[Vec<u8>],
) -> Vec<u8> {
    let mut objects: Vec<Vec<u8>> = vec![
        format!("<< /Type /Catalog /Pages 2 0 R {} >>", catalog_extra).into_bytes(),
        b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
        format!(
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
             /Resources << {} >> /Contents 4 0 R >>",
            resources
        )
        .into_bytes(),
        contents_body,
    ];
    objects.extend_from_slice(extra_objs);
    assemble_pdf_with_version(version, &objects)
}

/// Run the validator and return its error list, panicking if the fixture is not
/// parseable or validation itself errors (both indicate a broken fixture).
fn errors_of(pdf: &[u8], level: PdfALevel) -> Vec<ValidationError> {
    validate_result(pdf, level).expect("validation must not raise a parse error")
}

/// Run the validator and return the raw `Result`, so tests can assert that a
/// broken object graph (e.g. a dangling reference) surfaces as a parse error
/// rather than being silently accepted.
fn validate_result(
    pdf: &[u8],
    level: PdfALevel,
) -> Result<Vec<ValidationError>, oxidize_pdf::pdfa::PdfAError> {
    let mut reader = PdfReader::new(Cursor::new(pdf.to_vec())).expect("fixture must be parseable");
    PdfAValidator::new(level)
        .validate(&mut reader)
        .map(|r| r.errors().to_vec())
}

fn has_version_err(errs: &[ValidationError]) -> bool {
    errs.iter()
        .any(|e| matches!(e, ValidationError::IncompatiblePdfVersion { .. }))
}

// ---------------------------------------------------------------------------
// A. PDF version compatibility
// ---------------------------------------------------------------------------

#[test]
fn a1b_rejects_pdf_1_7() {
    let pdf = doc("1.7", "", "", plain_contents(), &[]);
    let errs = errors_of(&pdf, PdfALevel::A1b);
    assert!(
        errs.iter().any(|e| matches!(
            e,
            ValidationError::IncompatiblePdfVersion { actual, .. } if actual.starts_with("1.7")
        )),
        "PDF/A-1 requires version 1.4; 1.7 must be flagged. got: {:?}",
        errs
    );
}

#[test]
fn a1b_accepts_pdf_1_4_version() {
    let pdf = doc("1.4", "", "", plain_contents(), &[]);
    assert!(
        !has_version_err(&errors_of(&pdf, PdfALevel::A1b)),
        "PDF 1.4 is the exact version PDF/A-1 requires; no version error expected"
    );
}

#[test]
fn a2b_accepts_pdf_1_7_version() {
    let pdf = doc("1.7", "", "", plain_contents(), &[]);
    assert!(
        !has_version_err(&errors_of(&pdf, PdfALevel::A2b)),
        "PDF/A-2 permits 1.4..=1.7; 1.7 must not be flagged"
    );
}

#[test]
fn a2b_rejects_pdf_1_3() {
    let pdf = doc("1.3", "", "", plain_contents(), &[]);
    assert!(
        has_version_err(&errors_of(&pdf, PdfALevel::A2b)),
        "PDF/A-2 lower bound is 1.4; 1.3 must be flagged"
    );
}

// ---------------------------------------------------------------------------
// B. XMP metadata
// ---------------------------------------------------------------------------

/// Metadata stream object carrying the given XMP packet body.
fn metadata_obj(xmp: &str) -> Vec<u8> {
    stream_obj("/Type /Metadata /Subtype /XML", xmp.as_bytes())
}

fn xmp_with(part: &str, conformance: &str) -> String {
    format!(
        "<?xpacket?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF>\
         <rdf:Description xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\
         <pdfaid:part>{}</pdfaid:part>\
         <pdfaid:conformance>{}</pdfaid:conformance>\
         </rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end?>",
        part, conformance
    )
}

#[test]
fn metadata_missing_is_flagged() {
    let pdf = doc("1.4", "", "", plain_contents(), &[]);
    assert!(
        errors_of(&pdf, PdfALevel::A1b)
            .iter()
            .any(|e| matches!(e, ValidationError::XmpMetadataMissing)),
        "a catalog without /Metadata must raise XmpMetadataMissing"
    );
}

#[test]
fn metadata_present_without_pdfa_identifier_is_flagged() {
    let xmp = "<?xpacket?><x:xmpmeta><rdf:RDF><rdf:Description/></rdf:RDF></x:xmpmeta>";
    let pdf = doc(
        "1.4",
        "/Metadata 5 0 R",
        "",
        plain_contents(),
        &[metadata_obj(xmp)],
    );
    let errs = errors_of(&pdf, PdfALevel::A1b);
    assert!(
        errs.iter()
            .any(|e| matches!(e, ValidationError::XmpMissingPdfAIdentifier)),
        "XMP without pdfaid must raise XmpMissingPdfAIdentifier. got: {:?}",
        errs
    );
}

#[test]
fn metadata_part_mismatch_is_flagged() {
    // part 2 declared while validating against PDF/A-1
    let pdf = doc(
        "1.4",
        "/Metadata 5 0 R",
        "",
        plain_contents(),
        &[metadata_obj(&xmp_with("2", "B"))],
    );
    let errs = errors_of(&pdf, PdfALevel::A1b);
    assert!(
        errs.iter().any(|e| matches!(
            e,
            ValidationError::XmpInvalidPdfAIdentifier { details } if details.contains("Part mismatch")
        )),
        "declaring part 2 under A1b must raise a Part mismatch. got: {:?}",
        errs
    );
}

#[test]
fn metadata_conformance_mismatch_is_flagged() {
    // part 1 but conformance A while validating against A1b (conformance B)
    let pdf = doc(
        "1.4",
        "/Metadata 5 0 R",
        "",
        plain_contents(),
        &[metadata_obj(&xmp_with("1", "A"))],
    );
    let errs = errors_of(&pdf, PdfALevel::A1b);
    assert!(
        errs.iter().any(|e| matches!(
            e,
            ValidationError::XmpInvalidPdfAIdentifier { details } if details.contains("Conformance mismatch")
        )),
        "declaring conformance A under A1b must raise a Conformance mismatch. got: {:?}",
        errs
    );
}

#[test]
fn metadata_matching_identifier_passes() {
    let pdf = doc(
        "1.4",
        "/Metadata 5 0 R",
        "",
        plain_contents(),
        &[metadata_obj(&xmp_with("1", "B"))],
    );
    let errs = errors_of(&pdf, PdfALevel::A1b);
    assert!(
        !errs.iter().any(|e| matches!(
            e,
            ValidationError::XmpMetadataMissing
                | ValidationError::XmpMissingPdfAIdentifier
                | ValidationError::XmpInvalidPdfAIdentifier { .. }
        )),
        "a matching part-1 conformance-B identifier must produce no metadata errors. got: {:?}",
        errs
    );
}

#[test]
fn metadata_non_stream_object_is_flagged() {
    // /Metadata points to a plain dictionary, not a stream
    let pdf = doc(
        "1.4",
        "/Metadata 5 0 R",
        "",
        plain_contents(),
        &[b"<< /Type /Metadata >>".to_vec()],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b)
            .iter()
            .any(|e| matches!(e, ValidationError::XmpMetadataMissing)),
        "a non-stream /Metadata object must be treated as missing metadata"
    );
}

// ---------------------------------------------------------------------------
// C. JavaScript (forbidden in all levels)
// ---------------------------------------------------------------------------

fn has_js_at(errs: &[ValidationError], loc: &str) -> bool {
    errs.iter()
        .any(|e| matches!(e, ValidationError::JavaScriptForbidden { location } if location == loc))
}

#[test]
fn javascript_in_names_tree_is_flagged() {
    let pdf = doc(
        "1.4",
        "/Names << /JavaScript << /Names [] >> >>",
        "",
        plain_contents(),
        &[],
    );
    assert!(
        has_js_at(&errors_of(&pdf, PdfALevel::A1b), "Names/JavaScript"),
        "a /Names /JavaScript entry must raise JavaScriptForbidden(Names/JavaScript)"
    );
}

#[test]
fn javascript_in_open_action_is_flagged() {
    let pdf = doc(
        "1.4",
        "/OpenAction << /S /JavaScript /JS (app.alert\\(1\\);) >>",
        "",
        plain_contents(),
        &[],
    );
    assert!(
        has_js_at(&errors_of(&pdf, PdfALevel::A1b), "OpenAction"),
        "an /OpenAction with /S /JavaScript must raise JavaScriptForbidden(OpenAction)"
    );
}

#[test]
fn javascript_in_additional_actions_is_flagged() {
    let pdf = doc(
        "1.4",
        "/AA << /WC << /S /JavaScript /JS (close\\(\\);) >> >>",
        "",
        plain_contents(),
        &[],
    );
    assert!(
        has_js_at(&errors_of(&pdf, PdfALevel::A1b), "Catalog/AA"),
        "an /AA dictionary holding a JavaScript action must raise JavaScriptForbidden(Catalog/AA)"
    );
}

#[test]
fn javascript_in_names_tree_via_reference_is_flagged() {
    // /Names is an indirect object resolving to a dict with a JavaScript tree
    let pdf = doc(
        "1.4",
        "/Names 5 0 R",
        "",
        plain_contents(),
        &[b"<< /JavaScript << /Names [] >> >>".to_vec()],
    );
    assert!(
        has_js_at(&errors_of(&pdf, PdfALevel::A1b), "Names/JavaScript"),
        "an indirect /Names dict with /JavaScript must raise JavaScriptForbidden(Names/JavaScript)"
    );
}

#[test]
fn javascript_in_open_action_via_reference_is_flagged() {
    let pdf = doc(
        "1.4",
        "/OpenAction 5 0 R",
        "",
        plain_contents(),
        &[b"<< /S /JavaScript /JS (app.alert\\(1\\);) >>".to_vec()],
    );
    assert!(
        has_js_at(&errors_of(&pdf, PdfALevel::A1b), "OpenAction"),
        "an indirect /OpenAction JavaScript action must raise JavaScriptForbidden(OpenAction)"
    );
}

#[test]
fn additional_actions_via_reference_is_flagged() {
    // /AA is an indirect dict, and the per-event action is itself an indirect ref
    let pdf = doc(
        "1.4",
        "/AA 5 0 R",
        "",
        plain_contents(),
        &[
            b"<< /WC 6 0 R >>".to_vec(),
            b"<< /S /JavaScript /JS (x) >>".to_vec(),
        ],
    );
    assert!(
        has_js_at(&errors_of(&pdf, PdfALevel::A1b), "Catalog/AA"),
        "an indirect /AA holding an indirect JavaScript action must raise JavaScriptForbidden(Catalog/AA)"
    );
}

#[test]
fn additional_actions_without_javascript_is_not_flagged() {
    let pdf = doc(
        "1.4",
        "/AA << /O << /S /GoTo /D [0 /Fit] >> >>",
        "",
        plain_contents(),
        &[],
    );
    assert!(
        !errors_of(&pdf, PdfALevel::A1b)
            .iter()
            .any(|e| matches!(e, ValidationError::JavaScriptForbidden { .. })),
        "an /AA dictionary with only non-JavaScript actions must not be flagged"
    );
}

#[test]
fn open_action_gotoe_is_flagged_external() {
    let pdf = doc(
        "1.4",
        "/OpenAction << /S /GoToE /T << /R /C >> >>",
        "",
        plain_contents(),
        &[],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::ExternalReferenceForbidden { reference_type } if reference_type == "GoToE"
        )),
        "an embedded-go-to /GoToE action must raise ExternalReferenceForbidden(GoToE)"
    );
}

#[test]
fn dangling_metadata_reference_denies_conformance() {
    // /Metadata points to an object number that does not exist. The lenient
    // parser resolves the missing object to an empty placeholder rather than
    // erroring, so the validator must treat it as missing metadata (fail-safe
    // denial) — never a silent pass.
    let pdf = doc("1.4", "/Metadata 99 0 R", "", plain_contents(), &[]);
    let result =
        validate_result(&pdf, PdfALevel::A1b).expect("lenient parse resolves to no stream");
    assert!(
        result
            .iter()
            .any(|e| matches!(e, ValidationError::XmpMetadataMissing)),
        "a dangling /Metadata reference must be treated as missing metadata, not accepted. got: {:?}",
        result
    );
}

#[test]
fn font_resources_via_reference_are_checked() {
    // /Font is an indirect dict; the font entry is itself an indirect ref
    let pdf = doc(
        "1.4",
        "",
        "/Font 5 0 R",
        plain_contents(),
        &[
            b"<< /F1 6 0 R >>".to_vec(),
            b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
        ],
    );
    assert!(
        has_not_embedded(&errors_of(&pdf, PdfALevel::A1b), "F1"),
        "fonts reached through an indirect /Font resource dict must still be checked for embedding"
    );
}

#[test]
fn extgstate_via_reference_is_checked() {
    let pdf = doc(
        "1.4",
        "",
        "/ExtGState 5 0 R",
        plain_contents(),
        &[b"<< /GS1 << /ca 0.5 >> >>".to_vec()],
    );
    assert!(
        has_transparency(&errors_of(&pdf, PdfALevel::A1b)),
        "an indirect /ExtGState resource dict must still be scanned for transparency"
    );
}

#[test]
fn colorspace_dict_via_reference_is_checked() {
    let pdf = doc(
        "1.4",
        "",
        "/ColorSpace 5 0 R",
        plain_contents(),
        &[b"<< /CS0 /DeviceRGB >>".to_vec()],
    );
    assert!(
        has_invalid_cs(&errors_of(&pdf, PdfALevel::A1b)),
        "an indirect /ColorSpace resource dict must still be validated"
    );
}

#[test]
fn colorspace_value_via_reference_is_resolved() {
    // the colour space entry value is an indirect reference to a /DeviceRGB name
    let pdf = doc(
        "1.4",
        "",
        "/ColorSpace << /CS0 5 0 R >>",
        plain_contents(),
        &[b"/DeviceRGB".to_vec()],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::InvalidColorSpace { color_space, .. } if color_space == "DeviceRGB"
        )),
        "a colour-space value given as an indirect reference must be resolved and validated"
    );
}

#[test]
fn output_intents_via_reference_is_resolved() {
    // /OutputIntents is an indirect reference to the array
    let pdf = doc(
        "1.4",
        "/OutputIntents 5 0 R",
        "/ColorSpace << /CS0 /DeviceRGB >>",
        plain_contents(),
        &[
            b"[6 0 R]".to_vec(),
            b"<< /Type /OutputIntent /S /GTS_PDFA1 >>".to_vec(),
        ],
    );
    assert!(
        !has_invalid_cs(&errors_of(&pdf, PdfALevel::A1b)),
        "an OutputIntent reached through an indirect /OutputIntents array must satisfy device colour"
    );
}

#[test]
fn non_javascript_open_action_is_not_flagged_as_js() {
    let pdf = doc(
        "1.4",
        "/OpenAction << /S /GoTo /D [0 /Fit] >>",
        "",
        plain_contents(),
        &[],
    );
    let errs = errors_of(&pdf, PdfALevel::A1b);
    assert!(
        !errs
            .iter()
            .any(|e| matches!(e, ValidationError::JavaScriptForbidden { .. })),
        "an internal /GoTo action is not JavaScript. got: {:?}",
        errs
    );
}

// ---------------------------------------------------------------------------
// D. External references (forbidden in all levels)
// ---------------------------------------------------------------------------

#[test]
fn open_action_gotor_is_flagged_external() {
    let pdf = doc(
        "1.4",
        "/OpenAction << /S /GoToR /F (other.pdf) /D [0 /Fit] >>",
        "",
        plain_contents(),
        &[],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::ExternalReferenceForbidden { reference_type } if reference_type == "GoToR"
        )),
        "a remote /GoToR open action must raise ExternalReferenceForbidden(GoToR)"
    );
}

#[test]
fn open_action_launch_via_reference_is_flagged_external() {
    // OpenAction is an indirect reference to a Launch action
    let pdf = doc(
        "1.4",
        "/OpenAction 5 0 R",
        "",
        plain_contents(),
        &[b"<< /S /Launch /F (calc.exe) >>".to_vec()],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::ExternalReferenceForbidden { reference_type } if reference_type == "Launch"
        )),
        "an indirect /Launch open action must raise ExternalReferenceForbidden(Launch)"
    );
}

// ---------------------------------------------------------------------------
// E. Transparency (forbidden in PDF/A-1, allowed in PDF/A-2+)
// ---------------------------------------------------------------------------

fn has_transparency(errs: &[ValidationError]) -> bool {
    errs.iter()
        .any(|e| matches!(e, ValidationError::TransparencyForbidden { .. }))
}

#[test]
fn extgstate_fill_alpha_below_one_is_transparency() {
    let pdf = doc(
        "1.4",
        "",
        "/ExtGState << /GS1 << /ca 0.5 >> >>",
        plain_contents(),
        &[],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::TransparencyForbidden { location } if location.contains("ExtGState/GS1/ca")
        )),
        "fill alpha (ca) != 1.0 is transparency forbidden in PDF/A-1"
    );
}

#[test]
fn extgstate_stroke_alpha_below_one_is_transparency() {
    let pdf = doc(
        "1.4",
        "",
        "/ExtGState << /GS1 << /CA 0.25 >> >>",
        plain_contents(),
        &[],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::TransparencyForbidden { location } if location.contains("ExtGState/GS1/CA")
        )),
        "stroke alpha (CA) != 1.0 is transparency forbidden in PDF/A-1"
    );
}

#[test]
fn extgstate_soft_mask_is_transparency() {
    let pdf = doc(
        "1.4",
        "",
        "/ExtGState << /GS1 << /SMask << /S /Alpha /G 5 0 R >> >> >>",
        plain_contents(),
        &[stream_obj("/Type /XObject /Subtype /Form", b"")],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::TransparencyForbidden { location } if location.contains("ExtGState/GS1/SMask")
        )),
        "a non-/None SMask in ExtGState is transparency forbidden in PDF/A-1"
    );
}

#[test]
fn extgstate_non_normal_blend_mode_is_transparency() {
    let pdf = doc(
        "1.4",
        "",
        "/ExtGState << /GS1 << /BM /Multiply >> >>",
        plain_contents(),
        &[],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::TransparencyForbidden { location } if location.contains("BM=Multiply")
        )),
        "a non-Normal blend mode is transparency forbidden in PDF/A-1"
    );
}

#[test]
fn xobject_transparency_group_is_flagged() {
    let pdf = doc(
        "1.4",
        "",
        "/XObject << /Fm0 5 0 R >>",
        plain_contents(),
        &[stream_obj(
            "/Type /XObject /Subtype /Form /Group << /S /Transparency >> /BBox [0 0 10 10]",
            b"",
        )],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::TransparencyForbidden { location } if location.contains("transparency group")
        )),
        "a Form XObject with a /Transparency group is forbidden in PDF/A-1"
    );
}

#[test]
fn image_xobject_with_smask_is_flagged() {
    let pdf = doc(
        "1.4",
        "",
        "/XObject << /Im0 5 0 R >>",
        plain_contents(),
        &[stream_obj(
            "/Type /XObject /Subtype /Image /Width 1 /Height 1 /SMask 6 0 R \
             /ColorSpace /DeviceGray /BitsPerComponent 8",
            b"\x00",
        )],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::TransparencyForbidden { location } if location.contains("has SMask")
        )),
        "an Image XObject carrying an /SMask is forbidden in PDF/A-1"
    );
}

#[test]
fn conforming_extgstate_has_no_transparency_error() {
    let pdf = doc(
        "1.4",
        "",
        "/ExtGState << /GS1 << /ca 1.0 /CA 1 /SMask /None /BM /Normal >> >>",
        plain_contents(),
        &[],
    );
    assert!(
        !has_transparency(&errors_of(&pdf, PdfALevel::A1b)),
        "opaque alphas, /SMask /None and /BM /Normal are PDF/A-1 conforming"
    );
}

#[test]
fn transparency_is_allowed_in_pdfa_2() {
    // identical translucent ExtGState, but A2 permits transparency → check skipped
    let pdf = doc(
        "1.7",
        "",
        "/ExtGState << /GS1 << /ca 0.5 >> >>",
        plain_contents(),
        &[],
    );
    assert!(
        !has_transparency(&errors_of(&pdf, PdfALevel::A2b)),
        "PDF/A-2 allows transparency, so ca 0.5 must not be flagged"
    );
}

// ---------------------------------------------------------------------------
// F. LZW compression (forbidden in PDF/A-1, allowed in PDF/A-2+)
// ---------------------------------------------------------------------------

fn has_lzw(errs: &[ValidationError]) -> bool {
    errs.iter()
        .any(|e| matches!(e, ValidationError::LzwCompressionForbidden { .. }))
}

#[test]
fn lzw_in_content_stream_is_flagged() {
    let pdf = doc(
        "1.4",
        "",
        "",
        stream_obj("/Filter /LZWDecode", b"\x80\x0b\x60"),
        &[],
    );
    assert!(
        has_lzw(&errors_of(&pdf, PdfALevel::A1b)),
        "an LZW-filtered content stream is forbidden in PDF/A-1"
    );
}

#[test]
fn lzw_in_xobject_stream_is_flagged() {
    let pdf = doc(
        "1.4",
        "",
        "/XObject << /Im0 5 0 R >>",
        plain_contents(),
        &[stream_obj(
            "/Type /XObject /Subtype /Image /Width 1 /Height 1 \
             /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /LZWDecode",
            b"\x80\x0b\x60",
        )],
    );
    assert!(
        has_lzw(&errors_of(&pdf, PdfALevel::A1b)),
        "an LZW-filtered XObject stream is forbidden in PDF/A-1"
    );
}

#[test]
fn lzw_in_filter_array_is_flagged() {
    let pdf = doc(
        "1.4",
        "",
        "",
        stream_obj("/Filter [/ASCII85Decode /LZWDecode]", b"data~>"),
        &[],
    );
    assert!(
        has_lzw(&errors_of(&pdf, PdfALevel::A1b)),
        "LZWDecode anywhere in a /Filter array is forbidden in PDF/A-1"
    );
}

#[test]
fn flate_content_stream_has_no_lzw_error() {
    let pdf = doc(
        "1.4",
        "",
        "",
        stream_obj("/Filter /FlateDecode", b"\x78\x9c\x03\x00\x00\x00\x00\x01"),
        &[],
    );
    assert!(
        !has_lzw(&errors_of(&pdf, PdfALevel::A1b)),
        "a FlateDecode stream must not be flagged as LZW"
    );
}

#[test]
fn lzw_is_allowed_in_pdfa_2() {
    let pdf = doc(
        "1.7",
        "",
        "",
        stream_obj("/Filter /LZWDecode", b"\x80\x0b\x60"),
        &[],
    );
    assert!(
        !has_lzw(&errors_of(&pdf, PdfALevel::A2b)),
        "PDF/A-2 permits LZW, so an LZW content stream must not be flagged"
    );
}

// ---------------------------------------------------------------------------
// G. Embedded files (forbidden in PDF/A-1 and -2, allowed in -3)
// ---------------------------------------------------------------------------

#[test]
fn embedded_files_forbidden_in_pdfa_1() {
    let pdf = doc(
        "1.4",
        "/Names << /EmbeddedFiles << /Names [] >> >>",
        "",
        plain_contents(),
        &[],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b)
            .iter()
            .any(|e| matches!(e, ValidationError::EmbeddedFileForbidden)),
        "a /Names /EmbeddedFiles tree is forbidden in PDF/A-1"
    );
}

#[test]
fn embedded_files_allowed_in_pdfa_3() {
    let pdf = doc(
        "1.7",
        "/Names << /EmbeddedFiles << /Names [] >> >>",
        "",
        plain_contents(),
        &[],
    );
    assert!(
        !errors_of(&pdf, PdfALevel::A3b)
            .iter()
            .any(|e| matches!(e, ValidationError::EmbeddedFileForbidden)),
        "PDF/A-3 permits embedded files"
    );
}

// ---------------------------------------------------------------------------
// H. Fonts
// ---------------------------------------------------------------------------

fn has_not_embedded(errs: &[ValidationError], name: &str) -> bool {
    errs.iter()
        .any(|e| matches!(e, ValidationError::FontNotEmbedded { font_name } if font_name == name))
}

#[test]
fn font_without_descriptor_is_not_embedded() {
    let pdf = doc(
        "1.4",
        "",
        "/Font << /F1 5 0 R >>",
        plain_contents(),
        &[b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec()],
    );
    assert!(
        has_not_embedded(&errors_of(&pdf, PdfALevel::A1b), "F1"),
        "a Type1 font with no FontDescriptor must be reported as not embedded"
    );
}

#[test]
fn font_descriptor_without_fontfile_is_not_embedded() {
    let pdf = doc(
        "1.4",
        "",
        "/Font << /F1 5 0 R >>",
        plain_contents(),
        &[
            b"<< /Type /Font /Subtype /TrueType /BaseFont /Arial /FontDescriptor 6 0 R >>".to_vec(),
            b"<< /Type /FontDescriptor /FontName /Arial /Flags 32 >>".to_vec(),
        ],
    );
    assert!(
        has_not_embedded(&errors_of(&pdf, PdfALevel::A1b), "F1"),
        "a FontDescriptor lacking FontFile/2/3 means the font is not embedded"
    );
}

#[test]
fn font_descriptor_with_fontfile_is_embedded() {
    let pdf = doc(
        "1.4",
        "",
        "/Font << /F1 5 0 R >>",
        plain_contents(),
        &[
            b"<< /Type /Font /Subtype /TrueType /BaseFont /Arial /FontDescriptor 6 0 R >>".to_vec(),
            b"<< /Type /FontDescriptor /FontName /Arial /Flags 32 /FontFile2 7 0 R >>".to_vec(),
            stream_obj("/Length1 4", b"FONT"),
        ],
    );
    assert!(
        !has_not_embedded(&errors_of(&pdf, PdfALevel::A1b), "F1"),
        "a FontDescriptor with FontFile2 means the font is embedded"
    );
}

#[test]
fn type0_font_without_descendants_is_not_embedded() {
    let pdf = doc(
        "1.4",
        "",
        "/Font << /F1 5 0 R >>",
        plain_contents(),
        &[b"<< /Type /Font /Subtype /Type0 /BaseFont /X /Encoding /Identity-H >>".to_vec()],
    );
    assert!(
        has_not_embedded(&errors_of(&pdf, PdfALevel::A1b), "F1"),
        "a Type0 font with no /DescendantFonts must be reported as not embedded"
    );
}

#[test]
fn type0_descendant_without_fontfile_is_not_embedded() {
    let pdf = doc(
        "1.4",
        "",
        "/Font << /F1 5 0 R >>",
        plain_contents(),
        &[
            b"<< /Type /Font /Subtype /Type0 /BaseFont /X /Encoding /Identity-H \
              /DescendantFonts [6 0 R] >>"
                .to_vec(),
            b"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /X /FontDescriptor 7 0 R >>".to_vec(),
            b"<< /Type /FontDescriptor /FontName /X /Flags 4 >>".to_vec(),
        ],
    );
    assert!(
        has_not_embedded(&errors_of(&pdf, PdfALevel::A1b), "F1"),
        "a Type0 CIDFont descriptor lacking FontFile means not embedded"
    );
}

#[test]
fn type0_descendant_with_fontfile_is_embedded() {
    let pdf = doc(
        "1.4",
        "",
        "/Font << /F1 5 0 R >>",
        plain_contents(),
        &[
            b"<< /Type /Font /Subtype /Type0 /BaseFont /X /Encoding /Identity-H \
              /DescendantFonts [6 0 R] >>"
                .to_vec(),
            b"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /X /FontDescriptor 7 0 R >>".to_vec(),
            b"<< /Type /FontDescriptor /FontName /X /Flags 4 /FontFile2 8 0 R >>".to_vec(),
            stream_obj("/Length1 4", b"FONT"),
        ],
    );
    assert!(
        !has_not_embedded(&errors_of(&pdf, PdfALevel::A1b), "F1"),
        "a Type0 CIDFont descriptor with FontFile2 means embedded"
    );
}

#[test]
fn level_a_type3_without_tounicode_lacks_unicode_mapping() {
    let pdf = doc(
        "1.4",
        "",
        "/Font << /F1 5 0 R >>",
        plain_contents(),
        &[b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1 1] \
           /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << >> /Encoding << >> >>"
            .to_vec()],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1a).iter().any(|e| matches!(
            e,
            ValidationError::FontMissingToUnicode { font_name } if font_name == "F1"
        )),
        "a Type3 font without /ToUnicode fails Level A (accessibility) conformance"
    );
}

#[test]
fn level_a_type0_identity_encoding_without_tounicode_passes() {
    let pdf = doc(
        "1.4",
        "",
        "/Font << /F1 5 0 R >>",
        plain_contents(),
        &[
            b"<< /Type /Font /Subtype /Type0 /BaseFont /X /Encoding /Identity-H \
              /DescendantFonts [6 0 R] >>"
                .to_vec(),
            b"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /X /FontDescriptor 7 0 R >>".to_vec(),
            b"<< /Type /FontDescriptor /FontName /X /Flags 4 /FontFile2 8 0 R >>".to_vec(),
            stream_obj("/Length1 4", b"FONT"),
        ],
    );
    assert!(
        !errors_of(&pdf, PdfALevel::A1a)
            .iter()
            .any(|e| matches!(e, ValidationError::FontMissingToUnicode { .. })),
        "Identity-H encoding is an acceptable Unicode mapping for Level A"
    );
}

// ---------------------------------------------------------------------------
// I. Colour spaces / OutputIntent
// ---------------------------------------------------------------------------

fn has_invalid_cs(errs: &[ValidationError]) -> bool {
    errs.iter()
        .any(|e| matches!(e, ValidationError::InvalidColorSpace { .. }))
}

#[test]
fn device_rgb_without_output_intent_is_invalid() {
    let pdf = doc(
        "1.4",
        "",
        "/ColorSpace << /CS0 /DeviceRGB >>",
        plain_contents(),
        &[],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::InvalidColorSpace { color_space, location }
                if color_space == "DeviceRGB" && location.contains("ColorSpace/CS0")
        )),
        "a device-dependent colour space without an OutputIntent is invalid for PDF/A"
    );
}

#[test]
fn device_rgb_with_output_intent_dest_profile_is_valid() {
    let pdf = doc(
        "1.4",
        "/OutputIntents [5 0 R]",
        "/ColorSpace << /CS0 /DeviceRGB >>",
        plain_contents(),
        &[
            b"<< /Type /OutputIntent /S /GTS_PDFA1 /DestOutputProfile 6 0 R >>".to_vec(),
            stream_obj("/N 3", b"ICCPROFILE"),
        ],
    );
    assert!(
        !has_invalid_cs(&errors_of(&pdf, PdfALevel::A1b)),
        "DeviceRGB is permitted when a valid OutputIntent (DestOutputProfile) is present"
    );
}

#[test]
fn output_intent_pdfa_subtype_satisfies_device_colour() {
    // OutputIntent identified only by its /S subtype containing PDFA
    let pdf = doc(
        "1.4",
        "/OutputIntents [5 0 R]",
        "/ColorSpace << /CS0 /DeviceCMYK >>",
        plain_contents(),
        &[b"<< /Type /OutputIntent /S /GTS_PDFA1 >>".to_vec()],
    );
    assert!(
        !has_invalid_cs(&errors_of(&pdf, PdfALevel::A1b)),
        "an OutputIntent whose /S subtype names PDFA satisfies device colour usage"
    );
}

#[test]
fn icc_based_array_colour_space_is_not_device_dependent() {
    let pdf = doc(
        "1.4",
        "",
        "/ColorSpace << /CS0 [/ICCBased 5 0 R] >>",
        plain_contents(),
        &[stream_obj("/N 3", b"ICCPROFILE")],
    );
    assert!(
        !has_invalid_cs(&errors_of(&pdf, PdfALevel::A1b)),
        "an ICCBased colour space is device-independent and must not be flagged"
    );
}

#[test]
fn image_xobject_device_cmyk_without_output_intent_is_invalid() {
    let pdf = doc(
        "1.4",
        "",
        "/XObject << /Im0 5 0 R >>",
        plain_contents(),
        &[stream_obj(
            "/Type /XObject /Subtype /Image /Width 1 /Height 1 \
             /ColorSpace /DeviceCMYK /BitsPerComponent 8",
            b"\x00\x00\x00\x00",
        )],
    );
    assert!(
        errors_of(&pdf, PdfALevel::A1b).iter().any(|e| matches!(
            e,
            ValidationError::InvalidColorSpace { color_space, location }
                if color_space == "DeviceCMYK" && location.contains("XObject/Im0")
        )),
        "a DeviceCMYK image without an OutputIntent is invalid for PDF/A"
    );
}