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
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
//! Markdown input parser.
//!
//! Parses Markdown text into ContentElements for PDF generation.

use crate::elements::{ContentElement, FontSpec, TextContent, TextStyle};
use crate::error::Result;
use crate::geometry::Rect;

use super::{InputParser, InputParserConfig};

/// Parser for Markdown format.
///
/// Supports common Markdown elements:
/// - Headings (# to ######)
/// - Paragraphs
/// - Bold (**text** or __text__)
/// - Italic (*text* or _text_)
/// - Code blocks (``` or indented)
/// - Inline code (`code`)
/// - Lists (- or * or numbered)
/// - Horizontal rules (---, ***, ___)
#[derive(Debug, Clone, Default)]
pub struct MarkdownParser {
    /// Custom heading sizes (H1 to H6)
    heading_sizes: Option<[f32; 6]>,
}

impl MarkdownParser {
    /// Create a new Markdown parser with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set custom heading sizes.
    pub fn with_heading_sizes(mut self, sizes: [f32; 6]) -> Self {
        self.heading_sizes = Some(sizes);
        self
    }

    /// Get heading size for a given level (1-6).
    fn heading_size(&self, level: usize, base_size: f32) -> f32 {
        if let Some(sizes) = &self.heading_sizes {
            sizes
                .get(level.saturating_sub(1))
                .copied()
                .unwrap_or(base_size)
        } else {
            // Default heading sizes relative to base
            match level {
                1 => base_size * 2.0,
                2 => base_size * 1.5,
                3 => base_size * 1.25,
                4 => base_size * 1.1,
                5 => base_size * 1.0,
                6 => base_size * 0.9,
                _ => base_size,
            }
        }
    }

    /// Parse markdown into content elements.
    fn parse_markdown(
        &self,
        input: &str,
        config: &InputParserConfig,
    ) -> Result<Vec<ContentElement>> {
        let mut elements = Vec::new();
        let mut y_position = config.page_height - config.margin_top;
        let mut reading_order = 0;

        let lines: Vec<&str> = input.lines().collect();
        let mut i = 0;

        while i < lines.len() {
            let line = lines[i].trim_end();

            // Skip empty lines
            if line.is_empty() {
                y_position -= config.paragraph_spacing;
                i += 1;
                continue;
            }

            // Check for headings
            if let Some((level, text)) = self.parse_heading(line) {
                let font_size = self.heading_size(level, config.default_font_size);
                let line_height = font_size * config.line_height;

                y_position -= line_height;

                let element = self.create_text_element(
                    text,
                    config.margin_left,
                    y_position,
                    config.content_width(),
                    font_size,
                    &config.default_font,
                    TextStyle::bold(),
                    reading_order,
                );
                elements.push(element);
                reading_order += 1;

                // Extra spacing after headings
                y_position -= config.paragraph_spacing;
                i += 1;
                continue;
            }

            // Check for horizontal rule
            if self.is_horizontal_rule(line) {
                y_position -= config.paragraph_spacing;
                i += 1;
                continue;
            }

            // Check for code block
            if line.starts_with("```") {
                let (code_block, consumed) = self.parse_code_block(&lines[i..]);
                if !code_block.is_empty() {
                    let font_size = config.default_font_size * 0.9;
                    let line_height = font_size * config.line_height;

                    for code_line in code_block.lines() {
                        y_position -= line_height;

                        let element = self.create_text_element(
                            code_line,
                            config.margin_left + 20.0, // Indent code
                            y_position,
                            config.content_width() - 20.0,
                            font_size,
                            "Courier",
                            TextStyle::default(),
                            reading_order,
                        );
                        elements.push(element);
                        reading_order += 1;
                    }

                    y_position -= config.paragraph_spacing;
                }
                i += consumed;
                continue;
            }

            // Check for list item
            if let Some(text) = self.parse_list_item(line) {
                let line_height = config.default_font_size * config.line_height;
                y_position -= line_height;

                // Add bullet
                let bullet_element = self.create_text_element(
                    "\u{2022}", // Bullet character
                    config.margin_left,
                    y_position,
                    20.0,
                    config.default_font_size,
                    &config.default_font,
                    TextStyle::default(),
                    reading_order,
                );
                elements.push(bullet_element);
                reading_order += 1;

                // Add list item text
                let text_element = self.create_text_element(
                    text,
                    config.margin_left + 20.0,
                    y_position,
                    config.content_width() - 20.0,
                    config.default_font_size,
                    &config.default_font,
                    TextStyle::default(),
                    reading_order,
                );
                elements.push(text_element);
                reading_order += 1;

                i += 1;
                continue;
            }

            // Regular paragraph
            let paragraph = self.collect_paragraph(&lines[i..]);
            if !paragraph.is_empty() {
                let parsed_spans = self.parse_inline_formatting(&paragraph);
                let line_height = config.default_font_size * config.line_height;
                y_position -= line_height;

                for (text, style) in parsed_spans {
                    let element = self.create_text_element(
                        &text,
                        config.margin_left,
                        y_position,
                        config.content_width(),
                        config.default_font_size,
                        &config.default_font,
                        style,
                        reading_order,
                    );
                    elements.push(element);
                    reading_order += 1;
                }

                y_position -= config.paragraph_spacing;
            }

            // Skip consumed lines
            while i < lines.len() && !lines[i].is_empty() {
                i += 1;
            }
            i += 1;
        }

        Ok(elements)
    }

