oxidize-pdf 2.6.0

A pure Rust PDF generation and manipulation library with zero external dependencies
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! Page extension for table rendering
//!
//! This module provides traits and implementations to easily add tables to PDF pages.

use crate::document::Document;
use crate::error::{ensure_finite, PdfError};
use crate::graphics::Color;
use crate::page::Page;
use crate::text::{Font, HeaderStyle, Table, TableOptions};

/// Extension trait for adding tables to pages
pub trait PageTables {
    /// Add a simple table to the page
    fn add_simple_table(&mut self, table: &Table, x: f64, y: f64) -> Result<&mut Self, PdfError>;

    /// Create and add a quick table with equal columns
    fn add_quick_table(
        &mut self,
        data: Vec<Vec<String>>,
        x: f64,
        y: f64,
        width: f64,
        options: Option<TableOptions>,
    ) -> Result<&mut Self, PdfError>;

    /// Create and add an advanced table with custom styling
    fn add_styled_table(
        &mut self,
        headers: Vec<String>,
        data: Vec<Vec<String>>,
        x: f64,
        y: f64,
        width: f64,
        style: TableStyle,
    ) -> Result<&mut Self, PdfError>;
}

/// Predefined table styles
#[derive(Debug, Clone)]
pub struct TableStyle {
    /// Header background color
    pub header_background: Option<Color>,
    /// Header text color
    pub header_text_color: Option<Color>,
    /// Default font size
    pub font_size: f64,
    /// Header font override. `None` keeps the legacy default (`Font::Helvetica`).
    /// See [issue #217](https://github.com/bzsanti/oxidizePdf/issues/217).
    pub header_font: Option<Font>,
    /// Header bold override. `None` keeps the legacy default (`true`).
    /// Combined with `header_font`, the rendering layer maps non-oblique
    /// builtin fonts to their `*Bold` variant (e.g. `TimesRoman` + `bold=true`
    /// → `TimesBold`); oblique fonts and custom fonts are passed through
    /// unchanged.
    pub header_bold: Option<bool>,
}

impl TableStyle {
    /// Create a minimal table style (no borders)
    pub fn minimal() -> Self {
        Self {
            header_background: None,
            header_text_color: None,
            font_size: 10.0,
            header_font: None,
            header_bold: None,
        }
    }

    /// Create a simple table style with borders
    pub fn simple() -> Self {
        Self {
            header_background: None,
            header_text_color: None,
            font_size: 10.0,
            header_font: None,
            header_bold: None,
        }
    }

    /// Create a professional table style
    pub fn professional() -> Self {
        Self {
            header_background: Some(Color::gray(0.1)),
            header_text_color: Some(Color::white()),
            font_size: 10.0,
            header_font: None,
            header_bold: None,
        }
    }

    /// Create a colorful table style
    pub fn colorful() -> Self {
        Self {
            header_background: Some(Color::rgb(0.2, 0.4, 0.8)),
            header_text_color: Some(Color::white()),
            font_size: 10.0,
            header_font: None,
            header_bold: None,
        }
    }

    /// Override the header font. Chainable on presets.
    ///
    /// ```
    /// use oxidize_pdf::page_tables::TableStyle;
    /// use oxidize_pdf::text::Font;
    /// let style = TableStyle::professional().with_header_font(Font::TimesRoman);
    /// assert_eq!(style.header_font, Some(Font::TimesRoman));
    /// ```
    pub fn with_header_font(mut self, font: Font) -> Self {
        self.header_font = Some(font);
        self
    }

    /// Override the header bold flag. Chainable on presets.
    ///
    /// ```
    /// use oxidize_pdf::page_tables::TableStyle;
    /// let style = TableStyle::simple().with_header_bold(false);
    /// assert_eq!(style.header_bold, Some(false));
    /// ```
    pub fn with_header_bold(mut self, bold: bool) -> Self {
        self.header_bold = Some(bold);
        self
    }
}

impl PageTables for Page {
    fn add_simple_table(&mut self, table: &Table, x: f64, y: f64) -> Result<&mut Self, PdfError> {
        let mut table_clone = table.clone();
        table_clone.set_position(x, y);
        table_clone.render(self.graphics())?;
        Ok(self)
    }

