office2pdf 0.6.5

Convert DOCX, XLSX, and PPTX files to PDF using pure Rust
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
use super::{
    Alignment, Color, HyperlinkMap, LineSpacing, ParagraphStyle, TabAlignment, TabLeader, TabStop,
    TabStopOverride, TextStyle, VerticalTextAlign, apply_tab_stop_overrides,
};
use crate::ir::{BorderLineStyle, BorderSide, CellBorder, Insets, Run};
use crate::parser::units::{half_points_to_pt, twips_to_pt};
use crate::parser::xml_util;

// Word supplies an application- and locale-dependent sans face when the
// package omits one; Arial gives the parser a stable cross-platform baseline.
const WORD_COMPATIBLE_DEFAULT_FONT: &str = "Arial";

pub(super) fn extract_paragraph_style(prop: &docx_rs::ParagraphProperty) -> ParagraphStyle {
    let alignment = prop.alignment.as_ref().and_then(|j| match j.val.as_str() {
        "center" => Some(Alignment::Center),
        "right" | "end" => Some(Alignment::Right),
        "left" | "start" => Some(Alignment::Left),
        "both" | "justified" => Some(Alignment::Justify),
        _ => None,
    });

    let (indent_left, indent_right, indent_first_line) = extract_indent(&prop.indent);
    let (line_spacing, space_before, space_after) = extract_line_spacing(&prop.line_spacing);
    let tab_stops = extract_tab_stops(&prop.tabs);
    let border = extract_paragraph_borders(&prop.borders);
    let border_space = border
        .as_ref()
        .and_then(|_| extract_paragraph_border_space(&prop.borders));

    ParagraphStyle {
        alignment,
        indent_left,
        indent_right,
        indent_first_line,
        line_spacing,
        line_box: None,
        space_before,
        space_after,
        heading_level: None,
        direction: None,
        tab_stops,
        background: None,
        border,
        border_space,
    }
}

/// Each `w:pBdr` side's `w:space`, in points — the gap Word leaves between the
/// paragraph text and that rule. The attribute's own default is 0, so a border
/// that omits it gets no gap; substituting a fixed 4pt for every document
/// displaced everything below a bordered paragraph by the difference
/// (issue #520).
fn extract_paragraph_border_space(
    borders: &Option<docx_rs::ParagraphBorders>,
) -> Option<Box<Insets>> {
    let json = serde_json::to_value(borders.as_ref()?).ok()?;
    let side_space = |name: &str| -> f64 {
        json.get(name)
            .and_then(|side| side.get("space"))
            .and_then(serde_json::Value::as_f64)
            .unwrap_or(0.0)
    };
    Some(Box::new(Insets {
        top: side_space("top"),
        right: side_space("right"),
        bottom: side_space("bottom"),
        left: side_space("left"),
    }))
}

/// Word draws `w:pPr/w:pBdr` rules around the full paragraph width (heading
/// underlines, letterhead frames). docx-rs keeps the side fields private, so
/// they are read through the serialized form; `w:sz` is eighths of a point.
fn extract_paragraph_borders(
    borders: &Option<docx_rs::ParagraphBorders>,
) -> Option<Box<CellBorder>> {
    let borders = borders.as_ref()?;
    let json = serde_json::to_value(borders).ok()?;

    let side = |name: &str| -> Option<BorderSide> {
        let side_json = json.get(name)?;
        let val = side_json.get("val")?.as_str()?;
        let style = match val {
            "nil" | "none" => return None,
            "double" | "triple" => BorderLineStyle::Double,
            "dotted" => BorderLineStyle::Dotted,
            "dashed" | "dashSmallGap" => BorderLineStyle::Dashed,
            "dotDash" => BorderLineStyle::DashDot,
            "dotDotDash" => BorderLineStyle::DashDotDot,
            _ => BorderLineStyle::Solid,
        };
        let size = side_json
            .get("size")
            .and_then(|v| v.as_f64())
            .unwrap_or(4.0);
        let color = side_json
            .get("color")
            .and_then(|v| v.as_str())
            .and_then(xml_util::parse_hex_color)
            .unwrap_or_else(Color::black);
        Some(BorderSide {
            width: size / 8.0,
            color,
            style,
        })
    };

    let border = CellBorder {
        top: side("top"),
        bottom: side("bottom"),
        left: side("left"),
        right: side("right"),
    };
    if border.top.is_none()
        && border.bottom.is_none()
        && border.left.is_none()
        && border.right.is_none()
    {
        return None;
    }
    Some(Box::new(border))
}

