pdf_oxide 0.3.22

The fastest Rust PDF library with text extraction: 0.8ms mean, 100% pass rate on 3,830 PDFs. 5× faster than pdf_extract, 17× faster than oxidize_pdf. Extract, create, and edit PDFs.
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
//! PDF/UA (Universal Accessibility) validation module.
//!
//! This module provides functionality for validating PDF documents against
//! PDF/UA (ISO 14289) accessibility standards.
//!
//! ## PDF/UA Requirements Overview
//!
//! PDF/UA documents must:
//! - Be Tagged PDFs (logical structure)
//! - Include all content in the structure tree
//! - Specify document language
//! - Use standard structure types or role-mapped types
//! - Provide alternative text for images
//! - Have accessible names for form fields
//! - Properly associate table headers with cells
//! - Follow natural reading order
//! - Not rely on JavaScript for critical content
//! - Have document title in metadata
//!
//! ## Standards Reference
//!
//! - ISO 14289-1:2014 (PDF/UA-1)
//! - ISO 14289-2 (PDF/UA-2, in development)
//!
//! ## Example
//!
//! ```ignore
//! use pdf_oxide::compliance::{PdfUaValidator, PdfUaLevel, UaValidationResult};
//!
//! let mut pdf = Pdf::open("document.pdf")?;
//!
//! let validator = PdfUaValidator::new();
//! let result = validator.validate(&mut pdf, PdfUaLevel::Ua1)?;
//!
//! if result.is_compliant {
//!     println!("Document is PDF/UA-1 compliant");
//! } else {
//!     for error in &result.errors {
//!         println!("Accessibility violation: {}", error);
//!     }
//! }
//! ```

use super::types::{ComplianceWarning, WarningCode};
use crate::document::PdfDocument;
use crate::error::Result;
use crate::object::Object;
use std::fmt;

/// PDF/UA conformance level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PdfUaLevel {
    /// PDF/UA-1 (ISO 14289-1:2014)
    Ua1,
    /// PDF/UA-2 (in development, based on PDF 2.0)
    Ua2,
}

impl fmt::Display for PdfUaLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PdfUaLevel::Ua1 => write!(f, "PDF/UA-1"),
            PdfUaLevel::Ua2 => write!(f, "PDF/UA-2"),
        }
    }
}

impl PdfUaLevel {
    /// Get the XMP pdfuaid:part value.
    pub fn xmp_part(&self) -> &'static str {
        match self {
            PdfUaLevel::Ua1 => "1",
            PdfUaLevel::Ua2 => "2",
        }
    }
}

/// Result of PDF/UA validation.
#[derive(Debug, Clone)]
pub struct UaValidationResult {
    /// Whether the document is compliant with the target level.
    pub is_compliant: bool,
    /// The level validated against.
    pub level: PdfUaLevel,
    /// Accessibility errors (violations).
    pub errors: Vec<UaComplianceError>,
    /// Accessibility warnings (non-fatal issues).
    pub warnings: Vec<ComplianceWarning>,
    /// Summary statistics.
    pub stats: UaValidationStats,
}

impl Default for UaValidationResult {
    fn default() -> Self {
        Self {
            is_compliant: true,
            level: PdfUaLevel::Ua1,
            errors: Vec::new(),
            warnings: Vec::new(),
            stats: UaValidationStats::default(),
        }
    }
}

impl UaValidationResult {
    /// Create a new validation result for a specific level.
    pub fn new(level: PdfUaLevel) -> Self {
        Self {
            level,
            ..Default::default()
        }
    }

    /// Add an error to the result.
    pub fn add_error(&mut self, error: UaComplianceError) {
        self.errors.push(error);
        self.is_compliant = false;
    }

    /// Add a warning to the result.
    pub fn add_warning(&mut self, warning: ComplianceWarning) {
        self.warnings.push(warning);
    }

    /// Check if there are any errors.
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Check if there are any warnings.
    pub fn has_warnings(&self) -> bool {
        !self.warnings.is_empty()
    }
}

/// PDF/UA validation statistics.
#[derive(Debug, Clone, Default)]
pub struct UaValidationStats {
    /// Number of structure elements checked.
    pub structure_elements_checked: usize,
    /// Number of images checked.
    pub images_checked: usize,
    /// Number of images with alt text.
    pub images_with_alt: usize,
    /// Number of tables checked.
    pub tables_checked: usize,
    /// Number of form fields checked.
    pub form_fields_checked: usize,
    /// Number of annotations checked.
    pub annotations_checked: usize,
    /// Number of pages checked.
    pub pages_checked: usize,
}

