oxidize-pdf 2.5.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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
//! Table renderer for converting advanced tables to PDF content

use super::cell_style::{BorderConfiguration, BorderStyle, CellAlignment, CellStyle};
use super::header_builder::HeaderBuilder;
use super::table_builder::{AdvancedTable, CellData, RowData};
use crate::error::PdfError;
use crate::graphics::Color;
use crate::page::Page;
use crate::text::{measure_text, Font};

/// Renderer for advanced tables
pub struct TableRenderer {
    /// Default row height when not specified
    pub default_row_height: f64,
    /// Default header height
    pub default_header_height: f64,
    /// Whether to auto-calculate cell heights based on content
    pub auto_height: bool,
}

impl TableRenderer {
    /// Create a new table renderer
    pub fn new() -> Self {
        Self {
            default_row_height: 25.0,
            default_header_height: 30.0,
            auto_height: true,
        }
    }

    /// Calculate the total height needed to render a table
    ///
    /// This is essential for intelligent positioning and layout management.
    /// Returns the height in points from bottom to top of the rendered table.
    pub fn calculate_table_height(&self, table: &AdvancedTable) -> f64 {
        let mut total_height = 0.0;

        // Calculate header height
        if table.show_header {
            if let Some(header) = &table.header {
                // For complex headers, calculate based on levels and row spans
                total_height += header.calculate_height();
            } else if !table.columns.is_empty() {
                // Simple header from column definitions
                total_height += self.default_header_height;
            }
        }

        // Calculate rows height, tracking rows absorbed by rowspan.
        // When auto_height is enabled, expand rows to fit multiline content
        // (mirrors the same logic used in render_rows).
        let mut rows_to_skip: usize = 0;
        for (row_idx, row) in table.rows.iter().enumerate() {
            if rows_to_skip > 0 {
                rows_to_skip -= 1;
                continue;
            }

            let base_height = row.min_height.unwrap_or(self.default_row_height);
            let row_height = if self.auto_height {
                let content_height = self.calculate_content_row_height(table, row, row_idx);
                base_height.max(content_height)
            } else {
                base_height
            };

            let max_rowspan = row.cells.iter().map(|cell| cell.rowspan).max().unwrap_or(1);
            if max_rowspan > 1 {
                total_height += row_height * max_rowspan as f64;
                rows_to_skip = max_rowspan - 1;
            } else {
                total_height += row_height;
            }
        }

        // Add small buffer for table borders
        if table.table_border {
            total_height += 2.0; // Top and bottom borders
        }

        total_height
    }

    /// Render a table to a PDF page
    pub fn render_table(
        &self,
        page: &mut Page,
        table: &AdvancedTable,
        x: f64,
        y: f64,
    ) -> Result<f64, PdfError> {
        // Validate table structure
        table
            .validate()
            .map_err(|e| PdfError::InvalidOperation(e.to_string()))?;

        let mut current_y = y;

        // Render header if present
        if table.show_header {
            if let Some(header) = &table.header {
                current_y = self.render_header(page, table, header, x, current_y)?;
            } else if !table.columns.is_empty() {
                // Render simple header from column definitions
                current_y = self.render_simple_header(page, table, x, current_y)?;
            }
        }

        // Render table rows
        current_y = self.render_rows(page, table, x, current_y)?;

        // Render table border if enabled
        if table.table_border {
            self.render_table_border(page, table, x, y, current_y)?;
        }

        Ok(current_y)
    }

    /// Render table headers
    fn render_header(
        &self,
        page: &mut Page,
        table: &AdvancedTable,
        header: &HeaderBuilder,
        x: f64,
        start_y: f64,
    ) -> Result<f64, PdfError> {
        let mut current_y = start_y;
        let column_positions = self.calculate_column_positions(table, x);

        for level in header.levels.iter() {
            let row_height = self.default_header_height;

            for cell in level {
                let cell_x = column_positions[cell.start_col];
                let cell_width = self.calculate_span_width(table, cell.start_col, cell.colspan);
                let cell_height = row_height * cell.rowspan as f64;

                let style = cell.style.as_ref().unwrap_or(&table.header_style);

                self.render_cell(
                    page,
                    &cell.text,
                    cell_x,
                    current_y - cell_height,
                    cell_width,
                    cell_height,
                    style,
                )?;
            }

            current_y -= row_height;
        }

        Ok(current_y)
    }