fn extract_indent(indent: &Option<docx_rs::Indent>) -> (Option<f64>, Option<f64>, Option<f64>) {
    let Some(indent) = indent else {
        return (None, None, None);
    };

    let left = indent.start.map(twips_to_pt);
    let right = indent.end.map(twips_to_pt);
    let first_line = indent.special_indent.map(|si| match si {
        docx_rs::SpecialIndentType::FirstLine(v) => twips_to_pt(v),
        docx_rs::SpecialIndentType::Hanging(v) => -twips_to_pt(v),
    });

    (left, right, first_line)
}

fn extract_line_spacing(
    spacing: &Option<docx_rs::LineSpacing>,
) -> (Option<LineSpacing>, Option<f64>, Option<f64>) {
    let Some(spacing) = spacing else {
        return (None, None, None);
    };

    let json = match serde_json::to_value(spacing) {
        Ok(j) => j,
        Err(_) => return (None, None, None),
    };

    let space_before = json.get("before").and_then(|v| v.as_f64()).map(twips_to_pt);
    let space_after = json.get("after").and_then(|v| v.as_f64()).map(twips_to_pt);

    let line_spacing = json.get("line").and_then(|line_val| {
        let line = line_val.as_f64()?;
        let rule = json.get("lineRule").and_then(|v| v.as_str());
        match rule {
            Some("exact") | Some("atLeast") => Some(LineSpacing::Exact(twips_to_pt(line))),
            _ => Some(LineSpacing::Proportional(line / 240.0)),
        }
    });

    (line_spacing, space_before, space_after)
}

pub(super) fn extract_tab_stops(tabs: &[docx_rs::Tab]) -> Option<Vec<TabStop>> {
    let tab_overrides = extract_tab_stop_overrides(tabs)?;
    let mut tab_stops: Vec<TabStop> = Vec::new();
    apply_tab_stop_overrides(&mut tab_stops, &tab_overrides);
    Some(tab_stops)
}

pub(super) fn extract_tab_stop_overrides(tabs: &[docx_rs::Tab]) -> Option<Vec<TabStopOverride>> {
    if tabs.is_empty() {
        return None;
    }

    Some(
        tabs.iter()
            .filter_map(|tab| {
                let position = tab.pos.map(|pos_twips| twips_to_pt(pos_twips as f64))?;

                if matches!(tab.val, Some(docx_rs::TabValueType::Clear)) {
                    return Some(TabStopOverride::Clear(position));
                }

                let alignment = match tab.val {
                    Some(docx_rs::TabValueType::Center) => TabAlignment::Center,
                    Some(docx_rs::TabValueType::Right) | Some(docx_rs::TabValueType::End) => {
                        TabAlignment::Right
                    }
                    Some(docx_rs::TabValueType::Decimal) => TabAlignment::Decimal,
                    _ => TabAlignment::Left,
                };

                let leader =
                    match tab.leader {
                        Some(docx_rs::TabLeaderType::Dot)
                        | Some(docx_rs::TabLeaderType::MiddleDot) => TabLeader::Dot,
                        Some(docx_rs::TabLeaderType::Hyphen)
                        | Some(docx_rs::TabLeaderType::Heavy) => TabLeader::Hyphen,
                        Some(docx_rs::TabLeaderType::Underscore) => TabLeader::Underscore,
                        _ => TabLeader::None,
                    };

                Some(TabStopOverride::Set(TabStop {
                    position,
                    alignment,
                    leader,
                }))
            })
            .collect(),
    )
}

pub(super) fn extract_run_style(rp: &docx_rs::RunProperty) -> TextStyle {
    let json = serde_json::to_value(rp).unwrap_or(serde_json::Value::Null);
    extract_run_style_from_json(&json)
}

