pdf_oxide 0.3.23

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
# Architecture Overview

System design and implementation details for pdf_oxide.

## Table of Contents

- [High-Level Architecture]#high-level-architecture
- [Core Components]#core-components
- [Data Flow]#data-flow
- [Module Organization]#module-organization
- [Algorithm Details]#algorithm-details
- [Performance Design]#performance-design
- [Extension Points]#extension-points

## High-Level Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                        Public API Layer                          │
│  (PdfDocument, Exporters, Configuration)                        │
└───────────────────┬─────────────────────────────────────────────┘
┌───────────────────┴─────────────────────────────────────────────┐
│                     Processing Pipeline                          │
│                                                                  │
│  ┌──────────┐   ┌─────────┐   ┌──────────┐   ┌─────────────┐ │
│  │  Lexer   │──▶│ Parser  │──▶│  Stream  │──▶│   Layout    │ │
│  │          │   │         │   │ Decoder  │   │  Analysis   │ │
│  └──────────┘   └─────────┘   └──────────┘   └─────────────┘ │
│                                                       │          │
│  ┌──────────┐   ┌─────────┐   ┌──────────┐          │         │
│  │   Text   │◀──│  Font   │◀──│  Object  │◀─────────┘         │
│  │Extractor │   │ Parser  │   │  Resolver│                     │
│  └──────────┘   └─────────┘   └──────────┘                     │
│        │                                                         │
│        ▼                                                         │
│  ┌──────────┐   ┌─────────┐   ┌──────────┐                    │
│  │ Markdown │   │  HTML   │   │   Text   │                    │
│  │ Exporter │   │Exporter │   │ Exporter │                    │
│  └──────────┘   └─────────┘   └──────────┘                    │
└─────────────────────────────────────────────────────────────────┘
┌───────────────────┴─────────────────────────────────────────────┐
│                     Storage Layer                                │
│  (Memory-mapped files, Object cache, Font cache)               │
└─────────────────────────────────────────────────────────────────┘
```

## Core Components

### 1. Lexer (`src/lexer.rs`)

**Purpose:** Tokenize PDF byte stream into lexical tokens.

**Key Features:**
- Zero-copy tokenization using byte slices
- Handles all PDF token types (numbers, strings, names, operators)
- Efficient whitespace and comment skipping
- Position tracking for error reporting

**Performance:**
- ~1-2ms for typical PDFs
- O(n) complexity where n = file size
- Minimal allocations (uses `&[u8]` slices)

**Example:**
```rust
pub struct Lexer<'a> {
    data: &'a [u8],
    position: usize,
}

impl<'a> Lexer<'a> {
    pub fn next_token(&mut self) -> Result<Token<'a>> {
        // Zero-copy token extraction
    }
}
```

### 2. Parser (`src/parser.rs`)

**Purpose:** Parse PDF objects from token stream.

**Key Features:**
- Recursive descent parser
- Cycle detection for circular references
- Recursion depth limiting (max 100 levels)
- Proper error context propagation

**Object Types:**
- Null, Boolean, Integer, Real
- String, Name
- Array, Dictionary
- Stream, Reference

**Example:**
```rust
pub struct Parser<'a> {
    lexer: Lexer<'a>,
    objects: HashMap<ObjectId, Object>,
    recursion_depth: u32,
}

impl<'a> Parser<'a> {
    pub fn parse_object(&mut self) -> Result<Object> {
        // Recursive object parsing with cycle detection
    }
}
```

### 3. Stream Decoder (`src/stream_decoder.rs`)

**Purpose:** Decompress PDF streams using various filters.

**Supported Filters:**
- **FlateDecode**: Zlib/Deflate (most common)
- **LZWDecode**: LZW compression
- **ASCII85Decode**: ASCII85 encoding
- **ASCIIHexDecode**: Hex encoding
- **RunLengthDecode**: Run-length encoding
- **DCTDecode**: JPEG (passthrough)
- **CCITTFaxDecode**: CCITT Group 3/4

**Design:**
```rust
pub trait StreamFilter {
    fn decode(&self, data: &[u8], params: &DecodeParms) -> Result<Vec<u8>>;
}

