office2pdf 0.5.0

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
use std::collections::HashMap;

use crate::ir::{Color, DataBarInfo};
use crate::parser::xlsx::{CellPos, CellRange, parse_cell_ref};
use crate::parser::xml_util;

/// A conditional formatting override for a specific cell.
#[derive(Default)]
pub(crate) struct CondFmtOverride {
    pub background: Option<Color>,
    pub font_color: Option<Color>,
    pub bold: Option<bool>,
    pub data_bar: Option<DataBarInfo>,
    pub icon_text: Option<String>,
}

/// Parse an sqref string (e.g., "A1:C10" or "A1") into a list of CellRanges.
fn parse_sqref(sqref: &str) -> Vec<CellRange> {
    sqref
        .split_whitespace()
        .filter_map(|part| {
            if let Some((start_str, end_str)) = part.split_once(':') {
                let (sc, sr) = parse_cell_ref(start_str)?;
                let (ec, er) = parse_cell_ref(end_str)?;
                Some(CellRange {
                    start_col: sc,
                    start_row: sr,
                    end_col: ec,
                    end_row: er,
                })
            } else {
                let (c, r) = parse_cell_ref(part)?;
                Some(CellRange {
                    start_col: c,
                    start_row: r,
                    end_col: c,
                    end_row: r,
                })
            }
        })
        .collect()
}

use xml_util::parse_argb_color;

/// Try to get a numeric value from a cell.
fn cell_numeric_value(cell: &umya_spreadsheet::Cell) -> Option<f64> {
    let raw = cell.get_raw_value().to_string();
    if let Ok(v) = raw.parse::<f64>() {
        return Some(v);
    }
    cell.get_value().to_string().parse::<f64>().ok()
}

/// Evaluate a CellIs conditional formatting rule against a cell value.
fn evaluate_cell_is_rule(
    cell_val: f64,
    operator: &umya_spreadsheet::ConditionalFormattingOperatorValues,
    rule: &umya_spreadsheet::ConditionalFormattingRule,
) -> bool {
    use umya_spreadsheet::ConditionalFormattingOperatorValues::*;

    let formula_val = rule.get_formula().and_then(|f| {
        let s = f.get_address_str();
        s.trim().parse::<f64>().ok()
    });

    let Some(threshold) = formula_val else {
        return false;
    };

    match operator {
        GreaterThan => cell_val > threshold,
        GreaterThanOrEqual => cell_val >= threshold,
        LessThan => cell_val < threshold,
        LessThanOrEqual => cell_val <= threshold,
        Equal => (cell_val - threshold).abs() < f64::EPSILON,
        NotEqual => (cell_val - threshold).abs() >= f64::EPSILON,
        Between => cell_val >= threshold,
        NotBetween => cell_val < threshold,
        _ => false,
    }
}

/// Extract formatting overrides from a conditional formatting rule's style.
fn extract_cond_fmt_style(rule: &umya_spreadsheet::ConditionalFormattingRule) -> CondFmtOverride {
    let mut result = CondFmtOverride::default();

    if let Some(style) = rule.get_style() {
        if let Some(bg) = style.get_background_color() {
            result.background = parse_argb_color(bg.get_argb());
        }
        if let Some(font) = style.get_font() {
            if *font.get_bold() {
                result.bold = Some(true);
            }
            let color_argb = font.get_color().get_argb();
            if !color_argb.is_empty() && color_argb != "FF000000" {
                result.font_color = parse_argb_color(color_argb);
            }
        }
    }

    result
}

/// Parse an ARGB hex string from umya Color into an IR Color.
fn parse_umya_color_argb(color: &umya_spreadsheet::Color) -> Option<Color> {
    let argb = color.get_argb();
    if argb.is_empty() {
        return None;
    }
    parse_argb_color(argb)
}

/// Interpolate between two colors based on a ratio (0.0 = color_a, 1.0 = color_b).
fn interpolate_color(color_a: Color, color_b: Color, ratio: f64) -> Color {
    let ratio = ratio.clamp(0.0, 1.0);
    let r = (color_a.r as f64 + (color_b.r as f64 - color_a.r as f64) * ratio).round() as u8;
    let g = (color_a.g as f64 + (color_b.g as f64 - color_a.g as f64) * ratio).round() as u8;
    let b = (color_a.b as f64 + (color_b.b as f64 - color_a.b as f64) * ratio).round() as u8;
    Color::new(r, g, b)
}