pub(super) fn extract_run_style_from_json(rp: &serde_json::Value) -> TextStyle {
    let vertical_align: Option<VerticalTextAlign> =
        rp.get("vertAlign").and_then(|va| match va.as_str()? {
            "superscript" => Some(VerticalTextAlign::Superscript),
            "subscript" => Some(VerticalTextAlign::Subscript),
            _ => None,
        });

    let all_caps: Option<bool> = rp.get("caps").and_then(serde_json::Value::as_bool);

    TextStyle {
        bold: rp.get("bold").and_then(serde_json::Value::as_bool),
        italic: rp.get("italic").and_then(serde_json::Value::as_bool),
        underline: rp
            .get("underline")
            .and_then(|u| u.as_str())
            .and_then(|val| if val == "none" { None } else { Some(true) }),
        strikethrough: rp.get("strike").and_then(json_bool_or_val),
        font_size: rp
            .get("sz")
            .and_then(serde_json::Value::as_f64)
            .map(half_points_to_pt),
        color: rp
            .get("color")
            .and_then(serde_json::Value::as_str)
            .and_then(xml_util::parse_hex_color),
        font_family: rp.get("fonts").and_then(|fonts| {
            fonts
                .get("ascii")
                .or_else(|| fonts.get("hiAnsi"))
                .or_else(|| fonts.get("eastAsia"))
                .or_else(|| fonts.get("cs"))
                .and_then(serde_json::Value::as_str)
                .map(String::from)
        }),
        highlight: rp
            .get("highlight")
            .and_then(serde_json::Value::as_str)
            .and_then(resolve_highlight_color),
        vertical_align,
        all_caps,
        small_caps: None,
        letter_spacing: rp
            .get("characterSpacing")
            .and_then(serde_json::Value::as_i64)
            .map(|twips| twips_to_pt(twips as f64)),
    }
}

fn json_bool_or_val(value: &serde_json::Value) -> Option<bool> {
    value
        .as_bool()
        .or_else(|| value.get("val").and_then(serde_json::Value::as_bool))
}

pub(super) fn extract_doc_default_text_style_with_theme(
    styles: &docx_rs::Styles,
    theme_fonts: &ThemeFonts,
) -> TextStyle {
    let json = serde_json::to_value(&styles.doc_defaults).ok();
    let run_property = json.as_ref().and_then(|value| {
        value
            .get("runPropertyDefault")
            .and_then(|value| value.get("runProperty"))
    });
    let mut style = run_property
        .map(extract_run_style_from_json)
        .unwrap_or_default();
    if style.font_family.is_none() {
        style.font_family = run_property
            .and_then(|property| resolve_theme_font_family(property, theme_fonts))
            .or_else(|| Some(WORD_COMPATIBLE_DEFAULT_FONT.to_string()));
    }
    style
}

/// Latin typefaces of the document theme's minor (body) and major (heading)
/// font schemes, from `word/theme/theme1.xml`.
#[derive(Debug, Clone, Default)]
pub(super) struct ThemeFonts {
    pub(super) minor_latin: Option<String>,
    pub(super) major_latin: Option<String>,
}

/// Parse the theme's font scheme latin typefaces.
pub(super) fn parse_theme_fonts(theme_xml: &str) -> ThemeFonts {
    use quick_xml::Reader;
    use quick_xml::events::Event;

    let mut fonts = ThemeFonts::default();
    let mut reader = Reader::from_str(theme_xml);
    let mut in_minor = false;
    let mut in_major = false;

    loop {
        match reader.read_event() {
            Ok(Event::Start(ref e)) => match e.local_name().as_ref() {
                b"minorFont" => in_minor = true,
                b"majorFont" => in_major = true,
                _ => {}
            },
            Ok(Event::Empty(ref e)) if e.local_name().as_ref() == b"latin" => {
                let typeface: Option<String> = e.attributes().flatten().find_map(|attr| {
                    (attr.key.local_name().as_ref() == b"typeface")
                        .then(|| attr.unescape_value().ok())
                        .flatten()
                        .map(|v| v.to_string())
                        .filter(|v| !v.is_empty())
                });
                if in_minor {
                    fonts.minor_latin = typeface;
                } else if in_major {
                    fonts.major_latin = typeface;
                }
            }
            Ok(Event::End(ref e)) => match e.local_name().as_ref() {
                b"minorFont" => in_minor = false,
                b"majorFont" => in_major = false,
                _ => {}
            },
            Ok(Event::Eof) => break,
            Err(_) => break,
            _ => {}
        }
    }

    fonts
}

