pivot-pdf 0.6.0

A low-overhead PDF generation library for reports, invoices, and documents
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
use crate::document::format_coord;
use crate::fonts::{BuiltinFont, FontRef};
use crate::graphics::Color;
use crate::textflow::{
    break_word, line_height_for, measure_word, FitResult, Rect, TextStyle, UsedFonts, WordBreak,
};
use crate::truetype::TrueTypeFont;
use crate::writer::escape_pdf_string;

// -------------------------------------------------------
// Public types
// -------------------------------------------------------

/// Horizontal text alignment within a table cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextAlign {
    /// Text is left-aligned within the cell (default).
    #[default]
    Left,
    /// Text is centered within the cell.
    Center,
    /// Text is right-aligned within the cell.
    Right,
}

/// How text that overflows the cell height is handled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CellOverflow {
    /// Text wraps across lines; row height grows to fit content (default).
    Wrap,
    /// Text is word-wrapped but clipped to the row's fixed height.
    Clip,
    /// Font size shrinks until all text fits within the row's fixed height.
    Shrink,
}

/// Style options for a table cell.
#[derive(Debug, Clone)]
pub struct CellStyle {
    /// Optional cell background color (overrides row background).
    pub background_color: Option<Color>,
    /// Optional text color. Defaults to PDF's current fill color (black).
    pub text_color: Option<Color>,
    /// Font reference.
    pub font: FontRef,
    /// Font size in points.
    pub font_size: f64,
    /// Padding applied to all four sides, in points.
    pub padding: f64,
    /// How to handle text that exceeds the available cell height.
    pub overflow: CellOverflow,
    /// How to handle words wider than the cell's available width.
    pub word_break: WordBreak,
    /// Horizontal text alignment within the cell.
    pub text_align: TextAlign,
}

impl Default for CellStyle {
    fn default() -> Self {
        CellStyle {
            background_color: None,
            text_color: None,
            font: FontRef::Builtin(BuiltinFont::Helvetica),
            font_size: 10.0,
            padding: 4.0,
            overflow: CellOverflow::Wrap,
            word_break: WordBreak::BreakAll,
            text_align: TextAlign::Left,
        }
    }
}

/// A single table cell containing text and style.
#[derive(Clone)]
pub struct Cell {
    /// Text content to display in the cell.
    pub text: String,
    /// Visual style for this cell (font, color, padding, overflow, alignment).
    pub style: CellStyle,
    /// Number of columns this cell spans (default `1`, must be >= 1).
    pub col_span: usize,
}

impl Cell {
    /// Create a cell with the default style.
    pub fn new(text: impl Into<String>) -> Self {
        Cell {
            text: text.into(),
            style: CellStyle::default(),
            col_span: 1,
        }
    }

    /// Create a cell with an explicit style.
    pub fn styled(text: impl Into<String>, style: CellStyle) -> Self {
        Cell {
            text: text.into(),
            style,
            col_span: 1,
        }
    }
}

/// A row of cells in a table.
#[derive(Clone)]
pub struct Row {
    /// Cells in this row. The sum of `col_span` values across all cells must
    /// equal the table's column count.
    pub cells: Vec<Cell>,
    /// Optional background color applied to the entire row.
    /// Per-cell background_color takes priority.
    pub background_color: Option<Color>,
    /// Fixed row height in points. Required for `Clip` and `Shrink` overflow.
    /// When `None`, height is auto-calculated from cell content (`Wrap` mode).
    pub height: Option<f64>,
}

impl Row {
    /// Create a row with auto-calculated height and no background.
    pub fn new(cells: Vec<Cell>) -> Self {
        Row {
            cells,
            background_color: None,
            height: None,
        }
    }
}

/// Table layout configuration. Holds column widths and visual style; does not
/// store row data. The caller supplies one `Row` at a time to `fit_row`,
/// enabling streaming from a database cursor without buffering the full dataset.
pub struct Table {
    /// Column widths in points.
    pub columns: Vec<f64>,
    /// Reference style for constructing cells. Clone it when creating cells
    /// to apply consistent styling across the table.
    pub default_style: CellStyle,
    /// Border stroke color (default: black).
    pub border_color: Color,
    /// Border line width in points. Set to `0.0` to disable borders.
    pub border_width: f64,
}

