pdf_oxide 0.3.38

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
#!/usr/bin/env rust
//! Comprehensive PDF feature analyzer
//!
//! Analyzes all PDFs in test dataset to identify:
//! - Successfully parsed features
//! - Missing or unsupported features
//! - Coverage statistics
//! - Potential improvements

#![allow(dead_code)]
#![allow(unused_variables)]

use pdf_oxide::{Error, PdfDocument};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::Path;

#[derive(Debug, Default)]
struct FeatureStats {
    total_files: usize,
    successful_parses: usize,
    failed_parses: usize,

    // Font features
    fonts_found: usize,
    font_descriptors: usize,
    missing_font_descriptors: usize,
    encoding_found: usize,
    to_unicode_cmaps: usize,

    // Content features
    images_found: usize,
    forms_found: usize,
    annotations_found: usize,
    xobjects_found: usize,

    // Structure features
    pages_found: usize,
    total_pages: usize,
    has_outline: usize,
    has_metadata: usize,

    // Compression
    flate_streams: usize,
    lzw_streams: usize,
    dct_streams: usize,
    other_filters: HashSet<String>,

    // Missing features by file
    files_missing_features: HashMap<String, Vec<String>>,
}

fn analyze_pdf(path: &Path, stats: &mut FeatureStats) -> Result<(), Error> {
    let filename = path.file_name().unwrap().to_string_lossy().to_string();

    let mut doc = match PdfDocument::open(path) {
        Ok(doc) => {
            stats.successful_parses += 1;
            doc
        },
        Err(e) => {
            stats.failed_parses += 1;
            println!("{} - Failed to parse: {}", filename, e);
            return Err(e);
        },
    };

    let mut missing_features = Vec::new();

    // Basic info
    let page_count = match doc.page_count() {
        Ok(count) => count,
        Err(e) => {
            missing_features.push(format!("Failed to get page count: {}", e));
            0
        },
    };

    if page_count > 0 {
        stats.pages_found += 1;
        stats.total_pages += page_count;
    } else {
        missing_features.push("No pages detected".to_string());
    }

    // Analyze fonts (check if we can access font information)
    // This is a heuristic - try to extract text and see if we get font info
    if page_count > 0 {
        match doc.extract_text(0) {
            Ok(text) => {
                if !text.is_empty() {
                    stats.fonts_found += 1;
                    // We successfully extracted text, so fonts are working
                }
            },
            Err(_) => {
                missing_features.push("Text extraction failed".to_string());
            },
        }
    }

    // Check for images
    if page_count > 0 {
        match doc.extract_images(0) {
            Ok(images) => {
                if !images.is_empty() {
                    stats.images_found += 1;
                }
            },
            Err(_) => {
                // Images might not exist or extraction might be unsupported
            },
        }
    }

    if !missing_features.is_empty() {
        stats
            .files_missing_features
            .insert(filename.clone(), missing_features);
    }

    Ok(())
}

fn analyze_raw_pdf_structure(path: &Path, stats: &mut FeatureStats) {
    // Read raw PDF bytes to check for features we might not be parsing
    let bytes = match fs::read(path) {
        Ok(b) => b,
        Err(_) => return,
    };

    // Convert to string, replacing invalid UTF-8 (PDFs are mostly ASCII with binary streams)
    let content = String::from_utf8_lossy(&bytes);

    // Check for various PDF features in raw content
    if content.contains("/FontDescriptor") {
        stats.font_descriptors += 1;
    }

    if content.contains("/Encoding") {
        stats.encoding_found += 1;
    }

    if content.contains("/ToUnicode") {
        stats.to_unicode_cmaps += 1;
    }

    if content.contains("/Annot") {
        stats.annotations_found += 1;
    }

    if content.contains("/AcroForm") || content.contains("/XFA") {
        stats.forms_found += 1;
    }

    if content.contains("/XObject") {
        stats.xobjects_found += 1;
    }

    if content.contains("/Outlines") {
        stats.has_outline += 1;
    }

    if content.contains("/Metadata") {
        stats.has_metadata += 1;
    }

    // Check compression filters
    if content.contains("/FlateDecode") {
        stats.flate_streams += 1;
    }

    if content.contains("/LZWDecode") {
        stats.lzw_streams += 1;
    }

    if content.contains("/DCTDecode") {
        stats.dct_streams += 1;
    }

    // Check for other filters
    let filters = [
        "ASCII85Decode",
        "ASCIIHexDecode",
        "RunLengthDecode",
        "CCITTFaxDecode",
        "JBIG2Decode",
        "JPXDecode",
        "Crypt",
    ];

    for filter in &filters {
        if content.contains(filter) {
            stats.other_filters.insert(filter.to_string());
        }
    }
}