    /// Render simple header from column definitions
    fn render_simple_header(
        &self,
        page: &mut Page,
        table: &AdvancedTable,
        x: f64,
        start_y: f64,
    ) -> Result<f64, PdfError> {
        let column_positions = self.calculate_column_positions(table, x);
        let header_height = self.default_header_height;

        for (col_idx, column) in table.columns.iter().enumerate() {
            let cell_x = column_positions[col_idx];
            let cell_width = column.width;

            self.render_cell(
                page,
                &column.header,
                cell_x,
                start_y - header_height,
                cell_width,
                header_height,
                &table.header_style,
            )?;
        }

        Ok(start_y - header_height)
    }

    /// Calculate the minimum height needed for a row's content
    fn calculate_content_row_height(
        &self,
        table: &AdvancedTable,
        row: &RowData,
        row_idx: usize,
    ) -> f64 {
        let mut max_height = self.default_row_height;

        let mut actual_col = 0usize;
        for cell in row.cells.iter() {
            let style = self.resolve_cell_style(table, cell, row_idx, actual_col);
            let font = style.font.clone().unwrap_or(Font::Helvetica);
            let font_size = style.font_size.unwrap_or(12.0);
            // Sum column widths for colspan
            let col_width: f64 = (actual_col..actual_col + cell.colspan)
                .filter_map(|c| table.columns.get(c).map(|col| col.width))
                .sum();
            let available_width = col_width - style.padding.left - style.padding.right;

            if available_width > 0.0 && style.text_wrap {
                let lines =
                    self.wrap_text_to_lines(&cell.content, available_width, &font, font_size);
                let line_height = font_size * 1.2;
                let needed =
                    (lines.len() as f64 * line_height) + style.padding.top + style.padding.bottom;
                if needed > max_height {
                    max_height = needed;
                }
            }

            actual_col += cell.colspan;
        }

        max_height
    }

    /// Render table data rows
    fn render_rows(
        &self,
        page: &mut Page,
        table: &AdvancedTable,
        x: f64,
        start_y: f64,
    ) -> Result<f64, PdfError> {
        let mut current_y = start_y;
        let column_positions = self.calculate_column_positions(table, x);
        let num_cols = table.columns.len();
        // Track the last row index each column is occupied through (exclusive upper bound).
        // rowspan_end[c] > row_idx means column c is occupied by a rowspan from a previous row.
        let mut rowspan_end: Vec<usize> = vec![0; num_cols];

        for (row_idx, row) in table.rows.iter().enumerate() {
            // Calculate row height: explicit min_height, or auto-fit content
            let base_height = row.min_height.unwrap_or(self.default_row_height);
            let row_height = if self.auto_height {
                let content_height = self.calculate_content_row_height(table, row, row_idx);
                base_height.max(content_height)
            } else {
                base_height
            };

            // Track actual column position (accounts for colspan and rowspan)
            let mut actual_col = 0usize;
            for cell in row.cells.iter() {
                // Skip columns occupied by rowspan from previous rows
                while actual_col < num_cols && rowspan_end[actual_col] > row_idx {
                    actual_col += 1;
                }

                if actual_col >= column_positions.len() {
                    break;
                }

                let cell_x = column_positions[actual_col];
                let cell_width = self.calculate_span_width(table, actual_col, cell.colspan);
                let cell_height = row_height * cell.rowspan as f64;

                let style = self.resolve_cell_style(table, cell, row_idx, actual_col);

                self.render_cell(
                    page,
                    &cell.content,
                    cell_x,
                    current_y - cell_height,
                    cell_width,
                    cell_height,
                    &style,
                )?;

                // Record rowspan: this cell occupies columns through row_idx + rowspan - 1
                if cell.rowspan > 1 {
                    for c in actual_col..(actual_col + cell.colspan).min(num_cols) {
                        rowspan_end[c] = row_idx + cell.rowspan;
                    }
                }

                actual_col += cell.colspan;
            }

            current_y -= row_height;
        }

        Ok(current_y)
    }