    /// Parse a heading line, returning level and text.
    fn parse_heading<'a>(&self, line: &'a str) -> Option<(usize, &'a str)> {
        let trimmed = line.trim_start();
        if !trimmed.starts_with('#') {
            return None;
        }

        let level = trimmed.chars().take_while(|&c| c == '#').count();
        if level > 6 || level == 0 {
            return None;
        }

        let text = trimmed[level..].trim();
        if text.is_empty() {
            return None;
        }

        Some((level, text))
    }

    /// Check if a line is a horizontal rule.
    fn is_horizontal_rule(&self, line: &str) -> bool {
        let trimmed = line.trim();
        if trimmed.len() < 3 {
            return false;
        }

        let chars: Vec<char> = trimmed.chars().filter(|c| !c.is_whitespace()).collect();
        if chars.is_empty() {
            return false;
        }

        let first = chars[0];
        (first == '-' || first == '*' || first == '_') && chars.iter().all(|&c| c == first)
    }

    /// Parse a code block, returning content and lines consumed.
    fn parse_code_block(&self, lines: &[&str]) -> (String, usize) {
        if lines.is_empty() || !lines[0].trim_start().starts_with("```") {
            return (String::new(), 0);
        }

        let mut content = String::new();
        let mut consumed = 1;

        for line in &lines[1..] {
            consumed += 1;
            if line.trim_start().starts_with("```") {
                break;
            }
            if !content.is_empty() {
                content.push('\n');
            }
            content.push_str(line);
        }

        (content, consumed)
    }

    /// Parse a list item, returning the text without the marker.
    fn parse_list_item<'a>(&self, line: &'a str) -> Option<&'a str> {
        let trimmed = line.trim_start();

        // Unordered list
        if trimmed.starts_with("- ") || trimmed.starts_with("* ") || trimmed.starts_with("+ ") {
            return Some(trimmed[2..].trim_start());
        }

        // Ordered list (1. 2. etc.)
        let mut chars = trimmed.chars().peekable();
        let mut has_digit = false;

        while let Some(&c) = chars.peek() {
            if c.is_ascii_digit() {
                has_digit = true;
                chars.next();
            } else {
                break;
            }
        }

        if has_digit {
            if let Some('.') = chars.next() {
                if let Some(' ') = chars.next() {
                    let digit_count = trimmed.chars().take_while(|c| c.is_ascii_digit()).count();
                    return Some(trimmed[digit_count + 2..].trim_start());
                }
            }
        }

        None
    }

    /// Collect a paragraph from consecutive non-empty lines.
    fn collect_paragraph(&self, lines: &[&str]) -> String {
        let mut paragraph = String::new();

        for line in lines {
            if line.is_empty() {
                break;
            }
            // Skip special lines
            if self.parse_heading(line).is_some()
                || self.is_horizontal_rule(line)
                || line.trim_start().starts_with("```")
                || self.parse_list_item(line).is_some()
            {
                break;
            }

            if !paragraph.is_empty() {
                paragraph.push(' ');
            }
            paragraph.push_str(line.trim());
        }

        paragraph
    }

    /// Parse inline formatting (bold, italic, code).
    fn parse_inline_formatting(&self, text: &str) -> Vec<(String, TextStyle)> {
        // Simple implementation - returns single span with detected style
        // A full implementation would handle nested formatting
        let mut result = Vec::new();

        // Check for bold
        if (text.starts_with("**") && text.ends_with("**") && text.len() > 4)
            || (text.starts_with("__") && text.ends_with("__") && text.len() > 4)
        {
            result.push((text[2..text.len() - 2].to_string(), TextStyle::bold()));
            return result;
        }

        // Check for italic
        if (text.starts_with('*') && text.ends_with('*') && text.len() > 2)
            || (text.starts_with('_') && text.ends_with('_') && text.len() > 2)
        {
            result.push((text[1..text.len() - 1].to_string(), TextStyle::italic()));
            return result;
        }

        // Default: plain text
        result.push((text.to_string(), TextStyle::default()));
        result
    }

    /// Create a text content element.
    fn create_text_element(
        &self,
        text: &str,
        x: f32,
        y: f32,
        width: f32,
        font_size: f32,
        font_name: &str,
        style: TextStyle,
        reading_order: usize,
    ) -> ContentElement {
        // Estimate height based on font size
        let height = font_size;

        ContentElement::Text(TextContent {
            artifact_type: None,
 
            text: text.to_string(),
            bbox: Rect::new(x, y, width, height),
            font: FontSpec::new(font_name, font_size),
            style,
            reading_order: Some(reading_order),
        })
    }
}

