sghtmltopdf 0.6.1

HTML to PDF renderer that does not depend on Chromium, WebKit or Gecko
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
//! Serialising an inline `<svg>` element (from the HTML DOM) into an SVG document.
//!
//! The HTML parser has already done the hard part of the foreign-content rules: element
//! names such as `linearGradient` and attributes such as `viewBox` have their SVG casing
//! restored, and `xlink:href`/`xml:space`/`xmlns:*` carry their prefix. What is left is to
//! write the subtree out as XML for the SVG renderer ([`crate::pdf::svg`]):
//!
//! - the root gets `xmlns` (and `xmlns:xlink`) when the HTML markup left them out, which it
//!   usually does;
//! - `currentColor` is resolved by setting the root's `color` attribute to the element's
//!   computed CSS `color` (the renderer inherits it down the tree);
//! - a `width`/`height` the renderer cannot use as a size (`100%`, `2em`) is dropped, and when
//!   neither a `viewBox` nor a usable size is left, the CSS default replaced size 300x150
//!   stands in for the missing side.

use std::fmt::Write;

use html5ever::Attribute;

use crate::html::{Dom, NodeData, NodeId};
use crate::style::RgbaColor;

const SVG_NS: &str = "http://www.w3.org/2000/svg";
const XLINK_NS: &str = "http://www.w3.org/1999/xlink";

/// The CSS default size of a replaced element with neither an intrinsic size nor a ratio.
const DEFAULT_WIDTH: f32 = 300.0;
const DEFAULT_HEIGHT: f32 = 150.0;

/// Serialise the `<svg>` element `root` and its subtree. `color` is the element's computed
/// CSS `color`, used for `currentColor`.
pub fn serialize_inline_svg(dom: &Dom, root: NodeId, color: RgbaColor) -> String {
    let mut out = String::new();
    write_element(dom, root, true, color, &mut out);
    out
}

fn write_element(dom: &Dom, node: NodeId, is_root: bool, color: RgbaColor, out: &mut String) {
    let NodeData::Element { name, attrs, .. } = &dom.node(node).data else {
        return;
    };
    let tag = &*name.local;
    out.push('<');
    out.push_str(tag);
    if is_root {
        write_root_attributes(attrs, color, out);
    } else {
        for attr in attrs {
            if let Some(name) = serialisable_name(attr) {
                write_attribute(&name, &attr.value, out);
            }
        }
    }
    let mut children = dom.children(node).peekable();
    if children.peek().is_none() {
        out.push_str("/>");
        return;
    }
    out.push('>');
    for child in children {
        match &dom.node(child).data {
            // An element with a namespace prefix (`sodipodi:namedview`, `rdf:RDF`) has no
            // declared namespace once parsed as HTML; the SVG parser would reject the document.
            NodeData::Element { name, .. } if name.local.contains(':') => {}
            NodeData::Element { .. } => write_element(dom, child, false, color, out),
            NodeData::Text { contents } => escape_into(contents, false, out),
            _ => {}
        }
    }
    let _ = write!(out, "</{tag}>");
}

fn write_root_attributes(attrs: &[Attribute], color: RgbaColor, out: &mut String) {
    let mut has_xmlns = false;
    let mut has_xmlns_xlink = false;
    let mut view_box: Option<(f32, f32)> = None;
    let mut width = None;
    let mut height = None;

    for attr in attrs {
        let Some(name) = serialisable_name(attr) else {
            continue;
        };
        match name.as_str() {
            "xmlns" => has_xmlns = true,
            "xmlns:xlink" => has_xmlns_xlink = true,
            "viewBox" => view_box = parse_view_box_size(&attr.value),
            // CSS `color` is applied below; `width`/`height` are normalised below.
            "color" => continue,
            "width" => {
                width = svg_px_length(&attr.value);
                continue;
            }
            "height" => {
                height = svg_px_length(&attr.value);
                continue;
            }
            _ => {}
        }
        write_attribute(&name, &attr.value, out);
    }

    if !has_xmlns {
        write_attribute("xmlns", SVG_NS, out);
    }
    if !has_xmlns_xlink {
        write_attribute("xmlns:xlink", XLINK_NS, out);
    }
    // A missing side follows the viewBox's aspect ratio (the renderer would otherwise take the
    // viewBox's own height and letterbox the drawing). With no usable viewBox, the CSS default
    // replaced size applies.
    match (view_box, width, height) {
        (Some((vw, vh)), Some(w), None) => height = Some(w * vh / vw),
        (Some((vw, vh)), None, Some(h)) => width = Some(h * vw / vh),
        (None, _, _) => {
            width.get_or_insert(DEFAULT_WIDTH);
            height.get_or_insert(DEFAULT_HEIGHT);
        }
        _ => {}
    }
    if let Some(width) = width {
        write_attribute("width", &width.to_string(), out);
    }
    if let Some(height) = height {
        write_attribute("height", &height.to_string(), out);
    }
    write_attribute("color", &css_color(color), out);
}

