harumi 1.4.0

Pure-Rust PDF — CJK font embedding (Chinese/Japanese/Korean), OCR text overlay, text extraction, HTML→PDF, page merge/split. WASM-ready, zero C deps.
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
//! Minimal HTML tokenizer for harumi's HTML→PDF renderer.
//!
//! A pure-Rust, zero-dependency HTML parser that handles a document-oriented
//! subset of HTML (headings, paragraphs, lists, tables, inline styles).
//! Designed to replace the `scraper` crate for lightweight PDF generation.

use std::collections::HashMap;

/// A node in the HTML tree: either text or an element.
#[derive(Debug, Clone)]
pub(crate) enum HtmlNode {
    Text(String),
    Element {
        tag: String,
        attrs: HashMap<String, String>,
        children: Vec<HtmlNode>,
    },
}

impl HtmlNode {
    /// Returns the tag name if this is an element, None if text.
    pub(crate) fn tag_name(&self) -> Option<&str> {
        match self {
            HtmlNode::Element { tag, .. } => Some(tag),
            HtmlNode::Text(_) => None,
        }
    }

    /// Returns the text content if this is a text node, None if element.
    pub(crate) fn as_text(&self) -> Option<&str> {
        match self {
            HtmlNode::Text(s) => Some(s),
            HtmlNode::Element { .. } => None,
        }
    }

    /// Returns attribute value by name (case-insensitive keys).
    pub(crate) fn attr(&self, name: &str) -> Option<String> {
        match self {
            HtmlNode::Element { attrs, .. } => {
                let lower = name.to_ascii_lowercase();
                attrs
                    .iter()
                    .find(|(k, _)| k.to_ascii_lowercase() == lower)
                    .map(|(_, v)| v.clone())
            }
            HtmlNode::Text(_) => None,
        }
    }

    /// Returns iterator over child elements (skipping text nodes).
    #[allow(dead_code)]
    pub(crate) fn child_elements(&self) -> impl Iterator<Item = &HtmlNode> {
        match self {
            HtmlNode::Element { children, .. } => children.iter(),
            HtmlNode::Text(_) => [].iter(),
        }
    }

    /// Returns iterator over all children (element and text).
    pub(crate) fn children(&self) -> impl Iterator<Item = &HtmlNode> {
        match self {
            HtmlNode::Element { children, .. } => children.iter(),
            HtmlNode::Text(_) => [].iter(),
        }
    }

    /// Recursively collects all text content.
    pub(crate) fn text_content(&self) -> String {
        match self {
            HtmlNode::Text(s) => s.clone(),
            HtmlNode::Element { children, .. } => children
                .iter()
                .map(|child| child.text_content())
                .collect::<Vec<_>>()
                .join(""),
        }
    }
}

/// Parse HTML string into a document tree.
///
/// This is a best-effort HTML parser for harumi's document-oriented subset.
/// It handles:
/// - Basic tags and attributes
/// - Self-closing tags (`<br>`, `<img>`, `<hr>`)
/// - HTML entities (`&amp;`, `&lt;`, `&gt;`, `&nbsp;`, `&#...;`)
/// - Malformed HTML (closes unclosed tags, ignores unmatched closing tags)
/// - Comments (`<!-- ... -->`)
pub(crate) fn parse_html(html: &str) -> HtmlNode {
    let mut parser = HtmlParser::new(html);
    parser.parse_root()
}

struct HtmlParser {
    input: Vec<char>,
    pos: usize,
}

impl HtmlParser {
    fn new(html: &str) -> Self {
        HtmlParser {
            input: html.chars().collect(),
            pos: 0,
        }
    }

    fn current(&self) -> Option<char> {
        if self.pos < self.input.len() {
            Some(self.input[self.pos])
        } else {
            None
        }
    }

    fn peek(&self, offset: usize) -> Option<char> {
        let p = self.pos + offset;
        if p < self.input.len() {
            Some(self.input[p])
        } else {
            None
        }
    }

    fn advance(&mut self) {
        self.pos += 1;
    }

    fn skip_whitespace(&mut self) {
        while let Some(c) = self.current() {
            if c.is_whitespace() {
                self.advance();
            } else {
                break;
            }
        }
    }

    fn read_until(&mut self, terminator: char) -> String {
        let mut result = String::new();
        while let Some(c) = self.current() {
            if c == terminator {
                break;
            }
            result.push(c);
            self.advance();
        }
        result
    }

    fn read_tag_name(&mut self) -> String {
        let mut result = String::new();
        while let Some(c) = self.current() {
            if c.is_ascii_alphanumeric() || c == '-' {
                result.push(c);
                self.advance();
            } else {
                break;
            }
        }
        result.to_lowercase()
    }

    fn read_attribute_name(&mut self) -> String {
        let mut result = String::new();
        while let Some(c) = self.current() {
            if c.is_ascii_alphanumeric() || c == '-' || c == ':' {
                result.push(c);
                self.advance();
            } else {
                break;
            }
        }
        result.to_lowercase()
    }

    fn read_attribute_value(&mut self) -> String {
        self.skip_whitespace();
        if self.current() != Some('=') {
            return String::new();
        }
        self.advance(); // skip '='
        self.skip_whitespace();

        let quote = self.current();
        if quote == Some('"') || quote == Some('\'') {
            self.advance();
            let value = self.read_until(quote.unwrap());
            if self.current() == quote {
                self.advance();
            }
            Self::decode_html_entities(&value)
        } else {
            // Unquoted attribute
            let mut result = String::new();
            while let Some(c) = self.current() {
                if c.is_whitespace() || c == '>' {
                    break;
                }
                result.push(c);
                self.advance();
            }
            Self::decode_html_entities(&result)
        }
    }