    /// Render an individual cell
    #[allow(clippy::too_many_arguments)]
    fn render_cell(
        &self,
        page: &mut Page,
        content: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        style: &CellStyle,
    ) -> Result<(), PdfError> {
        // Draw background if specified
        if let Some(bg_color) = style.background_color {
            page.graphics()
                .save_state()
                .set_fill_color(bg_color)
                .rectangle(x, y, width, height)
                .fill()
                .restore_state();
        }

        // Draw borders
        self.render_cell_borders(page, x, y, width, height, &style.border)?;

        // Draw text content
        if !content.is_empty() {
            self.render_cell_text(page, content, x, y, width, height, style)?;
        }

        Ok(())
    }

    /// Render cell borders
    fn render_cell_borders(
        &self,
        page: &mut Page,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        border_config: &BorderConfiguration,
    ) -> Result<(), PdfError> {
        let graphics = page.graphics();

        // Top border
        if border_config.top.style != BorderStyle::None {
            graphics
                .save_state()
                .set_stroke_color(border_config.top.color)
                .set_line_width(border_config.top.width);

            self.apply_line_style(graphics, border_config.top.style);

            graphics
                .move_to(x, y + height)
                .line_to(x + width, y + height)
                .stroke()
                .restore_state();
        }

        // Bottom border
        if border_config.bottom.style != BorderStyle::None {
            graphics
                .save_state()
                .set_stroke_color(border_config.bottom.color)
                .set_line_width(border_config.bottom.width);

            self.apply_line_style(graphics, border_config.bottom.style);

            graphics
                .move_to(x, y)
                .line_to(x + width, y)
                .stroke()
                .restore_state();
        }

        // Left border
        if border_config.left.style != BorderStyle::None {
            graphics
                .save_state()
                .set_stroke_color(border_config.left.color)
                .set_line_width(border_config.left.width);

            self.apply_line_style(graphics, border_config.left.style);

            graphics
                .move_to(x, y)
                .line_to(x, y + height)
                .stroke()
                .restore_state();
        }

        // Right border
        if border_config.right.style != BorderStyle::None {
            graphics
                .save_state()
                .set_stroke_color(border_config.right.color)
                .set_line_width(border_config.right.width);

            self.apply_line_style(graphics, border_config.right.style);

            graphics
                .move_to(x + width, y)
                .line_to(x + width, y + height)
                .stroke()
                .restore_state();
        }

        Ok(())
    }

    /// Apply line style for borders
    fn apply_line_style(
        &self,
        _graphics: &mut crate::graphics::GraphicsContext,
        _style: BorderStyle,
    ) {
        // TODO: Implement line styles when GraphicsContext supports dash patterns
        // For now, all borders will be solid
    }

    /// Truncate text to fit within a specified width, adding ellipsis if needed
    fn truncate_text_to_width(
        &self,
        text: &str,
        max_width: f64,
        font: &Font,
        font_size: f64,
    ) -> String {
        // If text already fits, return as-is
        let full_width = measure_text(text, font, font_size);
        if full_width <= max_width {
            return text.to_string();
        }

        // If even ellipsis doesn't fit, return empty string
        let ellipsis = "...";
        let ellipsis_width = measure_text(ellipsis, font, font_size);
        if ellipsis_width > max_width {
            return String::new();
        }

        // If exactly ellipsis width, return ellipsis
        if ellipsis_width == max_width {
            return ellipsis.to_string();
        }

        // Linear scan: iterate character by character until width is exceeded.
        // For typical cell text (<100 chars) this is simpler and avoids allocating a Vec<char>.
        let available_width = max_width - ellipsis_width;
        let mut last_fit_end = 0usize;
        let mut width_so_far = 0.0f64;

        for (byte_pos, ch) in text.char_indices() {
            let ch_len = ch.len_utf8();
            let ch_str = &text[byte_pos..byte_pos + ch_len];
            let ch_width = measure_text(ch_str, font, font_size);
            if width_so_far + ch_width > available_width {
                break;
            }
            width_so_far += ch_width;
            last_fit_end = byte_pos + ch_len;
        }

        if last_fit_end == 0 {
            ellipsis.to_string()
        } else {
            format!("{}{}", &text[..last_fit_end], ellipsis)
        }
    }