impl Table {
    /// Create a new table layout with the given column widths.
    pub fn new(columns: Vec<f64>) -> Self {
        Table {
            columns,
            default_style: CellStyle::default(),
            border_color: Color::rgb(0.0, 0.0, 0.0),
            border_width: 0.5,
        }
    }

    /// Generate PDF content stream bytes for a single row.
    ///
    /// Returns the content bytes, a `FitResult`, and the fonts used.
    /// Updates `cursor` to reflect the row's placement.
    pub(crate) fn generate_row_ops(
        &self,
        row: &Row,
        cursor: &mut TableCursor,
        tt_fonts: &mut [TrueTypeFont],
    ) -> (Vec<u8>, FitResult, UsedFonts) {
        let row_height = measure_row_height(row, &self.columns, &self.default_style, tt_fonts);
        let bottom = cursor.rect.y - cursor.rect.height;

        if cursor.current_y - row_height < bottom {
            // Nothing placed yet on this page — rect is too small for this row.
            // Otherwise the page is simply full and the caller should turn it.
            let result = if cursor.first_row {
                FitResult::BoxEmpty
            } else {
                FitResult::BoxFull
            };
            return (Vec::new(), result, UsedFonts::default());
        }

        let mut output: Vec<u8> = Vec::new();
        let mut used = UsedFonts::default();

        let segments = cell_segments(&row.cells, &self.columns, cursor.rect.x);

        draw_row_backgrounds_with_segments(
            row,
            &segments,
            cursor.rect.x,
            cursor.current_y,
            row_height,
            &self.columns,
            &mut output,
        );

        for (cell, (cell_x, cell_width)) in row.cells.iter().zip(segments.iter()) {
            render_cell(
                cell,
                *cell_x,
                cursor.current_y,
                *cell_width,
                row_height,
                tt_fonts,
                &mut output,
                &mut used,
            );
        }

        if self.border_width > 0.0 {
            draw_row_borders(
                &self.columns,
                &row.cells,
                cursor.rect.x,
                cursor.current_y,
                row_height,
                self.border_color,
                self.border_width,
                &mut output,
            );
        }

        cursor.current_y -= row_height;
        cursor.first_row = false;

        (output, FitResult::Stop, used)
    }
}

/// Tracks where the next row will be placed within a page.
///
/// Created once per table area, then passed to each `fit_row` call.
/// Call `reset()` when starting a new page to restore the cursor to
/// the top of the new rect. `is_first_row()` lets the caller detect
/// a fresh page — useful for repeating a header row.
///
/// # Example
/// ```no_run
/// # use pivot_pdf::{Table, TableCursor, Row, Cell, Rect, FitResult, PdfDocument};
/// # let table = Table::new(vec![200.0, 200.0]);
/// # let rect = Rect { x: 72.0, y: 720.0, width: 400.0, height: 648.0 };
/// # let header = Row::new(vec![Cell::new("Name"), Cell::new("Value")]);
/// # let data: Vec<Row> = vec![];
/// # let mut doc = PdfDocument::new(Vec::<u8>::new()).unwrap();
/// let mut cursor = TableCursor::new(&rect);
/// let mut rows = data.iter().peekable();
/// while rows.peek().is_some() {
///     doc.begin_page(612.0, 792.0);
///     // Repeat header on every page
///     doc.fit_row(&table, &header, &mut cursor).unwrap();
///     while let Some(row) = rows.peek() {
///         match doc.fit_row(&table, row, &mut cursor).unwrap() {
///             FitResult::Stop    => { rows.next(); }
///             FitResult::BoxFull => break,
///             FitResult::BoxEmpty => { rows.next(); break; }
///         }
///     }
///     doc.end_page().unwrap();
///     if rows.peek().is_some() { cursor.reset(&rect); }
/// }
/// ```
pub struct TableCursor {
    /// Bounding rectangle for the current page.
    pub(crate) rect: Rect,
    /// Top of the next row (PDF absolute coordinates, from page bottom).
    pub(crate) current_y: f64,
    /// True when no rows have been placed on the current page yet.
    pub(crate) first_row: bool,
}

