oxidize-pdf 2.5.0

A pure Rust PDF generation and manipulation library with zero external dependencies
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
//! ISO 32000-1:2008 Compliance Verification Tests
//!
//! This module provides a comprehensive test suite for verifying PDF compliance
//! with ISO 32000-1:2008 standard. Tests are organized by ISO sections and
//! verification levels.
//!
//! ## Verification Levels
//!
//! - **Level 0**: Not Implemented - Feature is not available
//! - **Level 1**: Code Exists - API exists and doesn't crash
//! - **Level 2**: Generates PDF - Creates valid PDF output
//! - **Level 3**: Content Verified - PDF content is structurally correct
//! - **Level 4**: ISO Compliant - Passes external validation tools

use crate::verification::{parser::parse_pdf, VerificationLevel};
use crate::{Document, Font, Page, Result as PdfResult};
use std::collections::HashMap;
use std::fs;
use std::process::Command;

pub mod section_10_rendering;
pub mod section_11_interactive;
pub mod section_12_multimedia;
pub mod section_7_syntax;
pub mod section_8_graphics;
pub mod section_9_text;

/// Helper for creating test PDFs with basic structure
pub fn create_basic_test_pdf(title: &str, content: &str) -> PdfResult<Vec<u8>> {
    let mut doc = Document::new();
    doc.set_title(title);
    doc.set_author("ISO Verification Test Suite");
    doc.set_creator("oxidize-pdf");

    let mut page = Page::a4();

    // Title
    page.text()
        .set_font(Font::Helvetica, 16.0)
        .at(50.0, 750.0)
        .write(title)?;

    // Content
    page.text()
        .set_font(Font::TimesRoman, 12.0)
        .at(50.0, 700.0)
        .write(content)?;

    // Ensure minimum content for level 2 verification
    page.text()
        .set_font(Font::Courier, 10.0)
        .at(50.0, 650.0)
        .write("This PDF is generated for ISO 32000-1:2008 compliance verification")?;

    doc.add_page(page);
    doc.to_bytes()
}

/// Simple verification result structure
pub struct VerificationResult {
    pub passed: bool,
    pub level: VerificationLevel,
}

/// Helper for verifying PDF at different levels
pub fn verify_pdf_at_level(
    pdf_bytes: &[u8],
    _requirement_id: &str,
    level: VerificationLevel,
    _description: &str,
) -> VerificationResult {
    // Basic verification: PDF should be valid and non-empty
    let passed = pdf_bytes.len() > 1000 && pdf_bytes.starts_with(b"%PDF-");
    VerificationResult { passed, level }
}

/// Helper for updating verification status automatically
pub fn update_iso_status(
    requirement_id: &str,
    level: u8,
    test_location: &str,
    notes: &str,
) -> bool {
    // Check if the Python script exists first
    let possible_script_paths = [
        "../../../../scripts/update_verification_status.py",
        "../../../scripts/update_verification_status.py",
        "../../scripts/update_verification_status.py",
        "scripts/update_verification_status.py",
    ];

    let script_path = possible_script_paths
        .iter()
        .find(|path| std::path::Path::new(path).exists())
        .copied();

    let script_path = if let Some(path) = script_path {
        path
    } else {
        // Script doesn't exist - just log the status without failing
        if level == 0 {
            println!(
                "📝 ISO {} - Not implemented (Level {}): {}",
                requirement_id, level, notes
            );
        } else {
            println!(
                "✓ ISO {} - Level {} achieved: {}",
                requirement_id, level, notes
            );
        }
        return true; // Don't fail tests because script is missing
    };

    // Call the Python script to update status
    let result = Command::new("python3")
        .arg(script_path)
        .arg("--req-id")
        .arg(requirement_id)
        .arg("--level")
        .arg(level.to_string())
        .arg("--test-file")
        .arg(test_location)
        .arg("--notes")
        .arg(notes)
        .output();

    match result {
        Ok(output) => {
            if output.status.success() {
                println!(
                    "✓ Updated ISO status for {}: level {}",
                    requirement_id, level
                );
                true
            } else {
                eprintln!(
                    "⚠️  Failed to update ISO status for {}: {}",
                    requirement_id,
                    String::from_utf8_lossy(&output.stderr)
                );
                false
            }
        }
        Err(e) => {
            eprintln!(
                "⚠️  Failed to update ISO status for {}: {}",
                requirement_id, e
            );
            false
        }
    }
}