/// Collect all numeric values in ranges from the sheet (for color scale min/max).
fn collect_numeric_values_in_ranges(
    sheet: &umya_spreadsheet::Worksheet,
    ranges: &[CellRange],
) -> Vec<f64> {
    let mut values = Vec::new();
    for range in ranges {
        for row in range.start_row..=range.end_row {
            for col in range.start_col..=range.end_col {
                if let Some(cell) = sheet.get_cell((col, row))
                    && let Some(val) = cell_numeric_value(cell)
                {
                    values.push(val);
                }
            }
        }
    }
    values
}

/// Compute the min, max, and range span of a set of values.
/// Returns `None` if the slice is empty.
fn compute_min_max(values: &[f64]) -> Option<(f64, f64, f64)> {
    if values.is_empty() {
        return None;
    }
    let min_val: f64 = values.iter().cloned().fold(f64::INFINITY, f64::min);
    let max_val: f64 = values.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
    let val_range: f64 = max_val - min_val;
    Some((min_val, max_val, val_range))
}

/// Apply a CellIs conditional formatting rule to matching cells in the given ranges.
fn apply_cell_is_rule(
    sheet: &umya_spreadsheet::Worksheet,
    rule: &umya_spreadsheet::ConditionalFormattingRule,
    ranges: &[CellRange],
    overrides: &mut HashMap<CellPos, CondFmtOverride>,
) {
    let operator = rule.get_operator();
    let fmt = extract_cond_fmt_style(rule);

    for range in ranges {
        for row in range.start_row..=range.end_row {
            for col in range.start_col..=range.end_col {
                if let Some(cell) = sheet.get_cell((col, row))
                    && let Some(val) = cell_numeric_value(cell)
                    && evaluate_cell_is_rule(val, operator, rule)
                {
                    let entry = overrides.entry((col, row)).or_default();
                    if fmt.background.is_some() {
                        entry.background = fmt.background;
                    }
                    if fmt.font_color.is_some() {
                        entry.font_color = fmt.font_color;
                    }
                    if fmt.bold.is_some() {
                        entry.bold = fmt.bold;
                    }
                }
            }
        }
    }
}

/// Apply a ColorScale conditional formatting rule to cells in the given ranges.
fn apply_color_scale_rule(
    sheet: &umya_spreadsheet::Worksheet,
    rule: &umya_spreadsheet::ConditionalFormattingRule,
    ranges: &[CellRange],
    overrides: &mut HashMap<CellPos, CondFmtOverride>,
) {
    let Some(cs) = rule.get_color_scale() else {
        return;
    };

    let colors: Vec<Option<Color>> = cs
        .get_color_collection()
        .iter()
        .map(parse_umya_color_argb)
        .collect();

    if colors.len() < 2 {
        return;
    }

    let numeric_vals: Vec<f64> = collect_numeric_values_in_ranges(sheet, ranges);
    let Some((min_val, _max_val, val_range)) = compute_min_max(&numeric_vals) else {
        return;
    };

    let color_min: Color = colors[0].unwrap_or(Color::white());
    let color_max: Color = colors[colors.len() - 1].unwrap_or(Color::black());

    for range in ranges {
        for row in range.start_row..=range.end_row {
            for col in range.start_col..=range.end_col {
                if let Some(cell) = sheet.get_cell((col, row))
                    && let Some(val) = cell_numeric_value(cell)
                {
                    let ratio: f64 = if val_range.abs() < f64::EPSILON {
                        0.5
                    } else {
                        (val - min_val) / val_range
                    };

                    let color: Color = if colors.len() == 3 {
                        let color_mid: Color = colors[1].unwrap_or(Color::new(255, 255, 0));
                        if ratio <= 0.5 {
                            interpolate_color(color_min, color_mid, ratio * 2.0)
                        } else {
                            interpolate_color(color_mid, color_max, (ratio - 0.5) * 2.0)
                        }
                    } else {
                        interpolate_color(color_min, color_max, ratio)
                    };

                    let entry = overrides.entry((col, row)).or_default();
                    entry.background = Some(color);
                }
            }
        }
    }
}