    /// Wrap text into multiple lines that fit within the given width.
    ///
    /// Uses incremental width tracking to avoid remeasuring the full current line on
    /// every word — a significant saving in the hot path for tables with many cells.
    fn wrap_text_to_lines(
        &self,
        text: &str,
        max_width: f64,
        font: &Font,
        font_size: f64,
    ) -> Vec<String> {
        let mut lines = Vec::new();

        // Split by existing newlines first
        for paragraph in text.split('\n') {
            if paragraph.is_empty() {
                lines.push(String::new());
                continue;
            }

            // If paragraph fits, add it directly (single measure check)
            let paragraph_width = measure_text(paragraph, font, font_size);
            if paragraph_width <= max_width {
                lines.push(paragraph.to_string());
                continue;
            }

            // Word-wrap the paragraph
            let words: Vec<&str> = paragraph.split_whitespace().collect();
            if words.is_empty() {
                continue;
            }

            let mut current_line = String::new();
            let mut current_line_width = 0.0f64;
            let space_width = measure_text(" ", font, font_size);

            for word in words {
                let word_width = measure_text(word, font, font_size);

                if current_line.is_empty() {
                    // First word on the line
                    if word_width <= max_width {
                        current_line = word.to_string();
                        current_line_width = word_width;
                    } else {
                        // Word is too long — break it character by character
                        let chars: Vec<char> = word.chars().collect();
                        let mut char_line = String::new();
                        let mut char_line_width = 0.0f64;
                        for c in chars {
                            let char_width = measure_text(&c.to_string(), font, font_size);
                            if char_line_width + char_width <= max_width {
                                char_line.push(c);
                                char_line_width += char_width;
                            } else {
                                if !char_line.is_empty() {
                                    lines.push(char_line);
                                }
                                char_line = c.to_string();
                                char_line_width = char_width;
                            }
                        }
                        current_line = char_line;
                        current_line_width = char_line_width;
                    }
                } else {
                    // Test adding word to current line using incremental width
                    let test_width = current_line_width + space_width + word_width;

                    if test_width <= max_width {
                        current_line.push(' ');
                        current_line.push_str(word);
                        current_line_width = test_width;
                    } else {
                        // Start new line
                        lines.push(current_line);
                        if word_width <= max_width {
                            current_line = word.to_string();
                            current_line_width = word_width;
                        } else {
                            // Word is too long — break it character by character
                            let chars: Vec<char> = word.chars().collect();
                            let mut char_line = String::new();
                            let mut char_line_width = 0.0f64;
                            for c in chars {
                                let char_width = measure_text(&c.to_string(), font, font_size);
                                if char_line_width + char_width <= max_width {
                                    char_line.push(c);
                                    char_line_width += char_width;
                                } else {
                                    if !char_line.is_empty() {
                                        lines.push(char_line);
                                    }
                                    char_line = c.to_string();
                                    char_line_width = char_width;
                                }
                            }
                            current_line = char_line;
                            current_line_width = char_line_width;
                        }
                    }
                }
            }

            // Add remaining text
            if !current_line.is_empty() {
                lines.push(current_line);
            }
        }

        if lines.is_empty() {
            lines.push(String::new());
        }

        lines
    }