impl InputParser for MarkdownParser {
    fn parse(&self, input: &str, config: &InputParserConfig) -> Result<Vec<ContentElement>> {
        self.parse_markdown(input, config)
    }

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

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

    fn extensions(&self) -> &[&'static str] {
        &["md", "markdown"]
    }
}

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

    #[test]
    fn test_parse_heading() {
        let parser = MarkdownParser::new();

        assert_eq!(parser.parse_heading("# Title"), Some((1, "Title")));
        assert_eq!(parser.parse_heading("## Section"), Some((2, "Section")));
        assert_eq!(parser.parse_heading("### Subsection"), Some((3, "Subsection")));
        assert_eq!(parser.parse_heading("Not a heading"), None);
        assert_eq!(parser.parse_heading("####### Too many"), None);
    }

    #[test]
    fn test_is_horizontal_rule() {
        let parser = MarkdownParser::new();

        assert!(parser.is_horizontal_rule("---"));
        assert!(parser.is_horizontal_rule("***"));
        assert!(parser.is_horizontal_rule("___"));
        assert!(parser.is_horizontal_rule("- - -"));
        assert!(!parser.is_horizontal_rule("--"));
        assert!(!parser.is_horizontal_rule("text"));
    }

    #[test]
    fn test_parse_list_item() {
        let parser = MarkdownParser::new();

        assert_eq!(parser.parse_list_item("- Item"), Some("Item"));
        assert_eq!(parser.parse_list_item("* Item"), Some("Item"));
        assert_eq!(parser.parse_list_item("1. First"), Some("First"));
        assert_eq!(parser.parse_list_item("10. Tenth"), Some("Tenth"));
        assert_eq!(parser.parse_list_item("Not a list"), None);
    }

    #[test]
    fn test_parse_code_block() {
        let parser = MarkdownParser::new();

        let lines = ["```rust", "let x = 1;", "```"];
        let (content, consumed) = parser.parse_code_block(&lines);
        assert_eq!(content, "let x = 1;");
        assert_eq!(consumed, 3);
    }

    #[test]
    fn test_parse_simple_markdown() {
        let parser = MarkdownParser::new();
        let config = InputParserConfig::default();

        let input = "# Hello World\n\nThis is a paragraph.";
        let elements = parser.parse(input, &config).unwrap();

        assert!(elements.len() >= 2); // At least heading and paragraph

        // First element should be heading
        if let ContentElement::Text(text) = &elements[0] {
            assert_eq!(text.text, "Hello World");
            assert!(text.style.weight.is_bold());
        } else {
            panic!("Expected text element");
        }
    }

    #[test]
    fn test_heading_sizes() {
        let parser = MarkdownParser::new();
        let base = 12.0;

        assert_eq!(parser.heading_size(1, base), 24.0); // 2x
        assert_eq!(parser.heading_size(2, base), 18.0); // 1.5x
        assert_eq!(parser.heading_size(3, base), 15.0); // 1.25x
    }

    #[test]
    fn test_custom_heading_sizes() {
        let parser = MarkdownParser::new().with_heading_sizes([36.0, 28.0, 22.0, 18.0, 14.0, 12.0]);

        assert_eq!(parser.heading_size(1, 12.0), 36.0);
        assert_eq!(parser.heading_size(2, 12.0), 28.0);
    }
}