office2pdf 0.6.3

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
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
use super::*;

pub(super) fn generate_table(
    out: &mut String,
    table: &Table,
    ctx: &mut GenCtx,
) -> Result<(), ConvertError> {
    ctx.table_depth += 1;
    let result = match table.alignment {
        Some(Alignment::Center) => {
            out.push_str("#align(center)[\n");
            let result = generate_table_inner(out, table, ctx);
            out.push_str("]\n");
            result
        }
        Some(Alignment::Right) => {
            out.push_str("#align(right)[\n");
            let result = generate_table_inner(out, table, ctx);
            out.push_str("]\n");
            result
        }
        _ => generate_table_inner(out, table, ctx),
    };
    ctx.table_depth -= 1;
    result
}

fn generate_table_inner(
    out: &mut String,
    table: &Table,
    ctx: &mut GenCtx,
) -> Result<(), ConvertError> {
    out.push_str("#table(\n");

    // Only explicitly set borders render: Excel does not print gridlines,
    // and Word/PowerPoint borderless tables have none either. Typst's
    // default 1pt grid painted spurious borders on every unbordered table.
    out.push_str("  stroke: none,\n");

    if let Some(ref default_vertical_align) = table.default_vertical_align {
        let align_str: &str = match default_vertical_align {
            CellVerticalAlign::Top => "top",
            CellVerticalAlign::Center => "horizon",
            CellVerticalAlign::Bottom => "bottom",
        };
        let _ = writeln!(out, "  align: {align_str},");
    }

    if let Some(padding) = table.default_cell_padding {
        let _ = writeln!(out, "  inset: {},", format_insets(&padding));
    }

    let num_cols = if !table.column_widths.is_empty() {
        table.column_widths.len()
    } else {
        table.rows.iter().map(|r| r.cells.len()).max().unwrap_or(0)
    };

    if !table.column_widths.is_empty() {
        out.push_str("  columns: (");
        for (i, w) in table.column_widths.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            let _ = write!(out, "{}pt", format_f64(*w));
        }
        out.push_str("),\n");
    } else if num_cols > 1 {
        let _ = writeln!(out, "  columns: {num_cols},");
    }

    if !table.use_content_driven_row_heights && table.rows.iter().any(|row| row.height.is_some()) {
        out.push_str("  rows: (");
        for (i, row) in table.rows.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            match row.height {
                Some(height) => {
                    let _ = write!(out, "{}pt", format_f64(height));
                }
                None => out.push_str("auto"),
            }
        }
        out.push_str("),\n");
    }

    let mut rowspan_remaining = vec![0usize; num_cols];
    let header_row_count = table.header_row_count.min(table.rows.len());
    let default_cell_padding = table.default_cell_padding.unwrap_or(Insets {
        top: 5.0,
        right: 5.0,
        bottom: 5.0,
        left: 5.0,
    });

    let fixed_row_heights = !table.use_content_driven_row_heights;

    if header_row_count > 0 {
        out.push_str("  table.header(\n");
        generate_table_rows(
            out,
            &table.rows[..header_row_count],
            num_cols,
            &mut rowspan_remaining,
            "    ",
            default_cell_padding,
            fixed_row_heights,
            ctx,
        )?;
        out.push_str("  ),\n");
    }

    generate_table_rows(
        out,
        &table.rows[header_row_count..],
        num_cols,
        &mut rowspan_remaining,
        "  ",
        default_cell_padding,
        fixed_row_heights,
        ctx,
    )?;

    out.push_str(")\n");
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn generate_table_rows(
    out: &mut String,
    rows: &[TableRow],
    num_cols: usize,
    rowspan_remaining: &mut [usize],
    indent: &str,
    default_cell_padding: Insets,
    fixed_row_heights: bool,
    ctx: &mut GenCtx,
) -> Result<(), ConvertError> {
    for row in rows {
        for rs in rowspan_remaining.iter_mut() {
            if *rs > 0 {
                *rs -= 1;
            }
        }

        let mut col_pos: usize = 0;
        for cell in &row.cells {
            if cell.col_span == 0 || cell.row_span == 0 {
                continue;
            }

            while col_pos < num_cols && rowspan_remaining[col_pos] > 0 {
                col_pos += 1;
            }
            if col_pos >= num_cols {
                break;
            }

            let remaining = num_cols - col_pos;
            let clamped_colspan = (cell.col_span as usize).min(remaining).max(1) as u32;
            generate_table_cell(
                out,
                cell,
                clamped_colspan,
                indent,
                default_cell_padding,
                row.height.filter(|_| fixed_row_heights),
                ctx,
            )?;

            if cell.row_span > 1 {
                for rs in rowspan_remaining
                    .iter_mut()
                    .skip(col_pos)
                    .take(clamped_colspan as usize)
                {
                    *rs = cell.row_span as usize;
                }
            }
            col_pos += clamped_colspan as usize;
        }

        while col_pos < num_cols {
            if rowspan_remaining[col_pos] == 0 {
                let _ = writeln!(out, "{indent}[],");
            }
            col_pos += 1;
        }
    }

    Ok(())
}