    /// Render text within a cell
    #[allow(clippy::too_many_arguments)]
    fn render_cell_text(
        &self,
        page: &mut Page,
        content: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        style: &CellStyle,
    ) -> Result<(), PdfError> {
        let font = style.font.clone().unwrap_or(Font::Helvetica);
        let font_size = style.font_size.unwrap_or(12.0);
        let text_color = style.text_color.unwrap_or(Color::black());

        // Calculate available width for text (considering padding)
        let available_width = width - style.padding.left - style.padding.right;

        if available_width <= 0.0 {
            return Ok(());
        }

        // Check if text wrapping is enabled
        if style.text_wrap {
            // Wrap text into multiple lines
            let lines = self.wrap_text_to_lines(content, available_width, &font, font_size);

            if lines.is_empty() || (lines.len() == 1 && lines[0].is_empty()) {
                return Ok(());
            }

            // Calculate line height (typically 1.2x font size)
            let line_height = font_size * 1.2;
            let total_text_height = lines.len() as f64 * line_height;

            // Calculate available height (considering padding)
            let available_height = height - style.padding.top - style.padding.bottom;

            // Calculate starting Y position (top of text block, vertically centered)
            // In PDF coordinate system, Y increases upward
            let text_block_top =
                y + height - style.padding.top - (available_height - total_text_height) / 2.0;

            // Render each line
            for (line_idx, line) in lines.iter().enumerate() {
                if line.is_empty() {
                    continue;
                }

                // Calculate X position based on alignment
                let text_x = match style.alignment {
                    CellAlignment::Left => x + style.padding.left,
                    CellAlignment::Center => {
                        let line_width = measure_text(line, &font, font_size);
                        x + style.padding.left + (available_width - line_width) / 2.0
                    }
                    CellAlignment::Right => {
                        let line_width = measure_text(line, &font, font_size);
                        x + width - style.padding.right - line_width
                    }
                    CellAlignment::Justify => x + style.padding.left,
                };

                // Y position for this line (descending from top)
                let text_y = text_block_top - (line_idx as f64 + 0.8) * line_height;

                // Only render if within cell bounds
                if text_y >= y + style.padding.bottom {
                    page.text()
                        .set_font(font.clone(), font_size)
                        .set_fill_color(text_color)
                        .at(text_x, text_y)
                        .write(line)?;
                }
            }
        } else {
            // Original truncation behavior
            let display_text =
                self.truncate_text_to_width(content, available_width, &font, font_size);

            // Calculate text position based on alignment and padding
            let text_x = match style.alignment {
                CellAlignment::Left => x + style.padding.left,
                CellAlignment::Center => {
                    // For center alignment, we need to calculate based on actual text width
                    let text_width = measure_text(&display_text, &font, font_size);
                    x + style.padding.left + (available_width - text_width) / 2.0
                }
                CellAlignment::Right => {
                    let text_width = measure_text(&display_text, &font, font_size);
                    x + width - style.padding.right - text_width
                }
                CellAlignment::Justify => x + style.padding.left,
            };

            // Vertically center with padding applied
            let text_y = style
                .padding
                .pad_vertically(&page.coordinate_system(), y + height / 2.0);

            // Only render text if we have something to display
            if !display_text.is_empty() {
                let text_obj = page
                    .text()
                    .set_font(font, font_size)
                    .set_fill_color(text_color);

                text_obj.at(text_x, text_y).write(&display_text)?;
            }
        }

        Ok(())
    }

    /// Calculate column positions based on widths
    fn calculate_column_positions(&self, table: &AdvancedTable, start_x: f64) -> Vec<f64> {
        let mut positions = Vec::new();
        let mut current_x = start_x;

        for column in &table.columns {
            positions.push(current_x);
            current_x += column.width + table.cell_spacing;
        }

        positions
    }

    /// Calculate width for a cell that spans multiple columns
    fn calculate_span_width(&self, table: &AdvancedTable, start_col: usize, colspan: usize) -> f64 {
        let mut total_width = 0.0;

        for i in 0..colspan {
            if let Some(column) = table.columns.get(start_col + i) {
                total_width += column.width;
                if i > 0 {
                    total_width += table.cell_spacing;
                }
            }
        }

        total_width
    }

    /// Resolve the effective style for a cell
    fn resolve_cell_style(
        &self,
        table: &AdvancedTable,
        cell: &CellData,
        row_idx: usize,
        col_idx: usize,
    ) -> CellStyle {
        // Priority: cell style > specific cell style > row style > column style > table default

        if let Some(cell_style) = &cell.style {
            return cell_style.clone();
        }

        table.get_cell_style(row_idx, col_idx)
    }

    /// Render table border
    fn render_table_border(
        &self,
        page: &mut Page,
        table: &AdvancedTable,
        x: f64,
        start_y: f64,
        end_y: f64,
    ) -> Result<(), PdfError> {
        let total_width = table.calculate_width();
        let height = start_y - end_y;

        page.graphics()
            .save_state()
            .set_stroke_color(Color::black())
            .set_line_width(1.0)
            .rectangle(x, end_y, total_width, height)
            .stroke()
            .restore_state();

        Ok(())
    }
}

impl Default for TableRenderer {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_truncate_text_to_width_no_truncation_needed() {
        let renderer = TableRenderer::new();
        let text = "Short";
        let max_width = 100.0;
        let font = Font::Helvetica;
        let font_size = 12.0;

        let result = renderer.truncate_text_to_width(text, max_width, &font, font_size);
        assert_eq!(result, "Short");
    }

    #[test]
    fn test_truncate_text_to_width_with_truncation() {
        let renderer = TableRenderer::new();
        let text = "This is a very long text that should be truncated";
        let max_width = 50.0; // Very narrow width
        let font = Font::Helvetica;
        let font_size = 12.0;

        let result = renderer.truncate_text_to_width(text, max_width, &font, font_size);
        assert!(result.ends_with("..."));
        assert!(result.len() < text.len());

        // Verify the truncated text fits within the width
        let truncated_width = measure_text(&result, &font, font_size);
        assert!(truncated_width <= max_width);
    }