    fn read_attributes(&mut self) -> HashMap<String, String> {
        let mut attrs = HashMap::new();
        loop {
            self.skip_whitespace();
            if self.current() == Some('>') || self.current() == Some('/') {
                break;
            }
            let name = self.read_attribute_name();
            if name.is_empty() {
                break;
            }
            let value = self.read_attribute_value();
            attrs.insert(name, value);
        }
        attrs
    }

    fn parse_tag(&mut self) -> Option<(String, HashMap<String, String>, bool)> {
        // Current char should be '<'
        if self.current() != Some('<') {
            return None;
        }
        self.advance();

        // Check for comment
        if self.current() == Some('!') && self.peek(1) == Some('-') && self.peek(2) == Some('-') {
            self.advance(); // skip '!'
            self.advance(); // skip first '-'
            self.advance(); // skip second '-'
            // Skip until '-->'
            while self.current().is_some() {
                if self.current() == Some('-')
                    && self.peek(1) == Some('-')
                    && self.peek(2) == Some('>')
                {
                    self.advance();
                    self.advance();
                    self.advance();
                    break;
                }
                self.advance();
            }
            return None; // Comment nodes are skipped
        }

        // Check for closing tag
        if self.current() == Some('/') {
            return None;
        }

        let tag_name = self.read_tag_name();
        if tag_name.is_empty() {
            return None;
        }

        let attrs = self.read_attributes();

        let self_closing = self.current() == Some('/');
        if self_closing {
            self.advance();
        }

        if self.current() == Some('>') {
            self.advance();
        }

        Some((tag_name, attrs, self_closing))
    }

    fn is_self_closing_tag(tag: &str) -> bool {
        matches!(
            tag,
            "br" | "hr"
                | "img"
                | "input"
                | "meta"
                | "link"
                | "area"
                | "base"
                | "col"
                | "embed"
                | "source"
                | "track"
                | "wbr"
        )
    }

    fn decode_html_entities(text: &str) -> String {
        let mut result = String::new();
        let mut chars = text.chars().peekable();

        while let Some(c) = chars.next() {
            if c == '&' {
                let mut entity = String::new();
                while let Some(&next) = chars.peek() {
                    if next == ';' {
                        chars.next();
                        break;
                    }
                    entity.push(next);
                    chars.next();
                }

                let decoded: String = match entity.as_str() {
                    "amp" => "&".to_string(),
                    "lt" => "<".to_string(),
                    "gt" => ">".to_string(),
                    "quot" => "\"".to_string(),
                    "apos" => "'".to_string(),
                    "nbsp" => "\u{00A0}".to_string(),
                    _ if entity.starts_with('#') => {
                        if let Ok(code) = entity[1..].parse::<u32>() {
                            if let Some(ch) = char::from_u32(code) {
                                ch.to_string()
                            } else {
                                format!("&{};", entity)
                            }
                        } else {
                            format!("&{};", entity)
                        }
                    }
                    _ => format!("&{};", entity),
                };
                result.push_str(&decoded);
            } else {
                result.push(c);
            }
        }

        result
    }

    fn parse_root(&mut self) -> HtmlNode {
        let mut stack: Vec<(String, HashMap<String, String>, Vec<HtmlNode>)> = Vec::new(); // (tag, attrs, children)
        stack.push(("root".to_string(), HashMap::new(), Vec::new()));

        while self.current().is_some() && !stack.is_empty() {
            self.skip_whitespace();
            if self.current() == Some('<') {
                if self.peek(1) == Some('/') {
                    // Closing tag
                    self.advance(); // skip '<'
                    self.advance(); // skip '/'
                    let closing_tag = self.read_tag_name();
                    self.skip_whitespace();
                    if self.current() == Some('>') {
                        self.advance();
                    }
                    // Pop from stack if tag matches
                    if let Some((tag, _, _)) = stack.last() && closing_tag == *tag {
                        let (tag, attrs, children) = stack.pop().unwrap();
                        let node = HtmlNode::Element {
                            tag,
                            attrs,
                            children,
                        };
                        if let Some((_, _, parent_children)) = stack.last_mut() {
                            parent_children.push(node);
                        }
                    }
                } else if let Some((tag, attrs, is_self_closing)) = self.parse_tag() {
                    if is_self_closing || Self::is_self_closing_tag(&tag) {
                        let node = HtmlNode::Element {
                            tag,
                            attrs,
                            children: Vec::new(),
                        };
                        if let Some((_, _, children)) = stack.last_mut() {
                            children.push(node);
                        }
                    } else {
                        stack.push((tag, attrs, Vec::new()));
                    }
                }
            } else {
                // Text node
                let mut text = String::new();
                while let Some(c) = self.current() {
                    if c == '<' {
                        break;
                    }
                    text.push(c);
                    self.advance();
                }
                let decoded = Self::decode_html_entities(&text);
                if !decoded.trim().is_empty() && let Some((_, _, children)) = stack.last_mut() {
                    children.push(HtmlNode::Text(decoded));
                }
            }
        }

        if let Some((_, _, children)) = stack.pop() {
            HtmlNode::Element {
                tag: "root".to_string(),
                attrs: HashMap::new(),
                children,
            }
        } else {
            HtmlNode::Element {
                tag: "root".to_string(),
                attrs: HashMap::new(),
                children: Vec::new(),
            }
        }
    }
}