pub struct StreamDecoder {
    filters: Vec<Box<dyn StreamFilter>>,
}
```

**Performance:**
- Streaming decompression where possible
- Decompression bomb protection (10× ratio limit)
- Reusable buffers to minimize allocations

### 4. Layout Analysis (`src/layout/`)

**Purpose:** Understand document spatial structure.

**Submodules:**

#### 4.1 DBSCAN Clustering (`layout/dbscan.rs`)

**Algorithm:** Density-Based Spatial Clustering of Applications with Noise

**Parameters:**
- Epsilon (ε): 1.5× median character height
- MinPts: 2 for chars→words, 3 for words→lines

**Data Structure:** R*-tree for O(log n) neighborhood queries

**Performance:** O(n log n) instead of naive O(n²)

```rust
pub struct DbscanClusterer {
    spatial_index: RTree<Character>,
    epsilon: f32,
    min_points: usize,
}

impl DbscanClusterer {
    pub fn cluster(&self, chars: &[Character]) -> Vec<Cluster> {
        // DBSCAN with spatial indexing
    }
}
```

#### 4.2 XY-Cut (`layout/xy_cut.rs`)

**Algorithm:** Recursive projection-based page segmentation

**Steps:**
1. Project content onto X-axis (horizontal)
2. Find gaps in projection (valleys)
3. Split at largest gap
4. Recurse on sub-regions
5. Repeat for Y-axis

**Configuration:**
- Split threshold: 0.05 × page dimension (5%)
- Max recursion: 10 levels
- Gaussian smoothing: σ=2.0

```rust
pub struct XyCutSegmenter {
    threshold: f32,
    max_depth: u32,
}

impl XyCutSegmenter {
    pub fn segment(&self, page: &Page) -> Vec<Region> {
        self.segment_recursive(page, 0)
    }

    fn segment_recursive(&self, region: &Region, depth: u32) -> Vec<Region> {
        // Recursive XY-Cut with projection analysis
    }
}
```

#### 4.3 Font Clustering (`layout/font_clustering.rs`)

**Purpose:** Group text by font characteristics for formatting detection.

**Features:**
- Size tolerance: ±1pt
- Family exact matching
- Outlier rejection: fonts used in <2% of characters

**Use Cases:**
- Bold/italic detection
- Heading identification
- Style consistency checking

### 5. Text Extraction (`src/text.rs`)

**Purpose:** Extract text with proper spacing and formatting.

**Key Algorithms:**
- **Word spacing detection**: 0.25× character width threshold
- **Line spacing detection**: 1.2× character height threshold
- **Bold detection**: Font weight analysis
- **Reading order**: Top-to-bottom, left-to-right (with column detection)

**Quality:**
- 100% word spacing accuracy (tested on 103 PDFs)
- 100% whitespace preservation
- 37% more bold sections detected vs. reference

```rust
pub struct TextExtractor {
    config: TextConfig,
    font_cache: HashMap<String, Font>,
}

impl TextExtractor {
    pub fn extract(&mut self, page: &Page) -> Result<String> {
        // Character clustering → word formation → line formation → text
    }
}
```

### 6. Font Parser (`src/font.rs`)

**Purpose:** Parse PDF fonts and handle character encoding.

**Features:**
- **Standard fonts**: Built-in Type1 fonts (Times, Helvetica, etc.)
- **ToUnicode CMap**: Unicode mapping for custom encodings
- **Encoding tables**: PDFDocEncoding, MacRomanEncoding, WinAnsiEncoding
- **Font metrics**: Character widths, ascent, descent

**Caching:**
- Parsed fonts cached per document
- Reduces re-parsing overhead for multi-page documents
- ~25% speedup on typical documents

### 7. Image Extraction (`src/image.rs`)

**Purpose:** Extract embedded images from PDFs.

**Supported Formats:**
- JPEG (DCTDecode)
- PNG (FlateDecode + predictor)
- TIFF (CCITTFaxDecode)
- Raw RGB/CMYK

**Features:**
- Color space conversion (CMYK → RGB, etc.)
- Predictor functions (PNG filters)
- Decompression
- Metadata extraction (dimensions, DPI)

### 8. Exporters (`src/converters/`)

**Purpose:** Convert extracted content to various formats.

#### 8.1 Markdown Exporter

**Quality:** 99.8/100 (tested on 103 PDFs)

**Features:**
- Bold text detection and formatting
- Heading detection (font size heuristics)
- List detection
- Link preservation
- Proper whitespace normalization

#### 8.2 HTML Exporter

**Quality:** 94.0/100

**Features:**
- Semantic HTML5
- URL/email linkification
- Bold/italic tags
- Proper entity encoding
- CSS-friendly structure

#### 8.3 Plain Text Exporter

**Quality:** 100.0/100 (whitespace)

**Features:**
- Whitespace normalization
- Word spacing preservation
- Line break consistency

## Data Flow

### Opening a Document

```
1. User calls PdfDocument::open("file.pdf")
   2. Memory-map file (or load into buffer)
   3. Parse header, locate cross-reference table
   4. Build object index (lazy loading)
   5. Parse catalog and page tree
   6. Return PdfDocument handle