    fn add_quick_table(
        &mut self,
        data: Vec<Vec<String>>,
        x: f64,
        y: f64,
        width: f64,
        options: Option<TableOptions>,
    ) -> Result<&mut Self, PdfError> {
        if data.is_empty() {
            return Ok(self);
        }

        let num_columns = data[0].len();
        let mut table = Table::with_equal_columns(num_columns, width);

        if let Some(opts) = options {
            table.set_options(opts);
        }

        for row in data {
            table.add_row(row)?;
        }

        self.add_simple_table(&table, x, y)
    }

    fn add_styled_table(
        &mut self,
        headers: Vec<String>,
        data: Vec<Vec<String>>,
        x: f64,
        y: f64,
        width: f64,
        style: TableStyle,
    ) -> Result<&mut Self, PdfError> {
        let num_columns = headers.len();
        if num_columns == 0 {
            return Ok(self);
        }

        // Create a simple table with the given style
        let mut table = Table::with_equal_columns(num_columns, width);

        // Create table options based on style.
        //
        // The header gate now also fires on `header_font` / `header_bold`
        // overrides — without this, a caller picking `TableStyle::minimal()`
        // (where both colour fields are `None`) and overriding only the font
        // would have their request silently ignored.
        let header_style = if style.header_background.is_some()
            || style.header_text_color.is_some()
            || style.header_font.is_some()
            || style.header_bold.is_some()
        {
            Some(HeaderStyle {
                background_color: style.header_background.unwrap_or(Color::white()),
                text_color: style.header_text_color.unwrap_or(Color::black()),
                font: style.header_font.clone().unwrap_or(Font::Helvetica),
                bold: style.header_bold.unwrap_or(true),
            })
        } else {
            None
        };

        let options = TableOptions {
            font_size: style.font_size,
            header_style,
            ..Default::default()
        };

        table.set_options(options);

        // Add header row — `add_header_row` (not `add_row`) sets
        // `is_header: true`. Without it the row is treated as data and the
        // configured `HeaderStyle` is never applied at render time
        // (see `Table::render`'s `use_header_style = row.is_header && …`
        // guard). This was a pre-existing bug surfaced while fixing #217.
        table.add_header_row(headers)?;

        // Add data rows
        for row_data in data {
            table.add_row(row_data)?;
        }

        self.add_simple_table(&table, x, y)
    }
}

/// Document-level extension for table rendering with automatic pagination.
///
/// Where [`PageTables`] writes a table on a single page, this trait will
/// allocate continuation pages as needed when the table doesn't fit, and
/// (by default) repeat header rows on each new page.
///
/// See [issue #218](https://github.com/bzsanti/oxidizePdf/issues/218) for the
/// motivating use case.
pub trait DocumentTables {
    /// Render `table` starting at `(x, y)` on the page at `starting_page_index`.
    /// If the table doesn't fit above `bottom_y`, allocate new pages of the
    /// same dimensions and continue rendering each remaining slice at
    /// `(x, next_page_y)`.
    ///
    /// All `y` values are absolute coordinates in the page's PDF coordinate
    /// system (origin at the bottom-left). `bottom_y` is the floor below
    /// which no row may be drawn; `next_page_y` is the top of the table on
    /// every continuation page.
    ///
    /// When `table.options().repeat_header_on_split` is `true` (the default),
    /// the leading header rows are repeated at the top of every continuation
    /// page.
    ///
    /// # Returns
    ///
    /// `(final_page_index, final_y)` — where the layout cursor ended up after
    /// the table was fully rendered. Callers can resume layout from there.
    ///
    /// # Errors
    ///
    /// Returns [`PdfError::TableOverflow`] when a single row is taller than
    /// the available vertical space on a fresh page (the table cannot make
    /// progress and would loop forever).
    fn add_paginated_table(
        &mut self,
        starting_page_index: usize,
        table: &Table,
        x: f64,
        y: f64,
        bottom_y: f64,
        next_page_y: f64,
    ) -> Result<(usize, f64), PdfError>;
}