/// PDF/UA compliance error (accessibility violation).
#[derive(Debug, Clone)]
pub struct UaComplianceError {
    /// Error code.
    pub code: UaErrorCode,
    /// Human-readable message.
    pub message: String,
    /// Location in the document (if applicable).
    pub location: Option<String>,
    /// WCAG reference (if applicable).
    pub wcag_ref: Option<String>,
    /// ISO 14289 clause reference.
    pub clause: Option<String>,
}

impl UaComplianceError {
    /// Create a new compliance error.
    pub fn new(code: UaErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            location: None,
            wcag_ref: None,
            clause: None,
        }
    }

    /// Set the location.
    pub fn with_location(mut self, location: impl Into<String>) -> Self {
        self.location = Some(location.into());
        self
    }

    /// Set the WCAG reference.
    pub fn with_wcag(mut self, wcag_ref: impl Into<String>) -> Self {
        self.wcag_ref = Some(wcag_ref.into());
        self
    }

    /// Set the ISO clause reference.
    pub fn with_clause(mut self, clause: impl Into<String>) -> Self {
        self.clause = Some(clause.into());
        self
    }
}

impl fmt::Display for UaComplianceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}] {}", self.code, self.message)?;
        if let Some(ref loc) = self.location {
            write!(f, " (at {})", loc)?;
        }
        if let Some(ref wcag) = self.wcag_ref {
            write!(f, " [WCAG {}]", wcag)?;
        }
        Ok(())
    }
}

/// Error codes for PDF/UA violations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UaErrorCode {
    // Document-level errors
    /// Document is not a Tagged PDF
    NotTaggedPdf,
    /// Missing document language
    MissingLanguage,
    /// Missing document title
    MissingTitle,
    /// Document title not displayed in window title
    TitleNotDisplayed,
    /// Missing PDF/UA identification in XMP
    MissingPdfuaId,
    /// Invalid PDF/UA identification
    InvalidPdfuaId,

    // Structure errors
    /// Content not in structure tree
    ContentNotTagged,
    /// Invalid structure type
    InvalidStructureType,
    /// Role mapping missing for custom type
    MissingRoleMapping,
    /// Invalid nesting of structure elements
    InvalidStructureNesting,
    /// Heading levels not sequential
    HeadingLevelSkipped,

    // Figure/Image errors
    /// Figure missing alternative text
    FigureMissingAlt,
    /// Decorative figure not marked as artifact
    DecorativeNotArtifact,
    /// Figure caption not associated
    FigureCaptionNotAssociated,

    // Table errors
    /// Table missing headers
    TableMissingHeaders,
    /// Table header cell not TH
    TableHeaderNotTh,
    /// Table data cell not TD
    TableDataNotTd,
    /// Table headers not associated with cells
    TableHeadersNotAssociated,
    /// Table scope not specified
    TableScopeMissing,
    /// Complex table without IDs/headers
    ComplexTableNoIds,

    // Form errors
    /// Form field missing accessible name
    FormFieldMissingName,
    /// Form field missing tooltip
    FormFieldMissingTooltip,
    /// Required field not indicated
    RequiredFieldNotIndicated,
    /// Form without submit button
    FormNoSubmitButton,

    // Link errors
    /// Link text not descriptive
    LinkTextNotDescriptive,
    /// Link destination not specified
    LinkNoDestination,

    // List errors
    /// List items not properly marked
    ListItemsNotMarked,
    /// Nested list not properly structured
    NestedListInvalid,

    // Annotation errors
    /// Annotation not tagged
    AnnotationNotTagged,
    /// Annotation missing contents
    AnnotationMissingContents,
    /// Widget missing role
    WidgetMissingRole,

    // Font/Text errors
    /// Font not embedded
    FontNotEmbedded,
    /// Missing Unicode mapping
    MissingUnicodeMapping,
    /// Text without ActualText (for graphical text)
    MissingActualText,

    // Color errors
    /// Insufficient color contrast
    InsufficientContrast,
    /// Color alone conveys information
    ColorOnlyInformation,

    // Other errors
    /// JavaScript without accessible alternative
    JavaScriptNoAlternative,
    /// Audio/video without captions
    MultimediaNoCaptions,
    /// Reading order not logical
    ReadingOrderInvalid,
    /// Bookmark structure doesn't match headings
    BookmarksMismatch,
}

