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
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
//! Flat arena DOM built from the HTML tokenizer (HTML-2).
//!
//! Trades expressiveness for cheap traversal: every node is an entry
//! in `Dom::nodes`; references between nodes are `NodeId` (a `u32`
//! index). Sibling iteration walks parent's `children` vector directly.
//!
//! [`DomElement`] is a `Copy` handle pairing a `NodeId` with a
//! `&Dom`. It implements [`super::super::css::Element`] so the cascade
//! engine matches selectors against real document nodes — closing the
//! loop from CSS-4 (Element trait + matcher) through CSS-5 (cascade).
//!
//! Tree construction handles the common implicit-close cases that
//! showed up in the v0.3.35 fixtures (`<p>` auto-closes when another
//! `<p>` opens; `<li>` auto-closes when another `<li>` opens). The
//! full WHATWG insertion-mode state machine is *not* implemented —
//! v0.3.35 documents that callers needing wild-HTML tolerance should
//! preprocess.

use crate::html_css::css::matcher::{Element, ElementChildren};

use super::tokenizer::{tokenize, HtmlToken};

/// Index into [`Dom::nodes`].
pub type NodeId = u32;

/// What kind of node.
#[derive(Debug, Clone)]
pub enum NodeKind {
    /// The document root. Always at `NodeId(0)`.
    Document,
    /// `<tag attrs>...</tag>`.
    Element {
        /// Lowercase tag name.
        tag: String,
        /// Attribute map. Order is irrelevant for the matcher; we use
        /// a `Vec` because attribute counts are typically tiny and
        /// linear scan beats a HashMap for sub-10-attr nodes.
        attrs: Vec<(String, String)>,
    },
    /// Text content.
    Text(String),
    /// HTML comment — preserved for round-tripping but layout ignores.
    Comment(String),
    /// Raw text from a `<style>` or `<script>` element.
    RawText {
        /// `"style"` or `"script"`.
        host_tag: String,
        /// Body bytes.
        body: String,
    },
}

/// One node in the DOM.
#[derive(Debug, Clone)]
pub struct Node {
    /// What kind of node.
    pub kind: NodeKind,
    /// Parent node, or `None` for the document root.
    pub parent: Option<NodeId>,
    /// Direct children in source order.
    pub children: Vec<NodeId>,
}

/// The whole DOM.
#[derive(Debug, Clone, Default)]
pub struct Dom {
    /// All nodes, including the synthetic Document root at index 0.
    pub nodes: Vec<Node>,
}

impl Dom {
    /// Construct a fresh DOM with just the document root.
    pub fn new() -> Self {
        let mut d = Self {
            nodes: Vec::with_capacity(64),
        };
        d.nodes.push(Node {
            kind: NodeKind::Document,
            parent: None,
            children: Vec::new(),
        });
        d
    }

    /// Document root.
    pub const ROOT: NodeId = 0;

    /// Get a node by id.
    pub fn node(&self, id: NodeId) -> &Node {
        &self.nodes[id as usize]
    }

    /// Iterate all element nodes in document order.
    pub fn iter_elements(&self) -> impl Iterator<Item = NodeId> + '_ {
        (0..self.nodes.len() as NodeId)
            .filter(move |&i| matches!(self.nodes[i as usize].kind, NodeKind::Element { .. }))
    }

    /// Get a [`DomElement`] handle for the given id, returning `None`
    /// if the id doesn't point to an element.
    pub fn element(&self, id: NodeId) -> Option<DomElement<'_>> {
        if matches!(self.nodes[id as usize].kind, NodeKind::Element { .. }) {
            Some(DomElement { dom: self, id })
        } else {
            None
        }
    }

    /// Find the first element matching the predicate (DFS).
    pub fn find_element(
        &self,
        mut pred: impl FnMut(&str, &[(String, String)]) -> bool,
    ) -> Option<NodeId> {
        for id in self.iter_elements() {
            if let NodeKind::Element { tag, attrs } = &self.nodes[id as usize].kind {
                if pred(tag, attrs) {
                    return Some(id);
                }
            }
        }
        None
    }

    /// Find the first element with the given lowercase tag name.
    pub fn find_by_tag(&self, name: &str) -> Option<NodeId> {
        self.find_element(|tag, _| tag == name)
    }
}

// ─────────────────────────────────────────────────────────────────────
// Tree construction
// ─────────────────────────────────────────────────────────────────────

/// Tags that close any currently-open `<p>` when they open. The HTML5
/// spec's full list is bigger; this covers what HTML→PDF inputs hit.
const CLOSES_P_ON_OPEN: &[&str] = &[
    "address",
    "article",
    "aside",
    "blockquote",
    "details",
    "div",
    "dl",
    "fieldset",
    "figcaption",
    "figure",
    "footer",
    "form",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "header",
    "hr",
    "main",
    "menu",
    "nav",
    "ol",
    "p",
    "pre",
    "section",
    "table",
    "ul",
];