/// The width and height of a `viewBox` (`None` unless four numbers with a positive size).
fn parse_view_box_size(value: &str) -> Option<(f32, f32)> {
    let numbers: Vec<f32> = value
        .split(|c: char| c.is_ascii_whitespace() || c == ',')
        .filter(|part| !part.is_empty())
        .map(|part| part.parse::<f32>())
        .collect::<Result<_, _>>()
        .ok()?;
    match numbers[..] {
        [_, _, w, h] if w > 0.0 && h > 0.0 && w.is_finite() && h.is_finite() => Some((w, h)),
        _ => None,
    }
}

/// A `width`/`height` attribute the renderer can take as a size: a positive number,
/// optionally in `px`. Percentages and font-relative units depend on the layout, which the
/// CSS side handles (see the presentational hints), so they are dropped here.
fn svg_px_length(value: &str) -> Option<f32> {
    let value = value.trim();
    let number = value.strip_suffix("px").unwrap_or(value).trim_end();
    number
        .parse::<f32>()
        .ok()
        .filter(|v| v.is_finite() && *v > 0.0)
}

fn css_color(color: RgbaColor) -> String {
    if color.alpha >= 1.0 {
        format!("rgb({},{},{})", color.red, color.green, color.blue)
    } else {
        format!(
            "rgba({},{},{},{})",
            color.red,
            color.green,
            color.blue,
            color.alpha.max(0.0)
        )
    }
}

/// `prefix:local` for a prefixed attribute (`xlink:href`, `xml:space`, `xmlns:xlink`),
/// otherwise the local name.
fn qualified_name(attr: &Attribute) -> String {
    // html5ever gives the plain `xmlns` attribute an empty (not absent) prefix.
    match attr
        .name
        .prefix
        .as_ref()
        .filter(|prefix| !prefix.is_empty())
    {
        Some(prefix) => format!("{prefix}:{}", attr.name.local),
        None => attr.name.local.to_string(),
    }
}

/// The attribute's name as written in XML, or `None` when XML cannot carry it. HTML allows
/// names such as `x-on:click`, `@click`, `:class` or `hx-on:click` (Alpine, Vue, htmx,
/// Livewire); written back as they are they make the whole document ill-formed or give it
/// an unbound namespace prefix, and the icon is lost. Only the prefixes the HTML parser
/// itself recognises (`xlink:`, `xml:`, `xmlns:`) survive, and they arrive as a prefix.
fn serialisable_name(attr: &Attribute) -> Option<String> {
    let has_parser_prefix = attr.name.prefix.as_ref().is_some_and(|p| !p.is_empty());
    let local = &*attr.name.local;
    if local.contains(':') && !has_parser_prefix {
        return None;
    }
    if !is_xml_name(local) {
        return None;
    }
    Some(qualified_name(attr))
}

/// Whether `name` is a valid XML name without a colon.
fn is_xml_name(name: &str) -> bool {
    let mut chars = name.chars();
    let start_ok = |c: char| c == '_' || c.is_alphabetic() || (c as u32) >= 0xC0;
    match chars.next() {
        Some(c) if start_ok(c) => {}
        _ => return false,
    }
    chars.all(|c| start_ok(c) || c.is_ascii_digit() || c == '-' || c == '.' || c == '\u{B7}')
}