impl TableCursor {
    /// Create a cursor positioned at the top of `rect`.
    pub fn new(rect: &Rect) -> Self {
        TableCursor {
            rect: *rect,
            current_y: rect.y,
            first_row: true,
        }
    }

    /// Reset to the top of a new rect. Call this when starting a new page.
    pub fn reset(&mut self, rect: &Rect) {
        self.rect = *rect;
        self.current_y = rect.y;
        self.first_row = true;
    }

    /// Returns `true` if no rows have been placed on the current page yet.
    ///
    /// Use this to detect the start of a new page so you can insert a
    /// repeated header row before placing data rows.
    pub fn is_first_row(&self) -> bool {
        self.first_row
    }

    /// Returns the Y coordinate where the next row would be placed.
    ///
    /// After placing all rows, this equals the bottom edge of the last row.
    /// Use it to position content that follows the table (e.g., totals section)
    /// without guessing where the table ended.
    pub fn current_y(&self) -> f64 {
        self.current_y
    }
}

// -------------------------------------------------------
// Measurement helpers
// -------------------------------------------------------

/// Compute (x_position, width) for each cell, respecting col_span.
fn cell_segments(cells: &[Cell], columns: &[f64], row_x: f64) -> Vec<(f64, f64)> {
    let mut segments = Vec::with_capacity(cells.len());
    let mut col_idx = 0;
    let mut x = row_x;
    for cell in cells {
        let span = cell.col_span.max(1);
        let end = (col_idx + span).min(columns.len());
        let width: f64 = columns[col_idx..end].iter().sum();
        segments.push((x, width));
        x += width;
        col_idx = end;
    }
    segments
}

/// Compute which column dividers should be drawn.
///
/// Returns a `Vec<bool>` of length `columns.len() - 1`. `visible[k]` is `true`
/// when the divider between column k and column k+1 should be drawn.
fn visible_dividers(cells: &[Cell], columns: &[f64]) -> Vec<bool> {
    let n = columns.len();
    if n <= 1 {
        return vec![];
    }
    let mut visible = vec![true; n - 1];
    let mut col_idx = 0;
    for cell in cells {
        let span = cell.col_span.max(1);
        // Suppress dividers within the span: between col_idx and col_idx+span-1.
        for k in col_idx..(col_idx + span).saturating_sub(1) {
            if k < visible.len() {
                visible[k] = false;
            }
        }
        col_idx += span;
    }
    visible
}

/// Compute the height needed for a row based on its content.
///
/// Returns `row.height` directly for fixed-height rows (Clip/Shrink modes).
/// Otherwise computes the maximum cell height across all cells, using each
/// cell's actual rendered width (accounting for col_span).
fn measure_row_height(
    row: &Row,
    columns: &[f64],
    default_style: &CellStyle,
    tt_fonts: &[TrueTypeFont],
) -> f64 {
    if let Some(h) = row.height {
        return h;
    }
    let mut max_height = 0.0_f64;
    let mut col_idx = 0;
    for cell in &row.cells {
        let span = cell.col_span.max(1);
        let end = (col_idx + span).min(columns.len());
        let cell_width: f64 = columns[col_idx..end].iter().sum();
        let h = measure_cell_height(&cell.text, &cell.style, cell_width, tt_fonts);
        max_height = max_height.max(h);
        col_idx = end;
    }
    if max_height == 0.0 {
        // Fallback: no cells
        let ts = make_text_style(default_style);
        line_height_for(&ts, tt_fonts) + 2.0 * default_style.padding
    } else {
        max_height
    }
}

/// Compute the height needed to display a cell's text content with wrapping.
fn measure_cell_height(
    text: &str,
    style: &CellStyle,
    col_width: f64,
    tt_fonts: &[TrueTypeFont],
) -> f64 {
    let avail_width = col_width - 2.0 * style.padding;
    let ts = make_text_style(style);
    let lh = line_height_for(&ts, tt_fonts);
    let lines = count_lines(text, avail_width, &ts, style.word_break, tt_fonts);
    lines as f64 * lh + 2.0 * style.padding
}