/// Resolve rFonts theme slots (asciiTheme="minorHAnsi" etc.) against the
/// document theme when no literal font family is given.
pub(super) fn resolve_theme_font_family(
    run_property_json: &serde_json::Value,
    theme_fonts: &ThemeFonts,
) -> Option<String> {
    let fonts = run_property_json.get("fonts")?;
    let slot: &str = fonts
        .get("asciiTheme")
        .or_else(|| fonts.get("hiAnsiTheme"))
        .or_else(|| fonts.get("eastAsiaTheme"))
        .or_else(|| fonts.get("csTheme"))
        .and_then(serde_json::Value::as_str)?;
    if slot.starts_with("minor") {
        theme_fonts.minor_latin.clone()
    } else if slot.starts_with("major") {
        theme_fonts.major_latin.clone()
    } else {
        None
    }
}

pub(super) fn resolve_highlight_color(name: &str) -> Option<Color> {
    match name {
        "yellow" => Some(Color::new(255, 255, 0)),
        "green" => Some(Color::new(0, 255, 0)),
        "cyan" => Some(Color::new(0, 255, 255)),
        "magenta" => Some(Color::new(255, 0, 255)),
        "blue" => Some(Color::new(0, 0, 255)),
        "red" => Some(Color::new(255, 0, 0)),
        "darkBlue" => Some(Color::new(0, 0, 128)),
        "darkCyan" => Some(Color::new(0, 128, 128)),
        "darkGreen" => Some(Color::new(0, 128, 0)),
        "darkMagenta" => Some(Color::new(128, 0, 128)),
        "darkRed" => Some(Color::new(128, 0, 0)),
        "darkYellow" => Some(Color::new(128, 128, 0)),
        "darkGray" => Some(Color::new(128, 128, 128)),
        "lightGray" => Some(Color::new(192, 192, 192)),
        "black" => Some(Color::new(0, 0, 0)),
        "white" => Some(Color::new(255, 255, 255)),
        _ => None,
    }
}

// Re-export for sibling modules that import from here.
pub(super) use xml_util::parse_hex_color;

pub(super) fn resolve_hyperlink_url(
    hyperlink: &docx_rs::Hyperlink,
    hyperlinks: &HyperlinkMap,
) -> Option<String> {
    match &hyperlink.link {
        docx_rs::HyperlinkData::External { rid, path } => {
            if !path.is_empty() {
                Some(path.clone())
            } else {
                hyperlinks.get(rid).cloned()
            }
        }
        docx_rs::HyperlinkData::Anchor { .. } => None,
    }
}

pub(super) fn is_column_break(br: &docx_rs::Break) -> bool {
    break_type(br).as_deref() == Some("column")
}

pub(super) fn is_page_break(br: &docx_rs::Break) -> bool {
    break_type(br).as_deref() == Some("page")
}

fn break_type(br: &docx_rs::Break) -> Option<String> {
    serde_json::to_value(br)
        .ok()
        .and_then(|value| value.get("breakType")?.as_str().map(String::from))
}

pub(super) fn extract_run_text_skip_layout_breaks(run: &docx_rs::Run) -> String {
    let mut text = String::new();
    for child in &run.children {
        match child {
            docx_rs::RunChild::Text(t) => text.push_str(&t.text),
            docx_rs::RunChild::Tab(_) => text.push('\t'),
            docx_rs::RunChild::Break(br) if !is_column_break(br) && !is_page_break(br) => {
                text.push('\n');
            }
            _ => {}
        }
    }
    text
}