fn generate_table_cell(
    out: &mut String,
    cell: &TableCell,
    clamped_colspan: u32,
    indent: &str,
    default_cell_padding: Insets,
    row_height: Option<f64>,
    ctx: &mut GenCtx,
) -> Result<(), ConvertError> {
    let needs_cell_fn = clamped_colspan > 1
        || cell.row_span > 1
        || cell.border.is_some()
        || cell.background.is_some()
        || cell.vertical_align.is_some()
        || cell.padding.is_some();

    if needs_cell_fn {
        out.push_str(indent);
        out.push_str("table.cell(");
        write_cell_params(out, cell, clamped_colspan);
        out.push_str(")[");
    } else {
        out.push_str(indent);
        out.push('[');
    }

    if let Some(border) = &cell.border {
        write_double_border_overlays(out, border, cell.padding.unwrap_or(default_cell_padding));
    }

    if let Some(ref db) = cell.data_bar {
        // Excel draws the bar behind the value on the same line (no track),
        // with a horizontal fade of the bar color; #place keeps it out of
        // layout so the value renders on top at its normal position. The bar
        // height must be concrete: in auto-height rows a relative height has
        // no cell frame to resolve against and blows up to the page height,
        // smearing over neighboring rows (issue #362).
        let pct = db.fill_pct.clamp(0.0, 100.0);
        let padding = cell.padding.unwrap_or(default_cell_padding);
        let bar_height: String = match row_height {
            Some(height) => {
                let content_height = (height - padding.top - padding.bottom).max(1.0);
                format!("{}pt", format_f64(content_height))
            }
            // Excel sizes default rows to the font's line box; 1.2em tracks
            // that for single-line numeric cells.
            None => "1.2em".to_string(),
        };
        let _ = write!(
            out,
            "#place(left + horizon, box(width: {}%, height: {}, fill: gradient.linear(rgb({}, {}, {}), rgb({}, {}, {}).lighten(70%))))",
            format_f64(pct),
            bar_height,
            db.color.r,
            db.color.g,
            db.color.b,
            db.color.r,
            db.color.g,
            db.color.b,
        );
    }

    if let Some(ref icon) = cell.icon_text {
        // Excel draws icon set glyphs in their band color, independent of
        // the cell's font color, anchored at the cell's left edge on the
        // value's own line. Placing the icon out of layout keeps narrow
        // cells from wrapping the value onto a second line, which doubled
        // the row height (issue #367).
        match cell.icon_color {
            Some(color) => {
                let _ = write!(
                    out,
                    "#place(left + horizon, text(fill: rgb({}, {}, {}), weight: \"bold\")[{}])",
                    color.r, color.g, color.b, icon
                );
            }
            None => {
                let _ = write!(
                    out,
                    "#place(left + horizon, text(weight: \"bold\")[{icon}])"
                );
            }
        }
    }

    if let Some(spill_width) = cell.spill_width {
        // Excel paints unwrapped text across empty right neighbors without
        // growing the row: lay the content out on one clipped line via
        // #place (out of layout) and hold the row height with a zero-width
        // strut.
        let _ = write!(
            out,
            "#place(left + horizon, box(width: {}pt, height: 1.3em, clip: true)[",
            format_f64(spill_width),
        );
        generate_cell_content(out, &cell.content, ctx)?;
        out.push_str("])#box(width: 0pt, height: 1.3em)");
    } else {
        generate_cell_content(out, &cell.content, ctx)?;
    }
    out.push_str("],\n");
    Ok(())
}