/// Convert a `CellStyle` to a `TextStyle` for use with measurement helpers.
fn make_text_style(style: &CellStyle) -> TextStyle {
    TextStyle {
        font: style.font,
        font_size: style.font_size,
    }
}

/// Count the total number of wrapped lines for `text` given the available width.
fn count_lines(
    text: &str,
    avail_width: f64,
    style: &TextStyle,
    word_break: WordBreak,
    tt_fonts: &[TrueTypeFont],
) -> usize {
    if text.is_empty() {
        return 1;
    }
    text.split('\n')
        .map(|para| count_paragraph_lines(para, avail_width, style, word_break, tt_fonts))
        .sum::<usize>()
        .max(1)
}

/// Count lines for a single paragraph (no newlines).
fn count_paragraph_lines(
    text: &str,
    avail_width: f64,
    style: &TextStyle,
    word_break: WordBreak,
    tt_fonts: &[TrueTypeFont],
) -> usize {
    let text = text.trim();
    if text.is_empty() {
        return 1;
    }
    let mut lines = 1usize;
    let mut line_width = 0.0_f64;

    for word in text.split_whitespace() {
        let word_w = measure_word(word, style, tt_fonts);
        let space_w = if line_width == 0.0 {
            0.0
        } else {
            measure_word(" ", style, tt_fonts)
        };
        let needed = line_width + space_w + word_w;

        if needed > avail_width && line_width > 0.0 {
            lines += 1;
            line_width = word_w;
            // If this word still overflows on its own line, count extra lines.
            if word_break != WordBreak::Normal && word_w > avail_width {
                lines += count_break_lines(word, avail_width, style, word_break, tt_fonts) - 1;
                line_width = trailing_piece_width(word, avail_width, style, word_break, tt_fonts);
            }
        } else if word_break != WordBreak::Normal && word_w > avail_width {
            // First word on a fresh line and it's still too wide.
            lines += count_break_lines(word, avail_width, style, word_break, tt_fonts) - 1;
            line_width = trailing_piece_width(word, avail_width, style, word_break, tt_fonts);
        } else {
            line_width = needed;
        }
    }
    lines
}

/// Count how many lines a single oversized word occupies when broken.
fn count_break_lines(
    word: &str,
    avail_width: f64,
    style: &TextStyle,
    word_break: WordBreak,
    tt_fonts: &[TrueTypeFont],
) -> usize {
    break_word(word, avail_width, style, word_break, tt_fonts).len()
}

/// Width of the last piece when a word is broken across lines.
fn trailing_piece_width(
    word: &str,
    avail_width: f64,
    style: &TextStyle,
    word_break: WordBreak,
    tt_fonts: &[TrueTypeFont],
) -> f64 {
    break_word(word, avail_width, style, word_break, tt_fonts)
        .last()
        .map_or(0.0, |p| measure_word(p, style, tt_fonts))
}

/// Word-wrap `text` into lines that fit within `avail_width`.
fn wrap_text(
    text: &str,
    avail_width: f64,
    style: &TextStyle,
    word_break: WordBreak,
    tt_fonts: &[TrueTypeFont],
) -> Vec<String> {
    let mut lines: Vec<String> = Vec::new();
    for para in text.split('\n') {
        wrap_paragraph(
            para.trim(),
            avail_width,
            style,
            word_break,
            tt_fonts,
            &mut lines,
        );
    }
    if lines.is_empty() {
        lines.push(String::new());
    }
    lines
}