fn main() {
    println!("=== PDF Feature Coverage Analysis ===\n");

    let test_dir = Path::new("test_datasets/pdfs");

    if !test_dir.exists() {
        eprintln!("Error: test_datasets/pdfs directory not found");
        std::process::exit(1);
    }

    let mut stats = FeatureStats::default();

    // Find all PDFs
    let mut pdf_files = Vec::new();

    for category in &["forms", "mixed", "technical"] {
        let category_dir = test_dir.join(category);
        if !category_dir.exists() {
            continue;
        }

        if let Ok(entries) = fs::read_dir(&category_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().map(|e| e == "pdf").unwrap_or(false) {
                    pdf_files.push(path);
                }
            }
        }
    }

    stats.total_files = pdf_files.len();

    println!("Found {} PDF files\n", stats.total_files);

    // Analyze each PDF
    for (i, path) in pdf_files.iter().enumerate() {
        if (i + 1) % 10 == 0 {
            println!("Progress: {}/{}", i + 1, stats.total_files);
        }

        // High-level API analysis
        let _ = analyze_pdf(path, &mut stats);

        // Low-level structure analysis
        analyze_raw_pdf_structure(path, &mut stats);
    }

    println!("\n=== Results ===\n");

    // Parsing success rate
    println!("## Parsing Success");
    println!(
        "  Successful: {}/{} ({:.1}%)",
        stats.successful_parses,
        stats.total_files,
        (stats.successful_parses as f64 / stats.total_files as f64) * 100.0
    );
    println!(
        "  Failed: {}/{} ({:.1}%)",
        stats.failed_parses,
        stats.total_files,
        (stats.failed_parses as f64 / stats.total_files as f64) * 100.0
    );

    // Page detection
    println!("\n## Page Detection");
    println!(
        "  Files with pages: {}/{} ({:.1}%)",
        stats.pages_found,
        stats.successful_parses,
        (stats.pages_found as f64 / stats.successful_parses.max(1) as f64) * 100.0
    );
    println!("  Total pages: {}", stats.total_pages);
    println!(
        "  Avg pages/file: {:.1}",
        stats.total_pages as f64 / stats.pages_found.max(1) as f64
    );

    // Font features
    println!("\n## Font Features (in raw PDF)");
    println!(
        "  FontDescriptor: {}/{} ({:.1}%)",
        stats.font_descriptors,
        stats.total_files,
        (stats.font_descriptors as f64 / stats.total_files as f64) * 100.0
    );
    println!(
        "  Encoding: {}/{} ({:.1}%)",
        stats.encoding_found,
        stats.total_files,
        (stats.encoding_found as f64 / stats.total_files as f64) * 100.0
    );
    println!(
        "  ToUnicode CMap: {}/{} ({:.1}%)",
        stats.to_unicode_cmaps,
        stats.total_files,
        (stats.to_unicode_cmaps as f64 / stats.total_files as f64) * 100.0
    );

    // Content features
    println!("\n## Content Features");
    println!(
        "  Text extraction: {}/{} ({:.1}%)",
        stats.fonts_found,
        stats.pages_found,
        (stats.fonts_found as f64 / stats.pages_found.max(1) as f64) * 100.0
    );
    println!(
        "  Images: {}/{} ({:.1}%)",
        stats.images_found,
        stats.total_files,
        (stats.images_found as f64 / stats.total_files as f64) * 100.0
    );
    println!(
        "  Forms/AcroForm: {}/{} ({:.1}%)",
        stats.forms_found,
        stats.total_files,
        (stats.forms_found as f64 / stats.total_files as f64) * 100.0
    );
    println!(
        "  Annotations: {}/{} ({:.1}%)",
        stats.annotations_found,
        stats.total_files,
        (stats.annotations_found as f64 / stats.total_files as f64) * 100.0
    );
    println!(
        "  XObjects: {}/{} ({:.1}%)",
        stats.xobjects_found,
        stats.total_files,
        (stats.xobjects_found as f64 / stats.total_files as f64) * 100.0
    );

    // Structure features
    println!("\n## Structure Features");
    println!(
        "  Outlines/Bookmarks: {}/{} ({:.1}%)",
        stats.has_outline,
        stats.total_files,
        (stats.has_outline as f64 / stats.total_files as f64) * 100.0
    );
    println!(
        "  Metadata: {}/{} ({:.1}%)",
        stats.has_metadata,
        stats.total_files,
        (stats.has_metadata as f64 / stats.total_files as f64) * 100.0
    );

    // Compression
    println!("\n## Compression Filters");
    println!(
        "  FlateDecode: {}/{} ({:.1}%)",
        stats.flate_streams,
        stats.total_files,
        (stats.flate_streams as f64 / stats.total_files as f64) * 100.0
    );
    println!(
        "  LZWDecode: {}/{} ({:.1}%)",
        stats.lzw_streams,
        stats.total_files,
        (stats.lzw_streams as f64 / stats.total_files as f64) * 100.0
    );
    println!(
        "  DCTDecode (JPEG): {}/{} ({:.1}%)",
        stats.dct_streams,
        stats.total_files,
        (stats.dct_streams as f64 / stats.total_files as f64) * 100.0
    );

    if !stats.other_filters.is_empty() {
        println!("  Other filters found: {:?}", stats.other_filters);
    }

    // Files with missing features
    if !stats.files_missing_features.is_empty() {
        println!("\n## Files with Issues ({} files)", stats.files_missing_features.len());
        for (file, issues) in stats.files_missing_features.iter().take(10) {
            println!("  {}", file);
            for issue in issues {
                println!("    - {}", issue);
            }
        }

        if stats.files_missing_features.len() > 10 {
            println!("  ... and {} more", stats.files_missing_features.len() - 10);
        }
    }

    // Recommendations
    println!("\n=== Feature Coverage Assessment ===\n");

    let coverage_pct = (stats.successful_parses as f64 / stats.total_files as f64) * 100.0;

    if coverage_pct >= 95.0 {
        println!("✅ Excellent coverage ({:.1}%)", coverage_pct);
    } else if coverage_pct >= 80.0 {
        println!("⚠️  Good coverage ({:.1}%), some improvements possible", coverage_pct);
    } else {
        println!("❌ Coverage needs improvement ({:.1}%)", coverage_pct);
    }

    // Identify potential missing features
    println!("\n## Features We Support:");
    println!("  ✅ Basic PDF parsing (objects, streams, xref)");
    println!("  ✅ Text extraction");
    println!("  ✅ FlateDecode, LZWDecode, DCTDecode");
    println!("  ✅ Font encoding and ToUnicode CMaps");
    println!("  ✅ Image extraction");
    println!("  ✅ XObject forms");

    println!("\n## Features That May Need Attention:");

    if stats.font_descriptors > stats.to_unicode_cmaps {
        let diff = stats.font_descriptors - stats.to_unicode_cmaps;
        println!("  ⚠️  {} files have FontDescriptor but no ToUnicode", diff);
        println!("      (may need fallback encoding handling)");
    }

    if stats.annotations_found > 0 {
        println!("  ℹ️  {} files have annotations", stats.annotations_found);
        println!("      (currently not extracted in text output)");
    }

    if stats.has_outline > 0 {
        println!("  ℹ️  {} files have outlines/bookmarks", stats.has_outline);
        println!("      (currently not exposed in API)");
    }

    if !stats.other_filters.is_empty() {
        println!("  ℹ️  Other compression filters found: {:?}", stats.other_filters);
        println!("      (may or may not be supported)");
    }

    println!("\n=== Recommendation ===");
    println!();

    if coverage_pct >= 95.0 {
        println!("The library has excellent coverage of the test dataset.");
        println!("Current feature set is production-ready for v0.1.0.");
        println!();
        println!("Future enhancements (v1.x):");
        println!("  - Annotation extraction (if users request it)");
        println!("  - Outline/bookmark API (if users request it)");
        println!("  - Additional compression filters (as needed)");
    } else {
        println!(
            "Consider investigating the {} failed parses before release.",
            stats.failed_parses
        );
        println!("These may represent edge cases or unsupported PDF features.");
    }
}