fn write_double_border_overlays(out: &mut String, border: &CellBorder, padding: Insets) {
    if let Some(side) = border
        .top
        .as_ref()
        .filter(|side| side.style == BorderLineStyle::Double)
    {
        write_horizontal_double_border(out, side, padding, true);
    }
    if let Some(side) = border
        .bottom
        .as_ref()
        .filter(|side| side.style == BorderLineStyle::Double)
    {
        write_horizontal_double_border(out, side, padding, false);
    }
    if let Some(side) = border
        .left
        .as_ref()
        .filter(|side| side.style == BorderLineStyle::Double)
    {
        write_vertical_double_border(out, side, padding, true);
    }
    if let Some(side) = border
        .right
        .as_ref()
        .filter(|side| side.style == BorderLineStyle::Double)
    {
        write_vertical_double_border(out, side, padding, false);
    }
}

fn write_horizontal_double_border(
    out: &mut String,
    side: &BorderSide,
    padding: Insets,
    is_top: bool,
) {
    let align = if is_top {
        "top + left"
    } else {
        "bottom + left"
    };
    let first_dy = if is_top {
        -padding.top - side.width
    } else {
        padding.bottom - side.width
    };
    let second_dy = if is_top {
        -padding.top + side.width
    } else {
        padding.bottom + side.width
    };
    let dx = -padding.left;
    let length_extra = padding.left + padding.right;
    write_double_border_line(out, align, dx, first_dy, "0deg", length_extra, side);
    write_double_border_line(out, align, dx, second_dy, "0deg", length_extra, side);
}

fn write_vertical_double_border(
    out: &mut String,
    side: &BorderSide,
    padding: Insets,
    is_left: bool,
) {
    let align = if is_left { "top + left" } else { "top + right" };
    let first_dx = if is_left {
        -padding.left - side.width
    } else {
        padding.right - side.width
    };
    let second_dx = if is_left {
        -padding.left + side.width
    } else {
        padding.right + side.width
    };
    let dy = -padding.top;
    let length_extra = padding.top + padding.bottom;
    write_double_border_line(out, align, first_dx, dy, "90deg", length_extra, side);
    write_double_border_line(out, align, second_dx, dy, "90deg", length_extra, side);
}

fn write_double_border_line(
    out: &mut String,
    align: &str,
    dx: f64,
    dy: f64,
    angle: &str,
    length_extra: f64,
    side: &BorderSide,
) {
    let _ = write!(
        out,
        "#place({align}, dx: {}pt, dy: {}pt, line(length: 100% + {}pt, angle: {angle}, stroke: {}pt + rgb({}, {}, {})))",
        format_geometry(dx),
        format_geometry(dy),
        format_geometry(length_extra),
        format_geometry(side.width),
        side.color.r,
        side.color.g,
        side.color.b,
    );
}

fn format_geometry(value: f64) -> String {
    let rounded = (value * 1_000.0).round() / 1_000.0;
    format_f64(if rounded == -0.0 { 0.0 } else { rounded })
}

fn write_cell_params(out: &mut String, cell: &TableCell, clamped_colspan: u32) {
    let mut first = true;

    if clamped_colspan > 1 {
        write_param(out, &mut first, &format!("colspan: {clamped_colspan}"));
    }
    if cell.row_span > 1 {
        write_param(out, &mut first, &format!("rowspan: {}", cell.row_span));
    }
    if let Some(ref bg) = cell.background {
        write_param(out, &mut first, &format_color(bg));
    }
    if let Some(ref padding) = cell.padding {
        write_param(
            out,
            &mut first,
            &format!("inset: {}", format_insets(padding)),
        );
    }
    if let Some(ref border) = cell.border {
        let stroke = format_cell_stroke(border);
        if !stroke.is_empty() {
            write_param(out, &mut first, &stroke);
        }
    }
    if let Some(ref va) = cell.vertical_align {
        let align_str: &str = match va {
            CellVerticalAlign::Top => "top",
            CellVerticalAlign::Center => "horizon",
            CellVerticalAlign::Bottom => "bottom",
        };
        write_param(out, &mut first, &format!("align: {align_str}"));
    }
}