/// Word-wrap a single paragraph into lines, appending to `out`.
fn wrap_paragraph(
    text: &str,
    avail_width: f64,
    style: &TextStyle,
    word_break: WordBreak,
    tt_fonts: &[TrueTypeFont],
    out: &mut Vec<String>,
) {
    if text.is_empty() {
        out.push(String::new());
        return;
    }
    let mut current_line = String::new();
    let mut line_width = 0.0_f64;

    for word in text.split_whitespace() {
        let word_w = measure_word(word, style, tt_fonts);
        let space_w = if current_line.is_empty() {
            0.0
        } else {
            measure_word(" ", style, tt_fonts)
        };
        let needed = line_width + space_w + word_w;

        if needed > avail_width && !current_line.is_empty() {
            out.push(current_line.clone());
            current_line = String::new();
            line_width = 0.0;
            // Fall through to place word on fresh line (may need breaking).
            place_word_on_line(
                word,
                avail_width,
                style,
                word_break,
                tt_fonts,
                &mut current_line,
                &mut line_width,
                out,
            );
        } else if word_w > avail_width && word_break != WordBreak::Normal && current_line.is_empty()
        {
            // Fresh line, word is too wide — break it.
            place_word_on_line(
                word,
                avail_width,
                style,
                word_break,
                tt_fonts,
                &mut current_line,
                &mut line_width,
                out,
            );
        } else {
            if !current_line.is_empty() {
                current_line.push(' ');
            }
            current_line.push_str(word);
            line_width = needed;
        }
    }
    if !current_line.is_empty() {
        out.push(current_line);
    }
}

/// Append a single word to lines, breaking it if it is wider than `avail_width`.
///
/// All full pieces except the last are pushed to `out`. The last piece is
/// accumulated into `current_line`/`line_width` so subsequent words can
/// continue on the same line.
fn place_word_on_line(
    word: &str,
    avail_width: f64,
    style: &TextStyle,
    word_break: WordBreak,
    tt_fonts: &[TrueTypeFont],
    current_line: &mut String,
    line_width: &mut f64,
    out: &mut Vec<String>,
) {
    let word_w = measure_word(word, style, tt_fonts);

    if word_w <= avail_width || word_break == WordBreak::Normal {
        if !current_line.is_empty() {
            current_line.push(' ');
        }
        current_line.push_str(word);
        *line_width += word_w;
        return;
    }

    let pieces = break_word(word, avail_width, style, word_break, tt_fonts);
    let last_idx = pieces.len() - 1;
    for (i, piece) in pieces.into_iter().enumerate() {
        if i < last_idx {
            out.push(piece);
        } else {
            *current_line = piece.clone();
            *line_width = measure_word(&piece, style, tt_fonts);
        }
    }
}

// -------------------------------------------------------
// Rendering helpers
// -------------------------------------------------------

/// Get the PDF resource name for a font.
fn pdf_font_name(font: FontRef, tt_fonts: &[TrueTypeFont]) -> String {
    match font {
        FontRef::Builtin(b) => b.pdf_name().to_string(),
        FontRef::TrueType(id) => tt_fonts[id.0].pdf_name.clone(),
    }
}

/// Record a font as used in the current page.
fn record_font(font: &FontRef, used: &mut UsedFonts) {
    match font {
        FontRef::Builtin(b) => {
            used.builtin.insert(*b);
        }
        FontRef::TrueType(id) => {
            used.truetype.insert(id.0);
        }
    }
}

/// Emit a text string using the correct encoding for the font type.
fn emit_cell_text(text: &str, font: FontRef, tt_fonts: &mut [TrueTypeFont], output: &mut Vec<u8>) {
    if text.is_empty() {
        return;
    }
    match font {
        FontRef::Builtin(_) => {
            let escaped = escape_pdf_string(text);
            output.extend_from_slice(format!("({}) Tj\n", escaped).as_bytes());
        }
        FontRef::TrueType(id) => {
            let hex = tt_fonts[id.0].encode_text_hex(text);
            output.extend_from_slice(format!("{} Tj\n", hex).as_bytes());
        }
    }
}