impl fmt::Display for UaErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let code = match self {
            // Document-level
            UaErrorCode::NotTaggedPdf => "UA-DOC-001",
            UaErrorCode::MissingLanguage => "UA-DOC-002",
            UaErrorCode::MissingTitle => "UA-DOC-003",
            UaErrorCode::TitleNotDisplayed => "UA-DOC-004",
            UaErrorCode::MissingPdfuaId => "UA-DOC-005",
            UaErrorCode::InvalidPdfuaId => "UA-DOC-006",

            // Structure
            UaErrorCode::ContentNotTagged => "UA-STRUCT-001",
            UaErrorCode::InvalidStructureType => "UA-STRUCT-002",
            UaErrorCode::MissingRoleMapping => "UA-STRUCT-003",
            UaErrorCode::InvalidStructureNesting => "UA-STRUCT-004",
            UaErrorCode::HeadingLevelSkipped => "UA-STRUCT-005",

            // Figure
            UaErrorCode::FigureMissingAlt => "UA-FIG-001",
            UaErrorCode::DecorativeNotArtifact => "UA-FIG-002",
            UaErrorCode::FigureCaptionNotAssociated => "UA-FIG-003",

            // Table
            UaErrorCode::TableMissingHeaders => "UA-TBL-001",
            UaErrorCode::TableHeaderNotTh => "UA-TBL-002",
            UaErrorCode::TableDataNotTd => "UA-TBL-003",
            UaErrorCode::TableHeadersNotAssociated => "UA-TBL-004",
            UaErrorCode::TableScopeMissing => "UA-TBL-005",
            UaErrorCode::ComplexTableNoIds => "UA-TBL-006",

            // Form
            UaErrorCode::FormFieldMissingName => "UA-FORM-001",
            UaErrorCode::FormFieldMissingTooltip => "UA-FORM-002",
            UaErrorCode::RequiredFieldNotIndicated => "UA-FORM-003",
            UaErrorCode::FormNoSubmitButton => "UA-FORM-004",

            // Link
            UaErrorCode::LinkTextNotDescriptive => "UA-LINK-001",
            UaErrorCode::LinkNoDestination => "UA-LINK-002",

            // List
            UaErrorCode::ListItemsNotMarked => "UA-LIST-001",
            UaErrorCode::NestedListInvalid => "UA-LIST-002",

            // Annotation
            UaErrorCode::AnnotationNotTagged => "UA-ANNOT-001",
            UaErrorCode::AnnotationMissingContents => "UA-ANNOT-002",
            UaErrorCode::WidgetMissingRole => "UA-ANNOT-003",

            // Font/Text
            UaErrorCode::FontNotEmbedded => "UA-TEXT-001",
            UaErrorCode::MissingUnicodeMapping => "UA-TEXT-002",
            UaErrorCode::MissingActualText => "UA-TEXT-003",

            // Color
            UaErrorCode::InsufficientContrast => "UA-COLOR-001",
            UaErrorCode::ColorOnlyInformation => "UA-COLOR-002",

            // Other
            UaErrorCode::JavaScriptNoAlternative => "UA-OTHER-001",
            UaErrorCode::MultimediaNoCaptions => "UA-OTHER-002",
            UaErrorCode::ReadingOrderInvalid => "UA-OTHER-003",
            UaErrorCode::BookmarksMismatch => "UA-OTHER-004",
        };
        write!(f, "{}", code)
    }
}

/// PDF/UA validator.
///
/// Validates PDF documents against PDF/UA (ISO 14289) accessibility standards.
pub struct PdfUaValidator {
    /// Check for heading level sequence.
    check_heading_sequence: bool,
    /// Check for color contrast (approximate).
    check_color_contrast: bool,
    /// Custom structure types that are allowed.
    allowed_custom_types: Vec<String>,
}

impl Default for PdfUaValidator {
    fn default() -> Self {
        Self::new()
    }
}

impl PdfUaValidator {
    /// Create a new PDF/UA validator with default settings.
    pub fn new() -> Self {
        Self {
            check_heading_sequence: true,
            check_color_contrast: false, // Requires rendering, disabled by default
            allowed_custom_types: Vec::new(),
        }
    }

    /// Enable or disable heading sequence checking.
    pub fn check_heading_sequence(mut self, enabled: bool) -> Self {
        self.check_heading_sequence = enabled;
        self
    }