```

### Extracting Text from a Page

```
1. User calls doc.extract_text(page_num)
   2. Resolve page object from page tree
   3. Get content stream(s)
   4. Decode streams (decompress)
   5. Parse content stream operators
   6. Extract character data with positions
   7. Cluster characters into words (DBSCAN)
   8. Cluster words into lines (DBSCAN)
   9. Detect columns (XY-Cut)
   10. Sort into reading order
   11. Format text with proper spacing
   12. Return extracted text
```

### Exporting to Markdown

```
1. User calls exporter.export_all(doc)
   2. For each page:
   ├─ Extract text blocks with metadata
   ├─ Detect bold sections (font analysis)
   ├─ Detect headings (size heuristics)
   ├─ Detect lists (indentation + markers)
   3. Format as Markdown:
   ├─ Headings: # ## ###
   ├─ Bold: **text**
   ├─ Lists: - item
   ├─ Links: [text]url
   4. Concatenate pages with separators
   5. Return Markdown string
```

## Module Organization

```
src/
├── lib.rs              # Public API, re-exports
├── error.rs            # Error types
├── object.rs           # PDF object types
├── lexer.rs            # Tokenization
├── parser.rs           # Object parsing
├── document.rs         # High-level API
├── stream_decoder.rs   # Stream decompression
├── font.rs             # Font parsing
├── text.rs             # Text extraction
├── image.rs            # Image extraction
├── form.rs             # Form field extraction
├── bookmark.rs         # Bookmark extraction
├── annotation.rs       # Annotation extraction
├── layout/             # Layout analysis
│   ├── mod.rs
│   ├── dbscan.rs       # DBSCAN clustering
│   ├── xy_cut.rs       # XY-Cut segmentation
│   ├── font_clustering.rs
│   └── spatial_index.rs  # R*-tree
│
├── converters/         # Export formats
│   ├── mod.rs
│   ├── markdown.rs     # Markdown exporter
│   ├── html.rs         # HTML exporter
│   └── text.rs         # Plain text exporter
│
└── utils/              # Utilities
    ├── mod.rs
    ├── encoding.rs     # Character encoding
    └── geometry.rs     # Bounding box math

python/                 # Python bindings
├── src/
│   └── lib.rs         # PyO3 bindings
└── pyproject.toml

tests/                  # Integration tests
├── test_parsing.rs
├── test_text_extraction.rs
├── test_exporters.rs
└── fixtures/          # Test PDFs

benches/               # Performance benchmarks
└── parsing.rs

examples/              # Usage examples
├── basic.rs
├── batch_processing.rs
└── custom_exporter.rs
```

## Algorithm Details

### DBSCAN Clustering

**Pseudo-code:**
```
function dbscan(points, epsilon, minPts):
    clusters = []
    visited = set()

    for point in points:
        if point in visited:
            continue

        visited.add(point)
        neighbors = find_neighbors(point, epsilon)  # O(log n) with R*-tree

        if len(neighbors) < minPts:
            # Noise point
            continue

        # Start new cluster
        cluster = [point]
        queue = neighbors

        while queue:
            neighbor = queue.pop()
            if neighbor not in visited:
                visited.add(neighbor)
                new_neighbors = find_neighbors(neighbor, epsilon)

                if len(new_neighbors) >= minPts:
                    queue.extend(new_neighbors)

            if neighbor not in any cluster:
                cluster.append(neighbor)

        clusters.append(cluster)

    return clusters