/// Draw row and cell background fills.
///
/// Row background is drawn first; per-cell backgrounds overlay on top.
/// `segments` contains the (x, width) for each cell, already accounting for col_span.
fn draw_row_backgrounds_with_segments(
    row: &Row,
    segments: &[(f64, f64)],
    row_x: f64,
    row_top: f64,
    row_height: f64,
    columns: &[f64],
    output: &mut Vec<u8>,
) {
    let row_bottom = row_top - row_height;

    if let Some(bg) = row.background_color {
        let total_width: f64 = columns.iter().sum();
        output.extend_from_slice(
            format!(
                "{} {} {} rg\n{} {} {} {} re\nf\n",
                format_coord(bg.r),
                format_coord(bg.g),
                format_coord(bg.b),
                format_coord(row_x),
                format_coord(row_bottom),
                format_coord(total_width),
                format_coord(row_height),
            )
            .as_bytes(),
        );
    }

    for (cell, &(cell_x, cell_width)) in row.cells.iter().zip(segments.iter()) {
        if let Some(bg) = cell.style.background_color {
            output.extend_from_slice(
                format!(
                    "{} {} {} rg\n{} {} {} {} re\nf\n",
                    format_coord(bg.r),
                    format_coord(bg.g),
                    format_coord(bg.b),
                    format_coord(cell_x),
                    format_coord(row_bottom),
                    format_coord(cell_width),
                    format_coord(row_height),
                )
                .as_bytes(),
            );
        }
    }
}

/// Draw row borders: outer rectangle plus vertical column dividers.
///
/// Vertical dividers within a cell's col_span are suppressed.
fn draw_row_borders(
    columns: &[f64],
    cells: &[Cell],
    row_x: f64,
    row_top: f64,
    row_height: f64,
    border_color: Color,
    border_width: f64,
    output: &mut Vec<u8>,
) {
    let row_bottom = row_top - row_height;
    let total_width: f64 = columns.iter().sum();

    output.extend_from_slice(b"q\n");
    output.extend_from_slice(
        format!(
            "{} {} {} RG\n{} w\n",
            format_coord(border_color.r),
            format_coord(border_color.g),
            format_coord(border_color.b),
            format_coord(border_width),
        )
        .as_bytes(),
    );

    // Outer rectangle of the row
    output.extend_from_slice(
        format!(
            "{} {} {} {} re\nS\n",
            format_coord(row_x),
            format_coord(row_bottom),
            format_coord(total_width),
            format_coord(row_height),
        )
        .as_bytes(),
    );

    // Vertical column dividers — suppressed within spans
    let visible = visible_dividers(cells, columns);
    let mut col_x = row_x;
    for (k, &col_width) in columns[..columns.len().saturating_sub(1)]
        .iter()
        .enumerate()
    {
        col_x += col_width;
        if visible.get(k).copied().unwrap_or(true) {
            output.extend_from_slice(
                format!(
                    "{} {} m\n{} {} l\nS\n",
                    format_coord(col_x),
                    format_coord(row_top),
                    format_coord(col_x),
                    format_coord(row_bottom),
                )
                .as_bytes(),
            );
        }
    }

    output.extend_from_slice(b"Q\n");
}

/// Compute the x coordinate for a line of text within a cell based on alignment.
fn aligned_x(
    line: &str,
    align: TextAlign,
    cell_x: f64,
    col_width: f64,
    padding: f64,
    ts: &TextStyle,
    tt_fonts: &[TrueTypeFont],
) -> f64 {
    match align {
        TextAlign::Left => cell_x + padding,
        TextAlign::Right => {
            let line_w = measure_word(line, ts, tt_fonts);
            cell_x + col_width - padding - line_w
        }
        TextAlign::Center => {
            let avail = col_width - 2.0 * padding;
            let line_w = measure_word(line, ts, tt_fonts);
            cell_x + padding + (avail - line_w).max(0.0) / 2.0
        }
    }
}