    /// Enable or disable color contrast checking.
    pub fn check_color_contrast(mut self, enabled: bool) -> Self {
        self.check_color_contrast = enabled;
        self
    }

    /// Add allowed custom structure types.
    pub fn allow_custom_types(mut self, types: Vec<String>) -> Self {
        self.allowed_custom_types = types;
        self
    }

    /// Validate a document against the specified PDF/UA level.
    pub fn validate(
        &self,
        document: &mut PdfDocument,
        level: PdfUaLevel,
    ) -> Result<UaValidationResult> {
        let mut result = UaValidationResult::new(level);

        // Core PDF/UA validations
        self.validate_tagged_pdf(document, &mut result)?;
        self.validate_language(document, &mut result)?;
        self.validate_title(document, &mut result)?;
        self.validate_structure_tree(document, &mut result)?;
        self.validate_figures(document, &mut result)?;
        self.validate_tables(document, &mut result)?;
        self.validate_form_fields(document, &mut result)?;
        self.validate_annotations(document, &mut result)?;

        // Set compliance status
        result.is_compliant = result.errors.is_empty();

        Ok(result)
    }

    /// Check if document is a Tagged PDF.
    fn validate_tagged_pdf(
        &self,
        document: &mut PdfDocument,
        result: &mut UaValidationResult,
    ) -> Result<()> {
        let catalog = document.catalog()?;
        let catalog_dict = match catalog {
            Object::Dictionary(d) => d,
            _ => {
                result.add_error(
                    UaComplianceError::new(UaErrorCode::NotTaggedPdf, "Invalid document catalog")
                        .with_clause("7.1"),
                );
                return Ok(());
            },
        };

        // Check for MarkInfo with Marked = true
        let is_marked = if let Some(mark_info) = catalog_dict.get("MarkInfo") {
            let resolved_mark_info = document.resolve_references(mark_info, 1)?;
            if let Object::Dictionary(mi) = resolved_mark_info {
                matches!(mi.get("Marked"), Some(Object::Boolean(true)))
            } else {
                false
            }
        } else {
            false
        };

        if !is_marked {
            result.add_error(
                UaComplianceError::new(
                    UaErrorCode::NotTaggedPdf,
                    "Document must be a Tagged PDF (MarkInfo/Marked = true)",
                )
                .with_clause("7.1")
                .with_wcag("1.3.1"),
            );
        }

        // Check for StructTreeRoot
        if !catalog_dict.contains_key("StructTreeRoot") {
            result.add_error(
                UaComplianceError::new(
                    UaErrorCode::NotTaggedPdf,
                    "Document must have a structure tree (StructTreeRoot)",
                )
                .with_clause("7.1")
                .with_wcag("1.3.1"),
            );
        }

        Ok(())
    }

    /// Check for document language specification.
    fn validate_language(
        &self,
        document: &mut PdfDocument,
        result: &mut UaValidationResult,
    ) -> Result<()> {
        let catalog = document.catalog()?;
        let catalog_dict = match catalog {
            Object::Dictionary(d) => d,
            _ => return Ok(()),
        };

        // Check for /Lang in catalog
        if !catalog_dict.contains_key("Lang") {
            result.add_error(
                UaComplianceError::new(
                    UaErrorCode::MissingLanguage,
                    "Document must specify a primary language (/Lang in catalog)",
                )
                .with_clause("7.2")
                .with_wcag("3.1.1"),
            );
        } else {
            // Validate language tag format (should be BCP 47)
            if let Some(Object::String(lang)) = catalog_dict.get("Lang") {
                let lang_str = String::from_utf8_lossy(lang);
                if lang_str.is_empty() || !is_valid_language_tag(&lang_str) {
                    result.add_warning(ComplianceWarning::new(
                        WarningCode::MissingRecommendedMetadata,
                        format!("Language tag '{}' may not be a valid BCP 47 tag", lang_str),
                    ));
                }
            }
        }

        Ok(())
    }

