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
# Markdown Converter Usage Guide

## Quick Start

### Basic Usage

```rust
use pdf_oxide::pipeline::{OrderedTextSpan, TextPipelineConfig};
use pdf_oxide::pipeline::converters::{MarkdownOutputConverter, OutputConverter};

let converter = MarkdownOutputConverter::new();
let config = TextPipelineConfig::default();
let markdown = converter.convert(&spans, &config)?;
println!("{}", markdown);
```

### With Features Enabled

```rust
use pdf_oxide::pipeline::config::{OutputConfig, BoldMarkerBehavior};

let config = TextPipelineConfig {
    output: OutputConfig {
        detect_headings: true,
        bold_marker_behavior: BoldMarkerBehavior::Aggressive,
        extract_tables: true,
        preserve_layout: true,
        include_images: true,
        image_output_dir: Some("/tmp/images".to_string()),
    },
    ..Default::default()
};

let markdown = converter.convert(&spans, &config)?;
```

## Configuration Options

### `OutputConfig` Fields

#### Heading Detection
```rust
pub detect_headings: bool
```

**Default**: `false`

Enables automatic heading level detection based on font size:
- H1: 24pt+
- H2: 18-23pt
- H3: 14-17pt

**Example**:
```rust
OutputConfig {
    detect_headings: true,
    ..Default::default()
}
```

---

#### Bold Marker Behavior
```rust
pub bold_marker_behavior: BoldMarkerBehavior
```

**Type**: `enum BoldMarkerBehavior`
- `Conservative`: Apply bold only to text with content (skip whitespace)
- `Aggressive`: Apply bold to all bold-weight text

**Default**: `Conservative`

**Example**:
```rust
OutputConfig {
    bold_marker_behavior: BoldMarkerBehavior::Aggressive,
    ..Default::default()
}
```

---

#### Table Extraction
```rust
pub extract_tables: bool
```

**Default**: `false`

Detects grid-aligned text and formats as markdown tables:

**Example Input**:
```
Name    Age    City
Alice   30     NYC
Bob     25     LA
```

**Example Output**:
```markdown
| Name  | Age | City |
|-------|-----|------|
| Alice | 30  | NYC  |
| Bob   | 25  | LA   |
```

---

#### Layout Preservation
```rust
pub preserve_layout: bool
```

**Default**: `false`

Preserves whitespace to maintain column alignment:

**With `false`** (normalized):
```
Text in column A    Text in column B
More text
```

**With `true`** (preserved):
```
Text in column A                Text in column B
More text
```

---

#### Image Embedding
```rust
pub include_images: bool
pub image_output_dir: Option<String>
```

**Default**: `include_images: true`, `image_output_dir: None`

Controls image handling in output:
- `include_images: true`: Include image references
- `image_output_dir: Some(path)`: Extract images to specified directory

**Example**:
```rust
OutputConfig {
    include_images: true,
    image_output_dir: Some("/home/user/pdf_images".to_string()),
    ..Default::default()
}
```

---

## Feature Examples

### Example 1: Academic Paper Conversion

```rust
let config = TextPipelineConfig {
    output: OutputConfig {
        detect_headings: true,
        bold_marker_behavior: BoldMarkerBehavior::Conservative,
        extract_tables: true,
        preserve_layout: false,
        ..Default::default()
    },
    ..Default::default()
};

// Result:
// # Introduction
//
// This paper discusses **important** concepts.
//
// | Metric | Value |
// |--------|-------|
// | Recall | 95%   |
// | F1     | 0.92  |
```

### Example 2: Form Extraction

```rust
let config = TextPipelineConfig {
    output: OutputConfig {
        preserve_layout: true,
        bold_marker_behavior: BoldMarkerBehavior::Conservative,
        ..Default::default()
    },
    ..Default::default()
};

// Result:
// Name: ________________    Date: __________
// Address: ___________________________________
```

### Example 3: Simple Text Conversion

```rust
let config = TextPipelineConfig::default();

// Result:
// Plain text with **bold** and *italic* preserved
// but no heading detection or tables
```

## Output Formatting

### Headings
```markdown
# H1 Title
## H2 Section
### H3 Subsection
```

### Text Formatting
```markdown
**bold text**
*italic text*
***bold italic***
```