/// Whether the `<svg>` at `root` has a `<use>` that refers to an id (`href="#id"`) no element
/// inside the same `<svg>` carries, which is how sprite sheets reference icons.
pub fn has_unresolved_use(dom: &Dom, root: NodeId) -> bool {
    fn walk(dom: &Dom, node: NodeId, ids: &mut Vec<String>, uses: &mut Vec<String>) {
        if let NodeData::Element { name, attrs, .. } = &dom.node(node).data {
            for attr in attrs {
                match &*attr.name.local {
                    "id" => ids.push(attr.value.to_string()),
                    "href" if &*name.local == "use" => {
                        if let Some(id) = attr.value.strip_prefix('#') {
                            uses.push(id.to_string());
                        }
                    }
                    _ => {}
                }
            }
        }
        for child in dom.children(node) {
            walk(dom, child, ids, uses);
        }
    }
    let (mut ids, mut uses) = (Vec::new(), Vec::new());
    walk(dom, root, &mut ids, &mut uses);
    uses.iter().any(|id| !ids.contains(id))
}

fn write_attribute(name: &str, value: &str, out: &mut String) {
    out.push(' ');
    out.push_str(name);
    out.push_str("=\"");
    escape_into(value, true, out);
    out.push('"');
}

/// Escape for XML text (or, with `attribute`, for a double-quoted attribute value) and drop
/// the characters XML 1.0 cannot carry at all.
fn escape_into(text: &str, attribute: bool, out: &mut String) {
    for c in text.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' if attribute => out.push_str("&quot;"),
            '\t' | '\n' | '\r' if attribute => {
                let _ = write!(out, "&#{};", c as u32);
            }
            '\t' | '\n' | '\r' => out.push(c),
            c if (c as u32) < 0x20 || c == '\u{FFFE}' || c == '\u{FFFF}' => {}
            c => out.push(c),
        }
    }
}

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

    fn serialize(markup: &str) -> String {
        let dom = html::parse(markup.as_bytes());
        let svg = find_svg(&dom, dom.document()).expect("no <svg>");
        serialize_inline_svg(&dom, svg, RgbaColor::BLACK)
    }

    fn find_svg(dom: &Dom, id: NodeId) -> Option<NodeId> {
        if let NodeData::Element { name, .. } = &dom.node(id).data {
            if &*name.local == "svg" {
                return Some(id);
            }
        }
        dom.children(id).find_map(|child| find_svg(dom, child))
    }

    #[test]
    fn adds_the_namespaces_the_html_markup_left_out() {
        let out = serialize(r#"<svg viewBox="0 0 10 1"><rect width="10" height="1"/></svg>"#);
        assert!(
            out.contains(r#"xmlns="http://www.w3.org/2000/svg""#),
            "{out}"
        );
        assert!(out.contains("xmlns:xlink="), "{out}");
        assert!(out.contains(r#"viewBox="0 0 10 1""#), "{out}");
        assert!(out.contains("<rect"), "{out}");
    }

    #[test]
    fn does_not_duplicate_an_existing_xmlns() {
        let out = serialize(
            r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><path d="M0 0"/></svg>"#,
        );
        assert_eq!(out.matches("xmlns=").count(), 1, "{out}");
    }

    #[test]
    fn keeps_svg_name_casing_and_prefixed_attributes() {
        let out = serialize(
            r##"<svg viewBox="0 0 4 4"><defs><linearGradient id="g"><stop offset="0"/></linearGradient></defs><use xlink:href="#g"/></svg>"##,
        );
        assert!(out.contains("<linearGradient"), "{out}");
        assert!(out.contains(r##"xlink:href="#g""##), "{out}");
    }

    #[test]
    fn drops_attributes_xml_cannot_carry() {
        let out = serialize(
            r##"<svg x-on:click="go()" @click="go()" :class="c" hx-on:click="x" wire:click="y" viewBox="0 0 1 1" data-ok="1"><path :d="d" x-data="{}" d="M0 0" xlink:href="#a" xml:space="preserve"/></svg>"##,
        );
        for gone in [
            "x-on:click",
            "@click",
            ":class",
            "hx-on:click",
            "wire:click",
            ":d",
        ] {
            assert!(!out.contains(gone), "{gone} kept: {out}");
        }
        for kept in [
            "viewBox=",
            "data-ok=\"1\"",
            "x-data=",
            "xlink:href=\"#a\"",
            "xml:space=",
        ] {
            assert!(out.contains(kept), "{kept} lost: {out}");
        }
    }

    #[test]
    fn drops_elements_with_a_namespace_prefix() {
        let out = serialize(
            r##"<svg viewBox="0 0 1 1"><sodipodi:namedview id="nv"><x/></sodipodi:namedview><metadata><rdf:RDF><cc:Work rdf:about=""/></rdf:RDF></metadata><path d="M0 0"/></svg>"##,
        );
        for gone in ["sodipodi", "rdf:", "cc:", "namedview"] {
            assert!(!out.contains(gone), "{gone} kept: {out}");
        }
        assert!(out.contains("<path"), "{out}");
        assert!(out.contains("<metadata"), "{out}");
    }

    #[test]
    fn xml_names_are_checked() {
        assert!(is_xml_name("stroke-width"));
        assert!(is_xml_name("_a.b1"));
        assert!(!is_xml_name("@click"));
        assert!(!is_xml_name("1a"));
        assert!(!is_xml_name("a b"));
        assert!(!is_xml_name(""));
    }

    #[test]
    fn finds_a_use_that_points_outside_the_svg() {
        let check = |markup: &str| {
            let dom = html::parse(markup.as_bytes());
            let svg = find_svg(&dom, dom.document()).unwrap();
            has_unresolved_use(&dom, svg)
        };
        assert!(check(r##"<svg><use href="#icon"/></svg>"##));
        assert!(!check(
            r##"<svg><defs><path id="icon" d="M0 0"/></defs><use href="#icon"/></svg>"##
        ));
        assert!(!check(r#"<svg><path d="M0 0"/></svg>"#));
    }

    #[test]
    fn sets_the_color_attribute_for_current_color() {
        let dom = html::parse(br#"<svg viewBox="0 0 1 1" color="blue"></svg>"#);
        let svg = find_svg(&dom, dom.document()).unwrap();
        let red = RgbaColor {
            red: 255,
            green: 0,
            blue: 0,
            alpha: 1.0,
        };
        let out = serialize_inline_svg(&dom, svg, red);
        assert!(out.contains(r#"color="rgb(255,0,0)""#), "{out}");
        assert_eq!(out.matches("color=").count(), 1, "{out}");
    }

    #[test]
    fn escapes_text_and_attribute_values() {
        let out = serialize(
            r#"<svg viewBox="0 0 1 1"><text data-x="a&quot;b&amp;c">1 &lt; 2 &amp; 3 &nbsp;</text></svg>"#,
        );
        assert!(out.contains(r#"data-x="a&quot;b&amp;c""#), "{out}");
        assert!(out.contains(">1 &lt; 2 &amp; 3 \u{a0}</text>"), "{out}");
    }

    #[test]
    fn style_element_text_is_kept() {
        let out = serialize(
            r#"<svg viewBox="0 0 1 1"><style>.a > rect { fill: red }</style><rect class="a"/></svg>"#,
        );
        assert!(
            out.contains("<style>.a &gt; rect { fill: red }</style>"),
            "{out}"
        );
    }

    #[test]
    fn a_missing_side_follows_the_view_box_ratio() {
        let out = serialize(r#"<svg viewBox="0 0 120 30" width="240"><rect/></svg>"#);
        assert!(
            out.contains(r#"width="240""#) && out.contains(r#"height="60""#),
            "{out}"
        );
        let out = serialize(r#"<svg viewBox="0 0 120 30" height="10"><rect/></svg>"#);
        assert!(out.contains(r#"width="40""#), "{out}");
    }

    #[test]
    fn unusable_sizes_are_dropped_and_the_default_size_fills_in_without_a_view_box() {
        let out = serialize(r#"<svg width="100%" height="2em"><rect/></svg>"#);
        assert!(out.contains(r#"width="300""#), "{out}");
        assert!(out.contains(r#"height="150""#), "{out}");
        let out = serialize(r#"<svg viewBox="0 0 24 24" width="100%"><rect/></svg>"#);
        assert!(!out.contains("width="), "{out}");
        let out = serialize(r#"<svg viewBox="0 0 24 24" height="2em"><rect/></svg>"#);
        assert!(!out.contains("height="), "{out}");
        let out = serialize(r#"<svg viewBox="0 0 24 24" width="48px"><rect/></svg>"#);
        assert!(out.contains(r#"width="48""#), "{out}");
    }
}