fn format_cell_stroke(border: &CellBorder) -> String {
    let mut parts = Vec::with_capacity(4);

    if let Some(ref side) = border.top
        && side.style != BorderLineStyle::Double
    {
        parts.push(format!("top: {}", format_border_side(side)));
    }
    if let Some(ref side) = border.bottom
        && side.style != BorderLineStyle::Double
    {
        parts.push(format!("bottom: {}", format_border_side(side)));
    }
    if let Some(ref side) = border.left
        && side.style != BorderLineStyle::Double
    {
        parts.push(format!("left: {}", format_border_side(side)));
    }
    if let Some(ref side) = border.right
        && side.style != BorderLineStyle::Double
    {
        parts.push(format!("right: {}", format_border_side(side)));
    }

    if parts.is_empty() {
        String::new()
    } else {
        format!("stroke: ({})", parts.join(", "))
    }
}

fn format_border_side(side: &BorderSide) -> String {
    let base = format!(
        "{}pt + rgb({}, {}, {})",
        format_f64(side.width),
        side.color.r,
        side.color.g,
        side.color.b
    );
    match side.style {
        BorderLineStyle::Solid | BorderLineStyle::Double | BorderLineStyle::None => base,
        _ => format!(
            "(paint: rgb({}, {}, {}), thickness: {}pt, dash: \"{}\")",
            side.color.r,
            side.color.g,
            side.color.b,
            format_f64(side.width),
            border_line_style_to_typst(side.style),
        ),
    }
}

fn generate_cell_content(
    out: &mut String,
    blocks: &[Block],
    ctx: &mut GenCtx,
) -> Result<(), ConvertError> {
    for (i, block) in blocks.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        match block {
            Block::Paragraph(para) => generate_cell_paragraph(out, para),
            Block::Table(table) => {
                if ctx.table_depth < MAX_TABLE_DEPTH {
                    generate_table(out, table, ctx)?;
                }
            }
            Block::Image(img) => generate_image(out, img, ctx),
            Block::InlineImages(images) => {
                for image in images {
                    generate_image(out, image, ctx);
                }
            }
            Block::FloatingImage(fi) => generate_floating_image(out, fi, ctx),
            Block::FloatingTextBox(ftb) => generate_floating_text_box(out, ftb, ctx)?,
            Block::FloatingShape(fs) => generate_floating_shape(out, fs),
            Block::List(list) => {
                if can_render_fixed_text_list_inline(list) {
                    generate_fixed_text_list(out, list, true, None)?;
                } else {
                    generate_list(out, list, None)?;
                }
            }
            Block::MathEquation(math) => generate_math_equation(out, math),
            Block::Chart(chart) => generate_chart(out, chart),
            Block::PageBreak | Block::ColumnBreak => {}
        }
    }
    Ok(())
}

fn generate_cell_paragraph(out: &mut String, para: &Paragraph) {
    let style: &ParagraphStyle = &para.style;
    let alignment = style.alignment;
    let align_str: Option<&str> = match alignment {
        Some(Alignment::Left) => Some("left"),
        Some(Alignment::Center) => Some("center"),
        Some(Alignment::Right) => Some("right"),
        _ => None,
    };
    let has_block_wrapper = cell_paragraph_needs_block_wrapper(style) || align_str.is_some();

    if has_block_wrapper {
        out.push_str("#block(");
        write_cell_paragraph_block_params(out, align_str.is_some());
        out.push_str(")[\n");
        write_line_box_settings(out, style.line_box);
        write_par_settings(out, style);
        if let Some(align_str) = align_str {
            let _ = writeln!(out, "  #set align({align_str})");
        }
    }

    if let Some(space_before) = style.space_before {
        let _ = writeln!(out, "#v({}pt)", format_f64(space_before));
    }

    generate_runs_with_tabs(out, &para.runs, style.tab_stops.as_deref());

    if let Some(space_after) = style.space_after {
        let _ = write!(out, "\n#v({}pt)", format_f64(space_after));
    }

    if has_block_wrapper {
        out.push_str("\n]");
    }
}

fn cell_paragraph_needs_block_wrapper(style: &ParagraphStyle) -> bool {
    style.line_spacing.is_some()
        || style.line_box.is_some()
        || matches!(style.alignment, Some(Alignment::Justify))
        || matches!(style.direction, Some(TextDirection::Rtl))
}

fn write_cell_paragraph_block_params(out: &mut String, needs_full_width: bool) {
    let mut first = true;

    if needs_full_width {
        write_param(out, &mut first, "width: 100%");
    }
}