/// Parse an HTML source string into a [`Dom`].
pub fn parse_document(input: &str) -> Dom {
    let tokens = tokenize(input);
    let mut dom = Dom::new();
    let mut stack: Vec<NodeId> = vec![Dom::ROOT];

    for tok in tokens {
        match tok {
            HtmlToken::Doctype(_) | HtmlToken::Eof => {
                // Doctype is ignored; Eof terminates outer loop.
                if matches!(tok, HtmlToken::Eof) {
                    break;
                }
            },
            HtmlToken::Comment(body) => {
                let parent = *stack.last().unwrap();
                push_child(
                    &mut dom,
                    parent,
                    Node {
                        kind: NodeKind::Comment(body),
                        parent: Some(parent),
                        children: Vec::new(),
                    },
                );
            },
            HtmlToken::Text(s) => {
                if s.is_empty() {
                    continue;
                }
                let parent = *stack.last().unwrap();
                push_child(
                    &mut dom,
                    parent,
                    Node {
                        kind: NodeKind::Text(s),
                        parent: Some(parent),
                        children: Vec::new(),
                    },
                );
            },
            HtmlToken::RawText { host_tag, body } => {
                // Synthesize a host element with one RawText child so
                // CSS-3 (selectors) can still match `style`, `script`,
                // and HTML-3 can extract the body via NodeKind::RawText
                // child.
                let parent = *stack.last().unwrap();
                let host = push_child(
                    &mut dom,
                    parent,
                    Node {
                        kind: NodeKind::Element {
                            tag: host_tag.clone(),
                            attrs: Vec::new(),
                        },
                        parent: Some(parent),
                        children: Vec::new(),
                    },
                );
                push_child(
                    &mut dom,
                    host,
                    Node {
                        kind: NodeKind::RawText { host_tag, body },
                        parent: Some(host),
                        children: Vec::new(),
                    },
                );
            },
            HtmlToken::StartTag {
                name,
                attrs,
                self_closing,
            } => {
                // Implicit-close handling.
                if CLOSES_P_ON_OPEN.contains(&name.as_str()) && stack_top_is(&dom, &stack, "p") {
                    stack.pop();
                }
                if name == "li" && stack_top_is(&dom, &stack, "li") {
                    stack.pop();
                }
                let parent = *stack.last().unwrap();
                let new_id = push_child(
                    &mut dom,
                    parent,
                    Node {
                        kind: NodeKind::Element {
                            tag: name.clone(),
                            attrs,
                        },
                        parent: Some(parent),
                        children: Vec::new(),
                    },
                );
                if !self_closing {
                    stack.push(new_id);
                }
            },
            HtmlToken::EndTag { name } => {
                // Pop until we find a matching open tag, or until we
                // can't (forgive over-eager closes by leaving the
                // stack alone).
                let mut found_at: Option<usize> = None;
                for (i, &nid) in stack.iter().enumerate().rev() {
                    if let NodeKind::Element { tag, .. } = &dom.nodes[nid as usize].kind {
                        if tag == &name {
                            found_at = Some(i);
                            break;
                        }
                    }
                }
                if let Some(i) = found_at {
                    while stack.len() > i {
                        stack.pop();
                    }
                }
            },
        }
    }

    dom
}

fn push_child(dom: &mut Dom, parent: NodeId, mut node: Node) -> NodeId {
    let id = dom.nodes.len() as NodeId;
    node.parent = Some(parent);
    dom.nodes.push(node);
    dom.nodes[parent as usize].children.push(id);
    id
}

fn stack_top_is(dom: &Dom, stack: &[NodeId], tag_name: &str) -> bool {
    let Some(&top) = stack.last() else {
        return false;
    };
    matches!(
        &dom.nodes[top as usize].kind,
        NodeKind::Element { tag, .. } if tag == tag_name
    )
}

// ─────────────────────────────────────────────────────────────────────
// DomElement — Copy handle implementing the CSS-4 Element trait
// ─────────────────────────────────────────────────────────────────────

/// Cheap (`Copy`) handle that pairs a [`NodeId`] with the [`Dom`]
/// arena. Implements [`crate::html_css::css::matcher::Element`] so the
/// CSS cascade matches selectors against real document nodes.
#[derive(Debug, Clone, Copy)]
pub struct DomElement<'a> {
    /// Backing arena.
    pub dom: &'a Dom,
    /// Node id (must point to an Element).
    pub id: NodeId,
}