    #[test]
    fn test_truncate_text_to_width_empty_when_too_narrow() {
        let renderer = TableRenderer::new();
        let text = "Any text";
        let max_width = 5.0; // Too narrow even for ellipsis
        let font = Font::Helvetica;
        let font_size = 12.0;

        let result = renderer.truncate_text_to_width(text, max_width, &font, font_size);
        assert_eq!(result, "");
    }

    #[test]
    fn test_truncate_text_to_width_exactly_ellipsis_width() {
        let renderer = TableRenderer::new();
        let text = "Some text";
        let font = Font::Helvetica;
        let font_size = 12.0;

        // Calculate width that exactly fits ellipsis
        let ellipsis_width = measure_text("...", &font, font_size);

        let result = renderer.truncate_text_to_width(text, ellipsis_width, &font, font_size);
        assert_eq!(result, "...");
    }

    #[test]
    fn test_truncate_text_to_width_single_character() {
        let renderer = TableRenderer::new();
        let text = "A";
        let max_width = 50.0;
        let font = Font::Helvetica;
        let font_size = 12.0;

        let result = renderer.truncate_text_to_width(text, max_width, &font, font_size);
        assert_eq!(result, "A");
    }

    #[test]
    fn test_truncate_text_to_width_different_fonts() {
        let renderer = TableRenderer::new();
        let text = "This text will be truncated";
        let max_width = 60.0;
        let font_size = 12.0;

        // Test with different fonts
        let helvetica_result =
            renderer.truncate_text_to_width(text, max_width, &Font::Helvetica, font_size);
        let courier_result =
            renderer.truncate_text_to_width(text, max_width, &Font::Courier, font_size);
        let times_result =
            renderer.truncate_text_to_width(text, max_width, &Font::TimesRoman, font_size);

        // All should be truncated and fit within width
        for result in [&helvetica_result, &courier_result, &times_result] {
            assert!(result.ends_with("..."));
            assert!(result.len() < text.len());
        }

        // Courier (monospace) might have different truncation point
        // All results should be valid and within width limits
        assert!(!helvetica_result.is_empty());
        assert!(!courier_result.is_empty());
        assert!(!times_result.is_empty());
    }

    #[test]
    fn test_truncate_text_to_width_empty_input() {
        let renderer = TableRenderer::new();
        let text = "";
        let max_width = 100.0;
        let font = Font::Helvetica;
        let font_size = 12.0;

        let result = renderer.truncate_text_to_width(text, max_width, &font, font_size);
        assert_eq!(result, "");
    }

    #[test]
    fn test_truncate_text_to_width_unicode_characters() {
        let renderer = TableRenderer::new();
        let text = "Héllö Wørld with ümlauts and émojis 🚀🎉";
        let max_width = 80.0;
        let font = Font::Helvetica;
        let font_size = 12.0;

        let result = renderer.truncate_text_to_width(text, max_width, &font, font_size);

        // Should handle unicode properly
        if result != text {
            assert!(result.ends_with("..."));
        }

        // Verify width constraint
        let result_width = measure_text(&result, &font, font_size);
        assert!(result_width <= max_width);
    }

    // ================== truncate_text_to_width linear scan tests ==================

    #[test]
    fn test_truncate_linear_short_text_fits() {
        let renderer = TableRenderer::new();
        let text = "Hi";
        let font = Font::Helvetica;
        let font_size = 12.0;
        // A wide width means text fits unchanged
        let result = renderer.truncate_text_to_width(text, 500.0, &font, font_size);
        assert_eq!(result, "Hi");
    }

    #[test]
    fn test_truncate_linear_overflow_adds_ellipsis() {
        let renderer = TableRenderer::new();
        let text = "This is a long sentence that will not fit";
        let font = Font::Helvetica;
        let font_size = 12.0;
        let result = renderer.truncate_text_to_width(text, 40.0, &font, font_size);
        assert!(
            result.ends_with("..."),
            "Expected ellipsis suffix, got: {result}"
        );
        assert!(result.len() < text.len());
        let result_width = measure_text(&result, &font, font_size);
        assert!(result_width <= 40.0, "Truncated text exceeds max_width");
    }