/// Macro to create an ISO compliance test
#[macro_export]
macro_rules! iso_test {
    ($test_name:ident, $req_id:expr, $level:expr, $description:expr, $test_body:block) => {
        #[test]
        fn $test_name() -> PdfResult<()> {
            println!(
                "🔍 Testing ISO requirement {} at level {:?}",
                $req_id, $level
            );

            let result: Result<(bool, u8, String), crate::error::PdfError> = $test_body;

            let (passed, level_achieved, notes) = match result {
                Ok((success, actual_level, note)) => (success, actual_level, note),
                Err(e) => (false, 0, format!("Test error: {}", e)),
            };

            // Update ISO status
            let test_location = format!("{}::{}", module_path!(), stringify!($test_name));
            crate::verification::tests::update_iso_status(
                $req_id,
                level_achieved,
                &test_location,
                &notes,
            );

            // For Level 0 (NotImplemented), the test should pass even if passed=false
            let test_should_pass = if level_achieved == 0 {
                true // Level 0 tests always pass (documenting non-implementation)
            } else {
                passed // Other levels require actual success
            };

            if test_should_pass {
                if level_achieved == 0 {
                    println!("✅ ISO {} - Level 0 (Not Implemented) documented", $req_id);
                } else {
                    println!("✅ ISO {} - Level {} achieved", $req_id, level_achieved);
                }
            } else {
                println!("❌ ISO {} - Test failed: {}", $req_id, notes);
            }

            assert!(
                test_should_pass,
                "ISO requirement {} failed: {}",
                $req_id, notes
            );
            Ok(())
        }
    };
}

pub(crate) use iso_test;

/// Helper to check if external validators are available
pub fn get_available_validators() -> Vec<String> {
    let mut validators = Vec::new();

    // Check for qpdf
    if Command::new("qpdf").arg("--version").output().is_ok() {
        validators.push("qpdf".to_string());
    }

    // Check for veraPDF
    if Command::new("verapdf").arg("--version").output().is_ok() {
        validators.push("verapdf".to_string());
    }

    validators
}

/// Helper to run external validation if tools are available
pub fn run_external_validation(pdf_bytes: &[u8], validator: &str) -> Option<bool> {
    if !get_available_validators().contains(&validator.to_string()) {
        return None;
    }

    match validator {
        "qpdf" => run_qpdf_validation(pdf_bytes),
        "verapdf" => run_verapdf_validation(pdf_bytes),
        _ => None,
    }
}

fn run_qpdf_validation(pdf_bytes: &[u8]) -> Option<bool> {
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    // Create unique temp file name to avoid conflicts
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or(Duration::from_secs(0))
        .as_nanos();
    let temp_path = format!("/tmp/iso_test_{}.pdf", timestamp);

    if fs::write(&temp_path, pdf_bytes).is_err() {
        return None;
    }

    // Run qpdf validation with comprehensive checking
    let output = Command::new("qpdf")
        .arg("--check")
        .arg(&temp_path)
        .output()
        .ok()?;

    // Clean up
    let _ = fs::remove_file(&temp_path);

    // qpdf returns 0 for valid PDFs, non-zero for issues
    // Also check for common warnings that don't fail but indicate issues
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    let has_errors = stderr.contains("error") || stderr.contains("damaged");
    let has_warnings = stderr.contains("warning");

    // For Level 4 compliance, we want strict validation (no errors, minimal warnings)
    let is_valid = output.status.success() && !has_errors;

    if !is_valid && !stderr.is_empty() {
        eprintln!("qpdf validation issues: {}", stderr);
    }

    Some(is_valid)
}

fn run_verapdf_validation(pdf_bytes: &[u8]) -> Option<bool> {
    // Write PDF to temporary file
    let temp_path = "/tmp/iso_test.pdf";
    if fs::write(temp_path, pdf_bytes).is_err() {
        return None;
    }

    // Run veraPDF validation
    let output = Command::new("verapdf")
        .arg("--format")
        .arg("text")
        .arg(temp_path)
        .output()
        .ok()?;

    // Clean up
    let _ = fs::remove_file(temp_path);

    Some(output.status.success() && !String::from_utf8_lossy(&output.stdout).contains("FAIL"))
}