### Tables
```markdown
| Column 1 | Column 2 |
|----------|----------|
| Cell A   | Cell B   |
| Cell C   | Cell D   |
```

### Links
Auto-converted from text:
```markdown
[https://example.com](https://example.com)
[user@example.com](mailto:user@example.com)
```

### Paragraphs
Separated by blank lines:
```markdown
First paragraph.

Second paragraph.
```

## Performance Considerations

### Recommended Settings for Different Use Cases

**Speed-Optimized** (fastest):
```rust
OutputConfig {
    detect_headings: false,
    extract_tables: false,
    preserve_layout: false,
    ..Default::default()
}
```

**Quality-Optimized** (best output):
```rust
OutputConfig {
    detect_headings: true,
    extract_tables: true,
    preserve_layout: false,
    bold_marker_behavior: BoldMarkerBehavior::Conservative,
    ..Default::default()
}
```

**Form-Optimized** (preserves layout):
```rust
OutputConfig {
    preserve_layout: true,
    detect_headings: false,
    extract_tables: false,
    ..Default::default()
}
```

### Time Complexity

- **Overall**: O(n) where n = number of text spans
- **Heading detection**: O(n) - single statistical pass
- **Table detection**: O(n) - grouping by position
- **Linkification**: O(n) - regex replacements
- **Formatting**: O(n) - inline formatting

No heap allocations in tight loops.

## Testing

### Running Tests

```bash
# Run all markdown converter tests
cargo test --test test_pipeline_markdown_converter

# Run specific test
cargo test --test test_pipeline_markdown_converter test_heading_detection_h1

# Run with output
cargo test --test test_pipeline_markdown_converter -- --nocapture
```

### Writing Custom Tests

```rust
#[test]
fn my_custom_test() {
    use pdf_oxide::layout::{Color, FontWeight, TextSpan};
    use pdf_oxide::pipeline::OrderedTextSpan;

    let span = OrderedTextSpan::new(
        TextSpan {
            text: "My text".to_string(),
            bbox: Rect::new(0.0, 100.0, 100.0, 24.0),
            font_name: "Arial".to_string(),
            font_size: 24.0,
            font_weight: FontWeight::Bold,
            is_italic: false,
            color: Color::black(),
            mcid: None,
            sequence: 0,
            offset_semantic: false,
            split_boundary_before: false,
            char_spacing: 0.0,
            word_spacing: 0.0,
            horizontal_scaling: 100.0,
        },
        0,
    );

    let converter = MarkdownOutputConverter::new();
    let config = TextPipelineConfig {
        output: OutputConfig {
            detect_headings: true,
            ..Default::default()
        },
        ..Default::default()
    };

    let output = converter.convert(&vec![span], &config).unwrap();
    assert!(output.contains("# My text"));
}
```

## Troubleshooting

### Issue: Headings not detected

**Cause**: Font size below 24pt threshold

**Solution**:
1. Check actual font sizes in PDF
2. Use ratio-based detection (supply range of sizes)
3. Consider using `preserve_layout` instead

### Issue: False positive tables

**Cause**: Any grid-aligned text detected as table

**Solution**: Set `extract_tables: false`

### Issue: Whitespace not preserved

**Cause**: Layout preservation disabled

**Solution**: Enable `preserve_layout: true`

### Issue: Bold/italic not formatting

**Cause**: Font weight or italic flag not set in TextSpan

**Solution**:
1. Verify PDF contains font styling info
2. Check font mapping is correct
3. Use Conservative bold behavior

## Advanced: Custom Converter

To create a custom markdown converter:

```rust
use pdf_oxide::pipeline::converters::OutputConverter;

struct MyCustomMarkdown;

impl OutputConverter for MyCustomMarkdown {
    fn convert(&self, spans: &[OrderedTextSpan], config: &TextPipelineConfig) -> Result<String> {
        // Your implementation
        Ok("...".to_string())
    }

    fn name(&self) -> &'static str {
        "MyCustomMarkdown"
    }

    fn mime_type(&self) -> &'static str {
        "text/markdown"
    }
}
```

## See Also

- [PDF Specification]../spec/pdf.md - ISO 32000-1:2008
- [Architecture]ARCHITECTURE.md - System design
- [Development Guide]DEVELOPMENT_GUIDE.md - Development workflow