    /// Check for document title.
    fn validate_title(
        &self,
        document: &mut PdfDocument,
        result: &mut UaValidationResult,
    ) -> Result<()> {
        let catalog = document.catalog()?;
        let catalog_dict = match catalog {
            Object::Dictionary(d) => d,
            _ => return Ok(()),
        };

        // Check ViewerPreferences for DisplayDocTitle
        let display_title = if let Some(vp) = catalog_dict.get("ViewerPreferences") {
            let resolved_vp = document.resolve_references(vp, 1)?;
            if let Object::Dictionary(vp_dict) = resolved_vp {
                matches!(vp_dict.get("DisplayDocTitle"), Some(Object::Boolean(true)))
            } else {
                false
            }
        } else {
            false
        };

        if !display_title {
            result.add_error(
                UaComplianceError::new(
                    UaErrorCode::TitleNotDisplayed,
                    "ViewerPreferences/DisplayDocTitle must be true",
                )
                .with_clause("7.1")
                .with_wcag("2.4.2"),
            );
        }

        // Check for title in document info or XMP metadata
        // Clone the trailer to avoid borrow conflicts
        let trailer = document.trailer().clone();
        let has_title = if let Object::Dictionary(trailer_dict) = trailer {
            if let Some(info_ref) = trailer_dict.get("Info") {
                let info_obj = document.resolve_references(info_ref, 1)?;
                if let Object::Dictionary(info_dict) = info_obj {
                    if let Some(Object::String(title)) = info_dict.get("Title") {
                        !title.is_empty()
                    } else {
                        false
                    }
                } else {
                    false
                }
            } else {
                false
            }
        } else {
            false
        };

        if !has_title {
            result.add_error(
                UaComplianceError::new(
                    UaErrorCode::MissingTitle,
                    "Document must have a title in document info or XMP metadata",
                )
                .with_clause("7.1")
                .with_wcag("2.4.2"),
            );
        }

        Ok(())
    }

    /// Validate structure tree.
    fn validate_structure_tree(
        &self,
        document: &mut PdfDocument,
        result: &mut UaValidationResult,
    ) -> Result<()> {
        let catalog = document.catalog()?;
        let catalog_dict = match catalog {
            Object::Dictionary(d) => d,
            _ => return Ok(()),
        };

        let struct_tree_root = match catalog_dict.get("StructTreeRoot") {
            Some(obj) => document.resolve_references(obj, 1)?,
            None => return Ok(()), // Already reported in validate_tagged_pdf
        };

        if let Object::Dictionary(str_dict) = struct_tree_root {
            // Check for RoleMap (custom structure types need role mapping)
            let has_role_map = str_dict.contains_key("RoleMap");

            // Check for K (children)
            if !str_dict.contains_key("K") {
                result.add_warning(ComplianceWarning::new(
                    WarningCode::PartialCheck,
                    "Structure tree root has no children",
                ));
            }

            // If checking heading sequence, validate heading order
            if self.check_heading_sequence {
                // This would require traversing the structure tree
                // For now, add a warning about partial checking
                result.add_warning(ComplianceWarning::new(
                    WarningCode::PartialCheck,
                    "Heading sequence validation requires full structure tree traversal",
                ));
            }

            result.stats.structure_elements_checked += 1;

            // Suppress unused variable warning
            let _ = has_role_map;
        }

        Ok(())
    }

    /// Validate figures (images) have alternative text.
    fn validate_figures(
        &self,
        document: &mut PdfDocument,
        result: &mut UaValidationResult,
    ) -> Result<()> {
        // Figure validation requires traversing structure tree and checking Alt attributes
        // For now, add a warning about partial checking
        result.add_warning(ComplianceWarning::new(
            WarningCode::PartialCheck,
            "Figure alt text validation requires structure tree traversal",
        ));

        // Suppress unused variable warning
        let _ = document;

        Ok(())
    }

    /// Validate tables have proper headers.
    fn validate_tables(
        &self,
        document: &mut PdfDocument,
        result: &mut UaValidationResult,
    ) -> Result<()> {
        // Table validation requires traversing structure tree
        // For now, add a warning about partial checking
        result.add_warning(ComplianceWarning::new(
            WarningCode::PartialCheck,
            "Table header validation requires structure tree traversal",
        ));

        // Suppress unused variable warning
        let _ = document;

        Ok(())
    }