/// Render the text content of a single cell.
///
/// Wraps each cell in `q/Q` to isolate graphics state. Applies clip region
/// for `Clip` mode and reduces font size for `Shrink` mode.
fn render_cell(
    cell: &Cell,
    cell_x: f64,
    row_top: f64,
    col_width: f64,
    row_height: f64,
    tt_fonts: &mut [TrueTypeFont],
    output: &mut Vec<u8>,
    used: &mut UsedFonts,
) {
    let style = &cell.style;
    let avail_width = (col_width - 2.0 * style.padding).max(0.0);
    let avail_height = (row_height - 2.0 * style.padding).max(0.0);

    // Resolve effective font size (may be reduced for Shrink mode)
    let effective_font_size = if style.overflow == CellOverflow::Shrink {
        shrink_font_size(
            &cell.text,
            style.font,
            style.font_size,
            avail_width,
            avail_height,
            style.word_break,
            tt_fonts,
        )
    } else {
        style.font_size
    };

    let ts = TextStyle {
        font: style.font,
        font_size: effective_font_size,
    };
    let lh = line_height_for(&ts, tt_fonts);
    let lines = wrap_text(&cell.text, avail_width, &ts, style.word_break, tt_fonts);

    output.extend_from_slice(b"q\n");

    // Apply clipping rectangle for Clip mode
    if style.overflow == CellOverflow::Clip {
        let clip_bottom = row_top - row_height;
        output.extend_from_slice(
            format!(
                "{} {} {} {} re\nW\nn\n",
                format_coord(cell_x),
                format_coord(clip_bottom),
                format_coord(col_width),
                format_coord(row_height),
            )
            .as_bytes(),
        );
    }

    // Baseline: top of cell minus top padding minus font size (approximates ascent)
    let first_line_y = row_top - style.padding - effective_font_size;

    output.extend_from_slice(b"BT\n");

    // Always set an explicit fill color for text. Without this, the fill
    // color from background drawing (set outside q/Q) would bleed into
    // text rendering, making text invisible on colored backgrounds.
    let text_color = style
        .text_color
        .unwrap_or_else(|| Color::rgb(0.0, 0.0, 0.0));
    output.extend_from_slice(
        format!(
            "{} {} {} rg\n",
            format_coord(text_color.r),
            format_coord(text_color.g),
            format_coord(text_color.b),
        )
        .as_bytes(),
    );

    let font_name = pdf_font_name(ts.font, tt_fonts);
    output.extend_from_slice(
        format!("/{} {} Tf\n", font_name, format_coord(effective_font_size)).as_bytes(),
    );
    record_font(&ts.font, used);

    let align = style.text_align;
    let mut current_x = cell_x + style.padding; // placeholder; overwritten on first line

    for (i, line) in lines.iter().enumerate() {
        let line_x = aligned_x(line, align, cell_x, col_width, style.padding, &ts, tt_fonts);
        if i == 0 {
            output.extend_from_slice(
                format!(
                    "{} {} Td\n",
                    format_coord(line_x),
                    format_coord(first_line_y)
                )
                .as_bytes(),
            );
        } else {
            let dx = line_x - current_x;
            output.extend_from_slice(
                format!("{} {} Td\n", format_coord(dx), format_coord(-lh)).as_bytes(),
            );
        }
        current_x = line_x;
        emit_cell_text(line, ts.font, tt_fonts, output);
    }

    output.extend_from_slice(b"ET\n");
    output.extend_from_slice(b"Q\n");
}

/// Reduce font size by 0.5pt steps until the text fits within the available
/// dimensions, stopping at a minimum of 4pt.
///
/// When `word_break` is not `Normal`, every word can be broken, so only the
/// height constraint needs to be satisfied. When `Normal`, width must also
/// fit (a word wider than the column can never wrap — only shrinking helps).
fn shrink_font_size(
    text: &str,
    font: FontRef,
    initial_size: f64,
    avail_width: f64,
    avail_height: f64,
    word_break: WordBreak,
    tt_fonts: &[TrueTypeFont],
) -> f64 {
    const MIN_FONT_SIZE: f64 = 4.0;
    const STEP: f64 = 0.5;

    let mut font_size = initial_size;
    loop {
        let ts = TextStyle { font, font_size };
        let lh = line_height_for(&ts, tt_fonts);
        let lines = count_lines(text, avail_width, &ts, word_break, tt_fonts);
        let fits_height = lines as f64 * lh <= avail_height;
        let fits_width = word_break != WordBreak::Normal
            || text
                .split_whitespace()
                .all(|w| measure_word(w, &ts, tt_fonts) <= avail_width);
        if (fits_height && fits_width) || font_size <= MIN_FONT_SIZE {
            break;
        }
        font_size = (font_size - STEP).max(MIN_FONT_SIZE);
    }
    font_size
}