/// Apply a DataBar conditional formatting rule to cells in the given ranges.
fn apply_data_bar_rule(
    sheet: &umya_spreadsheet::Worksheet,
    rule: &umya_spreadsheet::ConditionalFormattingRule,
    ranges: &[CellRange],
    overrides: &mut HashMap<CellPos, CondFmtOverride>,
) {
    let Some(db) = rule.get_data_bar() else {
        return;
    };

    let bar_color: Color = db
        .get_color_collection()
        .first()
        .and_then(parse_umya_color_argb)
        .unwrap_or(Color::new(0x63, 0x8E, 0xC6)); // default blue

    let numeric_vals: Vec<f64> = collect_numeric_values_in_ranges(sheet, ranges);
    let Some((min_val, _max_val, val_range)) = compute_min_max(&numeric_vals) else {
        return;
    };

    for range in ranges {
        for row in range.start_row..=range.end_row {
            for col in range.start_col..=range.end_col {
                if let Some(cell) = sheet.get_cell((col, row))
                    && let Some(val) = cell_numeric_value(cell)
                {
                    let pct: f64 = if val_range.abs() < f64::EPSILON {
                        50.0
                    } else {
                        ((val - min_val) / val_range) * 100.0
                    };
                    let entry = overrides.entry((col, row)).or_default();
                    entry.data_bar = Some(DataBarInfo {
                        color: bar_color,
                        fill_pct: pct,
                    });
                }
            }
        }
    }
}

/// Apply an IconSet conditional formatting rule to cells in the given ranges.
fn apply_icon_set_rule(
    sheet: &umya_spreadsheet::Worksheet,
    rule: &umya_spreadsheet::ConditionalFormattingRule,
    ranges: &[CellRange],
    overrides: &mut HashMap<CellPos, CondFmtOverride>,
) {
    let numeric_vals: Vec<f64> = collect_numeric_values_in_ranges(sheet, ranges);
    let Some((min_val, _max_val, val_range)) = compute_min_max(&numeric_vals) else {
        return;
    };

    // Try to parse thresholds from IconSet cfvos
    let cfvo_thresholds: Vec<f64> = rule
        .get_icon_set()
        .map(|is| is.get_cfvo_collection())
        .unwrap_or(&[])
        .iter()
        .filter_map(|cfvo| {
            let pct: f64 = cfvo.get_val().parse().ok()?;
            Some(min_val + val_range * (pct / 100.0))
        })
        .collect();

    // Default to 3-icon equal-thirds if no thresholds available
    let thresholds: Vec<f64> = if cfvo_thresholds.len() >= 2 {
        cfvo_thresholds
    } else {
        vec![
            min_val,
            min_val + val_range / 3.0,
            min_val + val_range * 2.0 / 3.0,
        ]
    };

    // Default 3-icon arrows: down (low), right (mid), up (high)
    let icons: &[&str] = if thresholds.len() >= 5 {
        &["", "", "", "", ""]
    } else {
        &["", "", ""]
    };

    for range in ranges {
        for row in range.start_row..=range.end_row {
            for col in range.start_col..=range.end_col {
                if let Some(cell) = sheet.get_cell((col, row))
                    && let Some(val) = cell_numeric_value(cell)
                {
                    let icon_idx: usize = evaluate_icon_index(val, &thresholds, icons.len());
                    let entry = overrides.entry((col, row)).or_default();
                    entry.icon_text = Some(icons[icon_idx].to_string());
                }
            }
        }
    }
}

/// Build a map of conditional formatting overrides for all cells in the sheet.
pub(crate) fn build_cond_fmt_overrides(
    sheet: &umya_spreadsheet::Worksheet,
) -> HashMap<(u32, u32), CondFmtOverride> {
    let mut overrides: HashMap<CellPos, CondFmtOverride> = HashMap::new();

    for cf in sheet.get_conditional_formatting_collection() {
        let sqref = cf.get_sequence_of_references().get_sqref();
        let ranges: Vec<CellRange> = parse_sqref(&sqref);
        if ranges.is_empty() {
            continue;
        }

        for rule in cf.get_conditional_collection() {
            use umya_spreadsheet::ConditionalFormatValues;

            match rule.get_type() {
                ConditionalFormatValues::CellIs => {
                    apply_cell_is_rule(sheet, rule, &ranges, &mut overrides);
                }
                ConditionalFormatValues::ColorScale => {
                    apply_color_scale_rule(sheet, rule, &ranges, &mut overrides);
                }
                ConditionalFormatValues::DataBar => {
                    apply_data_bar_rule(sheet, rule, &ranges, &mut overrides);
                }
                ConditionalFormatValues::IconSet => {
                    apply_icon_set_rule(sheet, rule, &ranges, &mut overrides);
                }
                _ => {}
            }
        }
    }

    overrides
}

/// Determine which icon index a value falls into based on thresholds.
fn evaluate_icon_index(val: f64, thresholds: &[f64], num_icons: usize) -> usize {
    if num_icons == 0 {
        return 0;
    }
    // Iterate thresholds from highest to lowest
    for i in (1..thresholds.len()).rev() {
        if val >= thresholds[i] {
            return (i).min(num_icons - 1);
        }
    }
    0
}

#[cfg(test)]
#[path = "cond_fmt_tests.rs"]
mod tests;