    /// Validate form fields have accessible names.
    fn validate_form_fields(
        &self,
        document: &mut PdfDocument,
        result: &mut UaValidationResult,
    ) -> Result<()> {
        let catalog = document.catalog()?;
        let catalog_dict = match catalog {
            Object::Dictionary(d) => d,
            _ => return Ok(()),
        };

        // Check for AcroForm
        let acro_form = match catalog_dict.get("AcroForm") {
            Some(obj) => document.resolve_references(obj, 1)?,
            None => return Ok(()), // No forms
        };

        if let Object::Dictionary(form_dict) = acro_form {
            // Check for Fields
            if let Some(fields) = form_dict.get("Fields") {
                let resolved_fields = document.resolve_references(fields, 1)?;
                if let Object::Array(fields_arr) = resolved_fields {
                    for field in &fields_arr {
                        let resolved_field = document.resolve_references(field, 1)?;
                        if let Object::Dictionary(field_dict) = resolved_field {
                            // Check for TU (tooltip/accessible name)
                            if !field_dict.contains_key("TU") && !field_dict.contains_key("T") {
                                result.add_warning(ComplianceWarning::new(
                                    WarningCode::MissingRecommendedMetadata,
                                    "Form field missing TU (tooltip) or T (name)",
                                ));
                            }
                            result.stats.form_fields_checked += 1;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Validate annotations are accessible.
    fn validate_annotations(
        &self,
        document: &mut PdfDocument,
        result: &mut UaValidationResult,
    ) -> Result<()> {
        // Annotation validation requires page-level access
        // For now, add a warning about partial checking
        result.add_warning(ComplianceWarning::new(
            WarningCode::PartialCheck,
            "Full annotation validation requires page-level access",
        ));

        // Suppress unused variable warning
        let _ = document;

        Ok(())
    }
}

/// Simple validation of BCP 47 language tag format.
fn is_valid_language_tag(tag: &str) -> bool {
    // Basic validation: 2-3 letter primary tag, optionally followed by subtags
    let parts: Vec<&str> = tag.split('-').collect();
    if parts.is_empty() {
        return false;
    }

    // Primary language subtag should be 2-3 letters
    let primary = parts[0];
    if primary.len() < 2 || primary.len() > 3 || !primary.chars().all(|c| c.is_ascii_alphabetic()) {
        return false;
    }

    true
}

/// Convenience function to validate a document against PDF/UA-1.
pub fn validate_pdf_ua(
    document: &mut PdfDocument,
    level: PdfUaLevel,
) -> Result<UaValidationResult> {
    let validator = PdfUaValidator::new();
    validator.validate(document, level)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pdf_ua_level_display() {
        assert_eq!(format!("{}", PdfUaLevel::Ua1), "PDF/UA-1");
        assert_eq!(format!("{}", PdfUaLevel::Ua2), "PDF/UA-2");
    }

    #[test]
    fn test_pdf_ua_level_xmp() {
        assert_eq!(PdfUaLevel::Ua1.xmp_part(), "1");
        assert_eq!(PdfUaLevel::Ua2.xmp_part(), "2");
    }

    #[test]
    fn test_validation_result() {
        let mut result = UaValidationResult::new(PdfUaLevel::Ua1);
        assert!(result.is_compliant);
        assert!(!result.has_errors());

        result.add_error(UaComplianceError::new(UaErrorCode::NotTaggedPdf, "Not tagged"));
        assert!(result.has_errors());
        assert!(!result.is_compliant);
    }

    #[test]
    fn test_compliance_error_display() {
        let error = UaComplianceError::new(UaErrorCode::FigureMissingAlt, "Image without alt text")
            .with_location("Page 1")
            .with_wcag("1.1.1");
        let display = format!("{}", error);
        assert!(display.contains("[UA-FIG-001]"));
        assert!(display.contains("Page 1"));
        assert!(display.contains("WCAG 1.1.1"));
    }

    #[test]
    fn test_error_code_display() {
        assert_eq!(format!("{}", UaErrorCode::NotTaggedPdf), "UA-DOC-001");
        assert_eq!(format!("{}", UaErrorCode::FigureMissingAlt), "UA-FIG-001");
        assert_eq!(format!("{}", UaErrorCode::TableMissingHeaders), "UA-TBL-001");
    }

    #[test]
    fn test_language_tag_validation() {
        assert!(is_valid_language_tag("en"));
        assert!(is_valid_language_tag("en-US"));
        assert!(is_valid_language_tag("zh-Hans"));
        assert!(is_valid_language_tag("de-AT"));
        assert!(!is_valid_language_tag(""));
        assert!(!is_valid_language_tag("e")); // Too short
        assert!(!is_valid_language_tag("english")); // Too long for primary
    }

    #[test]
    fn test_validator_builder() {
        let validator = PdfUaValidator::new()
            .check_heading_sequence(false)
            .check_color_contrast(true)
            .allow_custom_types(vec!["MyHeading".to_string()]);

        assert!(!validator.check_heading_sequence);
        assert!(validator.check_color_contrast);
        assert!(validator
            .allowed_custom_types
            .contains(&"MyHeading".to_string()));
    }
}