impl<'a> DomElement<'a> {
    fn node(&self) -> &Node {
        &self.dom.nodes[self.id as usize]
    }

    fn elem(&self) -> (&str, &[(String, String)]) {
        match &self.node().kind {
            NodeKind::Element { tag, attrs } => (tag, attrs),
            _ => panic!("DomElement points to non-element node"),
        }
    }

    /// All attribute (name, value) pairs.
    pub fn attrs(&self) -> &[(String, String)] {
        self.elem().1
    }
}

impl<'a> Element for DomElement<'a> {
    fn local_name(&self) -> &str {
        self.elem().0
    }
    fn id(&self) -> Option<&str> {
        self.elem()
            .1
            .iter()
            .find(|(k, _)| k == "id")
            .map(|(_, v)| v.as_str())
    }
    fn has_class(&self, c: &str) -> bool {
        self.elem()
            .1
            .iter()
            .find(|(k, _)| k == "class")
            .map(|(_, v)| v.split_ascii_whitespace().any(|t| t == c))
            .unwrap_or(false)
    }
    fn attribute(&self, name: &str) -> Option<&str> {
        self.elem()
            .1
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }
    fn has_attribute(&self, name: &str) -> bool {
        self.attribute(name).is_some()
    }
    fn parent(&self) -> Option<Self> {
        let p = self.node().parent?;
        // Skip past the synthetic Document root — selectors expect a
        // None parent at the html element so :root matches it.
        if matches!(self.dom.nodes[p as usize].kind, NodeKind::Document) {
            None
        } else {
            Some(DomElement {
                dom: self.dom,
                id: p,
            })
        }
    }
    fn prev_element_sibling(&self) -> Option<Self> {
        let p = self.node().parent?;
        let kids = &self.dom.nodes[p as usize].children;
        let pos = kids.iter().position(|&k| k == self.id)?;
        for &kid in kids[..pos].iter().rev() {
            if matches!(self.dom.nodes[kid as usize].kind, NodeKind::Element { .. }) {
                return Some(DomElement {
                    dom: self.dom,
                    id: kid,
                });
            }
        }
        None
    }
    fn next_element_sibling(&self) -> Option<Self> {
        let p = self.node().parent?;
        let kids = &self.dom.nodes[p as usize].children;
        let pos = kids.iter().position(|&k| k == self.id)?;
        for &kid in &kids[pos + 1..] {
            if matches!(self.dom.nodes[kid as usize].kind, NodeKind::Element { .. }) {
                return Some(DomElement {
                    dom: self.dom,
                    id: kid,
                });
            }
        }
        None
    }
    fn is_empty(&self) -> bool {
        // No element children and no non-whitespace text.
        for &kid in &self.node().children {
            match &self.dom.nodes[kid as usize].kind {
                NodeKind::Element { .. } => return false,
                NodeKind::Text(s) if !s.trim().is_empty() => return false,
                _ => {},
            }
        }
        true
    }
    fn first_element_child(&self) -> Option<Self> {
        for &kid in &self.node().children {
            if matches!(self.dom.nodes[kid as usize].kind, NodeKind::Element { .. }) {
                return Some(DomElement {
                    dom: self.dom,
                    id: kid,
                });
            }
        }
        None
    }
}

// Manual default implementation of element_children to inherit the
// trait's blanket version — the trait method does the right thing
// already.
impl<'a> DomElement<'a> {
    /// Iterator alias matching [`Element::element_children`].
    pub fn children_iter(&self) -> ElementChildren<DomElement<'a>> {
        Element::element_children(self)
    }
}