impl DocumentTables for Document {
    fn add_paginated_table(
        &mut self,
        starting_page_index: usize,
        table: &Table,
        x: f64,
        y: f64,
        bottom_y: f64,
        next_page_y: f64,
    ) -> Result<(usize, f64), PdfError> {
        // Reject non-finite floats at the API boundary. NaN comparisons silently
        // return `false`, which would bypass `fit_count`'s overflow guard and
        // silently render off-page — exactly the failure mode #218 prevents.
        ensure_finite("x", x)?;
        ensure_finite("y", y)?;
        ensure_finite("bottom_y", bottom_y)?;
        ensure_finite("next_page_y", next_page_y)?;

        let repeat_headers = table.options().repeat_header_on_split;

        let mut current_table = table.clone();
        current_table.set_position(x, y);

        let mut current_page_idx = starting_page_index;

        loop {
            // Capture the current page's dims (needed both for the floor check
            // and for allocating a same-sized continuation page).
            let (page_width, page_height) = match self.page(current_page_idx) {
                Some(p) => (p.width(), p.height()),
                None => {
                    return Err(PdfError::InvalidStructure(format!(
                        "page index {current_page_idx} out of bounds (page_count={})",
                        self.page_count()
                    )))
                }
            };

            // Snapshot the data-row count BEFORE rendering. The progress check
            // must compare *data* rows, not raw row counts: a header-heavy
            // table where the page only fits headers would render some rows
            // but advance zero data rows, then re-prepend headers for the next
            // page — unbounded memory growth (DoS).
            let current_data_rows = current_table.row_count() - current_table.header_count();

            let tail = {
                let page = self.page_mut(current_page_idx).expect("checked above");
                current_table.render_with_split(page.graphics(), bottom_y)?
            };

            match tail {
                None => {
                    let final_y = current_table.position().1 - current_table.get_height();
                    return Ok((current_page_idx, final_y));
                }
                Some(mut tail) => {
                    // Forward progress: at least one *data* row must have been
                    // drawn on this page. Comparing raw `row_count()` is wrong
                    // because headers prepended on the next iteration inflate
                    // the count without making progress.
                    let tail_data_rows = tail.row_count() - tail.header_count();
                    let data_rows_drawn = current_data_rows.saturating_sub(tail_data_rows);
                    if data_rows_drawn == 0 {
                        return Err(PdfError::TableOverflow {
                            rendered: current_table.row_count() - tail.row_count(),
                            dropped: tail.row_count(),
                            bottom_y,
                        });
                    }

                    self.add_page(Page::new(page_width, page_height));
                    current_page_idx = self.page_count() - 1;

                    if repeat_headers {
                        tail.prepend_headers_from(table);
                    }
                    tail.set_position(x, next_page_y);
                    current_table = tail;
                }
            }
        }
    }
}

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

    // ==================== TableStyle Tests ====================

    #[test]
    fn test_table_style_minimal() {
        let style = TableStyle::minimal();
        assert_eq!(style.header_background, None);
        assert_eq!(style.header_text_color, None);
        assert_eq!(style.font_size, 10.0);
    }

    #[test]
    fn test_table_style_simple() {
        let style = TableStyle::simple();
        assert_eq!(style.header_background, None);
        assert_eq!(style.header_text_color, None);
        assert_eq!(style.font_size, 10.0);
    }

    #[test]
    fn test_table_style_professional() {
        let style = TableStyle::professional();
        assert!(style.header_background.is_some());
        assert!(style.header_text_color.is_some());
        assert_eq!(style.font_size, 10.0);

        // Verify dark header background
        if let Some(bg) = style.header_background {
            assert!(bg.r() < 0.2, "Professional header should be dark");
        }

        // Verify white text
        if let Some(text) = style.header_text_color {
            assert_eq!(text, Color::white());
        }
    }

    #[test]
    fn test_table_style_colorful() {
        let style = TableStyle::colorful();
        assert!(style.header_background.is_some());
        assert!(style.header_text_color.is_some());
        assert_eq!(style.font_size, 10.0);

        // Verify blue-ish header background (0.2, 0.4, 0.8)
        if let Some(bg) = style.header_background {
            assert!(bg.b() > bg.r(), "Colorful header should be blue-ish");
            assert!(bg.b() > bg.g(), "Colorful header should be blue-ish");
        }

        // Verify white text
        if let Some(text) = style.header_text_color {
            assert_eq!(text, Color::white());
        }
    }

    #[test]
    fn test_table_style_clone() {
        let original = TableStyle::professional();
        let cloned = original.clone();

        assert_eq!(cloned.header_background, original.header_background);
        assert_eq!(cloned.header_text_color, original.header_text_color);
        assert_eq!(cloned.font_size, original.font_size);
    }

    #[test]
    fn test_table_style_debug() {
        let style = TableStyle::minimal();
        let debug_str = format!("{:?}", style);
        assert!(debug_str.contains("TableStyle"));
    }

    #[test]
    fn test_table_style_mutability() {
        let mut style = TableStyle::minimal();

        style.header_background = Some(Color::red());
        style.header_text_color = Some(Color::blue());
        style.font_size = 14.0;

        assert_eq!(style.header_background, Some(Color::red()));
        assert_eq!(style.header_text_color, Some(Color::blue()));
        assert_eq!(style.font_size, 14.0);
    }

    #[test]
    fn test_table_styles() {
        let minimal = TableStyle::minimal();
        assert_eq!(minimal.font_size, 10.0);

        let simple = TableStyle::simple();
        assert_eq!(simple.font_size, 10.0);

        let professional = TableStyle::professional();
        assert!(professional.header_background.is_some());

        let colorful = TableStyle::colorful();
        assert!(colorful.header_background.is_some());
    }

    // ==================== Page Integration Tests ====================

    #[test]
    fn test_page_tables_trait() {
        let mut page = Page::a4();

        // Test quick table
        let data = vec![
            vec!["Name".to_string(), "Age".to_string()],
            vec!["John".to_string(), "30".to_string()],
        ];

        let result = page.add_quick_table(data, 50.0, 700.0, 400.0, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_quick_table_with_options() {
        let mut page = Page::a4();

        let data = vec![
            vec!["A".to_string(), "B".to_string()],
            vec!["C".to_string(), "D".to_string()],
        ];

        let options = TableOptions {
            font_size: 12.0,
            ..Default::default()
        };

        let result = page.add_quick_table(data, 50.0, 700.0, 400.0, Some(options));
        assert!(result.is_ok());
    }

    #[test]
    fn test_styled_table() {
        let mut page = Page::a4();

        let headers = vec!["Column 1".to_string(), "Column 2".to_string()];
        let data = vec![
            vec!["Data 1".to_string(), "Data 2".to_string()],
            vec!["Data 3".to_string(), "Data 4".to_string()],
        ];

        let result = page.add_styled_table(
            headers,
            data,
            50.0,
            700.0,
            500.0,
            TableStyle::professional(),
        );

        assert!(result.is_ok());
    }

    #[test]
    fn test_styled_table_minimal() {
        let mut page = Page::a4();

        let headers = vec!["H1".to_string(), "H2".to_string()];
        let data = vec![vec!["V1".to_string(), "V2".to_string()]];

        let result =
            page.add_styled_table(headers, data, 50.0, 700.0, 400.0, TableStyle::minimal());
        assert!(result.is_ok());
    }

    #[test]
    fn test_styled_table_colorful() {
        let mut page = Page::a4();

        let headers = vec!["Header".to_string()];
        let data = vec![vec!["Value".to_string()]];

        let result =
            page.add_styled_table(headers, data, 50.0, 700.0, 300.0, TableStyle::colorful());
        assert!(result.is_ok());
    }

    #[test]
    fn test_styled_table_empty_headers() {
        let mut page = Page::a4();

        let headers: Vec<String> = vec![];
        let data = vec![vec!["Data".to_string()]];

        // Empty headers should return Ok (early return)
        let result = page.add_styled_table(headers, data, 50.0, 700.0, 400.0, TableStyle::simple());
        assert!(result.is_ok());
    }

    #[test]
    fn test_styled_table_empty_data() {
        let mut page = Page::a4();

        let headers = vec!["H1".to_string(), "H2".to_string()];
        let data: Vec<Vec<String>> = vec![];

        // Headers only, no data rows
        let result = page.add_styled_table(
            headers,
            data,
            50.0,
            700.0,
            400.0,
            TableStyle::professional(),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_empty_table() {
        let mut page = Page::a4();

        let data: Vec<Vec<String>> = vec![];
        let result = page.add_quick_table(data, 50.0, 700.0, 400.0, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_single_cell_table() {
        let mut page = Page::a4();

        let data = vec![vec!["Single".to_string()]];
        let result = page.add_quick_table(data, 50.0, 700.0, 200.0, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_single_row_table() {
        let mut page = Page::a4();

        let data = vec![vec![
            "A".to_string(),
            "B".to_string(),
            "C".to_string(),
            "D".to_string(),
        ]];
        let result = page.add_quick_table(data, 50.0, 700.0, 500.0, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_single_column_table() {
        let mut page = Page::a4();

        let data = vec![
            vec!["Row 1".to_string()],
            vec!["Row 2".to_string()],
            vec!["Row 3".to_string()],
        ];
        let result = page.add_quick_table(data, 50.0, 700.0, 150.0, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_many_rows_table() {
        let mut page = Page::a4();

        let data: Vec<Vec<String>> = (0..50)
            .map(|i| vec![format!("Row {}", i), format!("Value {}", i)])
            .collect();

        let result = page.add_quick_table(data, 50.0, 700.0, 400.0, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_many_columns_table() {
        let mut page = Page::a4();

        let headers: Vec<String> = (0..10).map(|i| format!("Col {}", i)).collect();
        let data = vec![(0..10).map(|i| format!("V{}", i)).collect()];

        let result = page.add_styled_table(headers, data, 50.0, 700.0, 550.0, TableStyle::simple());
        assert!(result.is_ok());
    }

    #[test]
    fn test_table_at_different_positions() {
        let mut page = Page::a4();

        let data = vec![vec!["Test".to_string()]];

        // Top-left
        let result = page.add_quick_table(data.clone(), 0.0, 800.0, 100.0, None);
        assert!(result.is_ok());

        // Center-ish
        let result = page.add_quick_table(data.clone(), 200.0, 400.0, 100.0, None);
        assert!(result.is_ok());

        // Bottom-right area
        let result = page.add_quick_table(data, 400.0, 100.0, 100.0, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_styled_table_with_only_header_background() {
        let mut page = Page::a4();

        let mut style = TableStyle::minimal();
        style.header_background = Some(Color::green());
        // header_text_color remains None

        let headers = vec!["Test".to_string()];
        let data = vec![vec!["Data".to_string()]];

        let result = page.add_styled_table(headers, data, 50.0, 700.0, 200.0, style);
        assert!(result.is_ok());
    }

    #[test]
    fn test_styled_table_with_only_header_text_color() {
        let mut page = Page::a4();

        let mut style = TableStyle::minimal();
        style.header_text_color = Some(Color::red());
        // header_background remains None

        let headers = vec!["Test".to_string()];
        let data = vec![vec!["Data".to_string()]];

        let result = page.add_styled_table(headers, data, 50.0, 700.0, 200.0, style);
        assert!(result.is_ok());
    }

    #[test]
    fn test_styled_table_custom_font_size() {
        let mut page = Page::a4();

        let mut style = TableStyle::professional();
        style.font_size = 16.0;

        let headers = vec!["Big".to_string(), "Text".to_string()];
        let data = vec![vec!["Large".to_string(), "Font".to_string()]];

        let result = page.add_styled_table(headers, data, 50.0, 700.0, 300.0, style);
        assert!(result.is_ok());
    }

    #[test]
    fn test_all_styles_integration() {
        let mut page = Page::a4();

        let headers = vec!["A".to_string(), "B".to_string()];
        let data = vec![vec!["1".to_string(), "2".to_string()]];

        let styles = vec![
            TableStyle::minimal(),
            TableStyle::simple(),
            TableStyle::professional(),
            TableStyle::colorful(),
        ];

        for (i, style) in styles.into_iter().enumerate() {
            let y = 700.0 - (i as f64 * 100.0);
            let result =
                page.add_styled_table(headers.clone(), data.clone(), 50.0, y, 200.0, style);
            assert!(result.is_ok(), "Failed for style index {}", i);
        }
    }
}