    #[test]
    fn test_truncate_linear_unicode() {
        let renderer = TableRenderer::new();
        // Multi-byte UTF-8 characters: each Japanese kanji is 3 bytes
        let text = "日本語テスト文字列";
        let font = Font::Helvetica;
        let font_size = 12.0;
        let result = renderer.truncate_text_to_width(text, 50.0, &font, font_size);
        // Result must be valid UTF-8 (no partial char splits)
        assert!(std::str::from_utf8(result.as_bytes()).is_ok());
        if result != text {
            assert!(
                result.ends_with("..."),
                "Truncated unicode should end with ellipsis"
            );
        }
        let result_width = measure_text(&result, &font, font_size);
        assert!(result_width <= 50.0);
    }

    // ================== wrap_text_to_lines tests (Issue #131) ==================

    #[test]
    fn test_wrap_text_to_lines_no_wrap_needed() {
        let renderer = TableRenderer::new();
        let text = "Short text";
        let max_width = 200.0;
        let font = Font::Helvetica;
        let font_size = 12.0;

        let lines = renderer.wrap_text_to_lines(text, max_width, &font, font_size);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0], "Short text");
    }

    #[test]
    fn test_wrap_text_to_lines_simple_wrap() {
        let renderer = TableRenderer::new();
        let text = "This is a longer text that should wrap to multiple lines";
        let max_width = 80.0; // Narrow width to force wrapping
        let font = Font::Helvetica;
        let font_size = 12.0;

        let lines = renderer.wrap_text_to_lines(text, max_width, &font, font_size);
        assert!(lines.len() > 1, "Text should wrap to multiple lines");

        // Verify all lines fit within max_width
        for line in &lines {
            let line_width = measure_text(line, &font, font_size);
            assert!(
                line_width <= max_width + 1.0, // Small tolerance for floating point
                "Line '{}' exceeds max_width (width: {}, max: {})",
                line,
                line_width,
                max_width
            );
        }
    }

    #[test]
    fn test_wrap_text_to_lines_preserves_newlines() {
        let renderer = TableRenderer::new();
        let text = "Line one\nLine two\nLine three";
        let max_width = 200.0; // Wide enough for any single line
        let font = Font::Helvetica;
        let font_size = 12.0;

        let lines = renderer.wrap_text_to_lines(text, max_width, &font, font_size);
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0], "Line one");
        assert_eq!(lines[1], "Line two");
        assert_eq!(lines[2], "Line three");
    }

    #[test]
    fn test_wrap_text_to_lines_empty_input() {
        let renderer = TableRenderer::new();
        let text = "";
        let max_width = 100.0;
        let font = Font::Helvetica;
        let font_size = 12.0;

        let lines = renderer.wrap_text_to_lines(text, max_width, &font, font_size);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0], "");
    }

    #[test]
    fn test_wrap_text_to_lines_single_word_too_long() {
        let renderer = TableRenderer::new();
        let text = "Supercalifragilisticexpialidocious";
        let max_width = 50.0; // Too narrow for the word
        let font = Font::Helvetica;
        let font_size = 12.0;

        let lines = renderer.wrap_text_to_lines(text, max_width, &font, font_size);
        // Word should be broken across lines
        assert!(lines.len() >= 1, "Should produce at least one line");

        // When we join all lines, we should get the original word
        let joined: String = lines.join("");
        assert_eq!(joined, text);
    }

    #[test]
    fn test_wrap_text_to_lines_multiple_spaces() {
        let renderer = TableRenderer::new();
        let text = "Word   with   spaces";
        let max_width = 200.0;
        let font = Font::Helvetica;
        let font_size = 12.0;

        let lines = renderer.wrap_text_to_lines(text, max_width, &font, font_size);
        assert_eq!(lines.len(), 1);
        // The implementation treats each space-separated segment as a word
        assert!(!lines[0].is_empty());
    }

    #[test]
    fn test_wrap_text_to_lines_unicode() {
        let renderer = TableRenderer::new();
        let text = "日本語テキスト with English words";
        let max_width = 100.0;
        let font = Font::Helvetica;
        let font_size = 12.0;

        let lines = renderer.wrap_text_to_lines(text, max_width, &font, font_size);
        // Should handle unicode without panic
        assert!(!lines.is_empty());
    }
}