pub(super) fn extract_run_text(run: &docx_rs::Run) -> String {
    let mut text = String::new();
    for child in &run.children {
        match child {
            docx_rs::RunChild::Text(t) => text.push_str(&t.text),
            docx_rs::RunChild::Tab(_) => text.push('\t'),
            docx_rs::RunChild::Break(_) => text.push('\n'),
            _ => {}
        }
    }
    text
}

/// Extract the referenced character style id (`<w:rStyle>`) from a run's
/// properties, if present. docx-rs serialises the reference under the `style`
/// key. Used to resolve syntax-highlighting token styles (issue #176).
pub(super) fn extract_run_style_id(run_property: &docx_rs::RunProperty) -> Option<String> {
    serde_json::to_value(run_property)
        .ok()?
        .get("style")?
        .as_str()
        .map(String::from)
}

/// In-text marker for Word's automatic space between East Asian text and
/// adjacent Latin letters or digits. The renderer expands it to a quarter em
/// and it is never emitted literally; see the matching constant there.
const EAST_ASIAN_AUTO_SPACE_CHAR: char = '\u{E001}';

/// Insert Word's automatic space at every East Asian/Latin boundary in the
/// paragraph that does not already carry a literal space.
///
/// `w:autoSpaceDE` and `w:autoSpaceDN` are on unless a paragraph turns them
/// off, and the space they add is exactly a quarter em. Measured on a native
/// Word export of a ten-case probe that varies one factor at a time: the same
/// sentence gets 2.625pt at 10.5pt and 2.375pt at 9.5pt as a plain paragraph, a
/// `w:numPr` list item, a justified paragraph, a `ListParagraph`-styled
/// paragraph, and a table cell alike, on both sides of a Latin island
/// (`제3자` widens at `제→3` and at `3→자`). Only setting the two properties to
/// `false` suppresses it, and then completely (issue #521).
///
/// The boundary can fall between two runs, so the scan carries the previous
/// character across the run break rather than restarting at each run.
///
/// TODO(docx-rs models neither `w:autoSpaceDE` nor `w:autoSpaceDN`, so a
/// paragraph that explicitly turns them off still gets the space; both default
/// to on, which is what every file in the corpus relies on).
pub(super) fn insert_east_asian_auto_space(runs: &mut [Run]) {
    let mut previous: Option<char> = None;
    for run in runs.iter_mut() {
        if run.footnote.is_some() {
            previous = None;
            continue;
        }
        let mut spaced = String::with_capacity(run.text.len());
        for ch in run.text.chars() {
            // Never trust the marker from the input: it is ours to place.
            if ch == EAST_ASIAN_AUTO_SPACE_CHAR {
                continue;
            }
            if previous.is_some_and(|previous| needs_auto_space_between(previous, ch)) {
                spaced.push(EAST_ASIAN_AUTO_SPACE_CHAR);
            }
            spaced.push(ch);
            previous = Some(ch);
        }
        run.text = spaced;
    }
}

fn needs_auto_space_between(left: char, right: char) -> bool {
    (is_east_asian_text(left) && is_western_alphanumeric(right))
        || (is_western_alphanumeric(left) && is_east_asian_text(right))
}

/// East Asian *text*, deliberately narrower than the renderer's `is_cjk_like`:
/// CJK symbols and punctuation and the fullwidth forms are already full-width
/// and Word adds nothing beside them, so widening a boundary at `、` or `.`
/// would be over-applying the rule.
fn is_east_asian_text(ch: char) -> bool {
    matches!(
        ch as u32,
        0x1100..=0x11FF   // Hangul Jamo
            | 0x3040..=0x30FF // Hiragana and Katakana
            | 0x3130..=0x318F // Hangul Compatibility Jamo
            | 0x3400..=0x4DBF // CJK Unified Ideographs Extension A
            | 0x4E00..=0x9FFF // CJK Unified Ideographs
            | 0xAC00..=0xD7AF // Hangul Syllables
            | 0xF900..=0xFAFF // CJK Compatibility Ideographs
    )
}

fn is_western_alphanumeric(ch: char) -> bool {
    ch.is_ascii_alphanumeric()
}