/// Generate a comprehensive test report
pub fn generate_test_report() -> PdfResult<String> {
    let mut report = String::new();

    report.push_str("# ISO 32000-1:2008 Compliance Test Report\n\n");
    report.push_str(&format!(
        "Generated: {}\n\n",
        chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
    ));

    // Load current status if available
    if let Ok(status_content) = fs::read_to_string("ISO_VERIFICATION_STATUS.toml") {
        if let Ok(status_data) = toml::from_str::<HashMap<String, toml::Value>>(&status_content) {
            if let Some(stats) = status_data.get("statistics") {
                report.push_str("## Overall Statistics\n\n");
                if let Some(total) = stats.get("level_0_count").and_then(|v| v.as_integer()) {
                    report.push_str(&format!("- Level 0 (Not Implemented): {}\n", total));
                }
                if let Some(level1) = stats.get("level_1_count").and_then(|v| v.as_integer()) {
                    report.push_str(&format!("- Level 1 (Code Exists): {}\n", level1));
                }
                if let Some(level2) = stats.get("level_2_count").and_then(|v| v.as_integer()) {
                    report.push_str(&format!("- Level 2 (Generates PDF): {}\n", level2));
                }
                if let Some(level3) = stats.get("level_3_count").and_then(|v| v.as_integer()) {
                    report.push_str(&format!("- Level 3 (Content Verified): {}\n", level3));
                }
                if let Some(level4) = stats.get("level_4_count").and_then(|v| v.as_integer()) {
                    report.push_str(&format!("- Level 4 (ISO Compliant): {}\n", level4));
                }
                if let Some(avg) = stats.get("average_level").and_then(|v| v.as_float()) {
                    report.push_str(&format!("- Average Level: {:.2}\n", avg));
                }
                if let Some(pct) = stats
                    .get("compliance_percentage")
                    .and_then(|v| v.as_float())
                {
                    report.push_str(&format!("- Overall Compliance: {:.1}%\n\n", pct));
                }
            }
        }
    }

    report.push_str("## Available External Validators\n\n");
    let validators = get_available_validators();
    if validators.is_empty() {
        report.push_str("No external validators available for Level 4 verification.\n\n");
    } else {
        for validator in validators {
            report.push_str(&format!("- {}\n", validator));
        }
        report.push_str("\n");
    }

    report.push_str("## Test Coverage by Section\n\n");
    report.push_str("- Section 7 (Syntax): Document Structure, Objects, File Structure\n");
    report.push_str("- Section 8 (Graphics): Color Spaces, Images, Paths, Graphics State\n");
    report.push_str("- Section 9 (Text): Fonts, Text Operators, Character Encoding\n\n");

    report.push_str("---\n");
    report.push_str("Generated by oxidize-pdf ISO compliance test suite\n");

    Ok(report)
}

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

    #[test]
    fn test_basic_pdf_creation() -> PdfResult<()> {
        let pdf_bytes = create_basic_test_pdf("Test PDF", "Test content")?;
        assert!(true, "Test passed");

        // Verify it can be parsed
        let parsed = parse_pdf(&pdf_bytes)?;
        assert!(
            parsed.version.starts_with("1."),
            "Should have valid PDF version"
        );
        assert!(parsed.object_count > 0, "Should have objects");

        Ok(())
    }

    #[test]
    fn test_verification_helpers() {
        let pdf_bytes = create_basic_test_pdf("Helper Test", "Testing helpers").unwrap();

        let result = verify_pdf_at_level(
            &pdf_bytes,
            "test.helper",
            VerificationLevel::GeneratesPdf,
            "Testing helper functions",
        );

        assert!(result.passed, "Helper verification should pass");
        assert_eq!(result.level, VerificationLevel::GeneratesPdf);
    }

    #[test]
    fn test_report_generation() {
        let report = generate_test_report().unwrap();
        assert!(report.contains("# ISO 32000-1:2008 Compliance Test Report"));
        assert!(report.contains("Generated:"));
        assert!(report.len() > 200, "Report should be substantial");
    }
}