```

**Optimization:** R*-tree spatial index allows O(log n) neighbor queries instead of O(n) linear scan.

### XY-Cut Segmentation

**Pseudo-code:**
```
function xy_cut(region, depth):
    if depth > MAX_DEPTH:
        return [region]

    # Project onto X-axis
    x_projection = project_horizontal(region)
    x_gaps = find_gaps(x_projection, threshold)

    if x_gaps:
        split_x = largest_gap(x_gaps)
        left, right = split_region(region, split_x, vertical=True)
        return xy_cut(left, depth+1) + xy_cut(right, depth+1)

    # Project onto Y-axis
    y_projection = project_vertical(region)
    y_gaps = find_gaps(y_projection, threshold)

    if y_gaps:
        split_y = largest_gap(y_gaps)
        top, bottom = split_region(region, split_y, vertical=False)
        return xy_cut(top, depth+1) + xy_cut(bottom, depth+1)

    # No split found
    return [region]
```

### Word Spacing Detection

**Algorithm:**
```
For each pair of adjacent characters (c1, c2):
    gap = c2.x - (c1.x + c1.width)
    threshold = 0.25 * c1.width

    if gap > threshold:
        insert_space()
```

**Dynamic threshold:** Uses character width for adaptive spacing detection.

## Performance Design

### Zero-Copy Parsing

**Technique:** Use byte slices (`&[u8]`) instead of copying data.

**Example:**
```rust
// Zero-copy token
pub enum Token<'a> {
    Name(&'a [u8]),
    String(&'a [u8]),
    // ...
}

// No allocation needed
let token = lexer.next_token()?;
```

### Memory-Mapped Files

**Technique:** Use `mmap` for large files.

**Benefits:**
- OS handles memory management
- Lazy loading (only accessed pages loaded)
- Shared memory across processes

### Object Caching

**Strategy:** Cache parsed objects by object ID.

**Benefits:**
- Avoid re-parsing referenced objects
- O(1) lookup for cross-references
- Memory bounded by unique object count

### Streaming

**Technique:** Process pages one at a time.

**Benefits:**
- Constant memory regardless of document size
- Can process 10 GB documents with <100 MB RAM

## Extension Points

### Custom Exporters

Implement the `Exporter` trait:

```rust
pub trait Exporter {
    fn export_page(&self, doc: &mut PdfDocument, page_num: u32) -> Result<String>;
    fn export_all(&self, doc: &mut PdfDocument) -> Result<String>;
}
```

### Custom Stream Filters

Implement the `StreamFilter` trait:

```rust
pub trait StreamFilter {
    fn decode(&self, data: &[u8], params: &DecodeParms) -> Result<Vec<u8>>;
}
```

### Custom Layout Analyzers

Replace or extend layout analysis:

```rust
pub trait LayoutAnalyzer {
    fn analyze(&self, page: &Page) -> Result<Layout>;
}
```

## Security Considerations

### Input Validation

**PDF as untrusted input:**
- Limit file size (default: 500 MB)
- Limit object count (default: 1M objects)
- Limit recursion depth (default: 100 levels)
- Validate array/dictionary sizes

### Decompression Bombs

**Protection:**
- Limit decompressed size to 10× compressed size
- Check compression ratio before full decompression
- Stream decompression where possible

### Memory Safety

**Rust guarantees:**
- No buffer overflows
- No use-after-free
- No data races
- Bounds checking on all array accesses

**Minimal `unsafe`:**
- Used sparingly (e.g., performance-critical paths)
- Thoroughly documented with safety invariants
- Reviewed by multiple developers

## Future Architecture

### Planned Improvements

**v1.x:**
- Stream API for ultra-low memory usage
- Table detection (smart heuristics)
- Rotated text handling

**v2.x:**
- ML-based layout analysis (optional)
- GPU acceleration (optional)
- Parallel page processing

**v3.x:**
- OCR integration (Tesseract)
- PDF/A validation
- Advanced form handling

## References

- **PDF Specification**: ISO 32000-1:2008 (PDF 1.7) - `docs/spec/pdf.md`
- **Architecture**: ARCHITECTURE.md - Detailed system design
- **DBSCAN**: Ester et al., "A Density-Based Algorithm for Discovering Clusters" (1996)
- **XY-Cut**: Nagy & Seth, "Hierarchical Representation of Optically Scanned Documents" (1984)
- **R*-tree**: Beckmann et al., "The R*-tree: An Efficient and Robust Access Method" (1990)

## Questions?

- **GitHub Issues**: https://github.com/yfedoseev/pdf_oxide/issues
- **Discussions**: https://github.com/yfedoseev/pdf_oxide/discussions
- **Documentation**: https://docs.rs/pdf_oxide