// ─────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::html_css::css::matcher::{match_selector_list, Element as CssElement};
    use crate::html_css::css::parser::{parse_stylesheet, Rule};
    use crate::html_css::css::selectors::parse_selector_list;

    fn dom(html: &str) -> Dom {
        parse_document(html)
    }

    fn first_element(d: &Dom, tag: &str) -> NodeId {
        d.find_by_tag(tag)
            .unwrap_or_else(|| panic!("must find <{tag}>"))
    }

    #[test]
    fn parse_simple_paragraph() {
        let d = dom("<p>hello</p>");
        let p = first_element(&d, "p");
        let kids = &d.node(p).children;
        assert_eq!(kids.len(), 1);
        match &d.node(kids[0]).kind {
            NodeKind::Text(s) => assert_eq!(s, "hello"),
            other => panic!("expected text, got {other:?}"),
        }
    }

    #[test]
    fn parse_attributes() {
        let d = dom(r#"<a href="x" class="foo bar" id="z">link</a>"#);
        let a = first_element(&d, "a");
        let el = d.element(a).unwrap();
        assert_eq!(el.id(), Some("z"));
        assert!(el.has_class("foo"));
        assert!(el.has_class("bar"));
        assert!(!el.has_class("baz"));
        assert_eq!(el.attribute("href"), Some("x"));
    }

    #[test]
    fn nested_structure() {
        let d = dom("<div><p>a</p><p>b</p></div>");
        let div = first_element(&d, "div");
        let kids = &d.node(div).children;
        assert_eq!(kids.len(), 2);
        for &k in kids {
            assert!(matches!(d.node(k).kind, NodeKind::Element { ref tag, .. } if tag == "p"));
        }
    }

    #[test]
    fn implicit_p_close_on_new_block() {
        let d = dom("<p>first<p>second");
        // Should produce two sibling <p>s, not nested.
        let body_or_root = Dom::ROOT;
        let kids = &d.node(body_or_root).children;
        assert_eq!(
            kids.iter()
                .filter(
                    |&&k| matches!(d.node(k).kind, NodeKind::Element { ref tag, .. } if tag == "p")
                )
                .count(),
            2
        );
    }

    #[test]
    fn implicit_li_close() {
        let d = dom("<ul><li>a<li>b<li>c</ul>");
        let ul = first_element(&d, "ul");
        let kids = &d.node(ul).children;
        let li_count = kids
            .iter()
            .filter(
                |&&k| matches!(d.node(k).kind, NodeKind::Element { ref tag, .. } if tag == "li"),
            )
            .count();
        assert_eq!(li_count, 3);
    }

    #[test]
    fn void_element_no_close_needed() {
        let d = dom("<div><br><br><br></div>");
        let div = first_element(&d, "div");
        assert_eq!(d.node(div).children.len(), 3);
    }

    #[test]
    fn style_block_preserved_as_raw_text() {
        let d = dom("<head><style>p{color:red;}</style></head>");
        let style = first_element(&d, "style");
        let kid = d.node(style).children[0];
        match &d.node(kid).kind {
            NodeKind::RawText { body, .. } => assert!(body.contains("color:red")),
            other => panic!("expected RawText, got {other:?}"),
        }
    }

    #[test]
    fn entities_decoded_in_text() {
        let d = dom("<p>Bread &amp; butter</p>");
        let p = first_element(&d, "p");
        let kid = d.node(p).children[0];
        if let NodeKind::Text(s) = &d.node(kid).kind {
            assert_eq!(s, "Bread & butter");
        } else {
            panic!();
        }
    }

    // ---- Element trait integration with the CSS matcher -----------

    #[test]
    fn cascade_matches_against_dom() {
        let d = dom(
            r#"<html><body><div id="main" class="container"><p class="lead">x</p></div></body></html>"#,
        );
        let p = first_element(&d, "p");
        let pe = d.element(p).unwrap();

        let ss = parse_stylesheet("p.lead {}").unwrap();
        let r = match &ss.rules[0] {
            Rule::Qualified(q) => q,
            _ => unreachable!(),
        };
        let list = parse_selector_list(&r.prelude).unwrap();
        assert!(match_selector_list(&list, pe));
    }

    #[test]
    fn descendant_combinator_via_dom() {
        let d = dom(r#"<html><body><div id="main"><span><a>x</a></span></div></body></html>"#);
        let a = first_element(&d, "a");
        let ae = d.element(a).unwrap();

        let ss = parse_stylesheet("#main a {}").unwrap();
        let r = match &ss.rules[0] {
            Rule::Qualified(q) => q,
            _ => unreachable!(),
        };
        let list = parse_selector_list(&r.prelude).unwrap();
        assert!(match_selector_list(&list, ae));
    }

    #[test]
    fn nth_child_via_dom() {
        let d = dom("<ul><li>a</li><li>b</li><li>c</li></ul>");
        let lis: Vec<NodeId> = d
            .iter_elements()
            .filter(
                |&id| matches!(d.node(id).kind, NodeKind::Element { ref tag, .. } if tag == "li"),
            )
            .collect();
        assert_eq!(lis.len(), 3);
        let pe2 = d.element(lis[1]).unwrap();
        assert_eq!(pe2.sibling_index(), 2);
    }

    #[test]
    fn parent_skips_document_root() {
        let d = dom("<html><body></body></html>");
        let html = d.element(first_element(&d, "html")).unwrap();
        // <html>'s parent is the synthetic Document, but we mask that
        // out so :root matches.
        assert!(html.parent().is_none());
    }

    #[test]
    fn case_insensitive_attribute_lookup() {
        let d = dom(r#"<input TYPE="text">"#);
        let inp = d.element(first_element(&d, "input")).unwrap();
        // attribute() lookup is case-insensitive.
        assert_eq!(inp.attribute("type"), Some("text"));
        assert_eq!(inp.attribute("TYPE"), Some("text"));
    }
}