docxide-pdf 0.16.1

Library and CLI for converting DOCX files to PDF, matching Microsoft Word's output as closely as possible
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
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
use std::collections::HashMap;

use pdf_writer::{Content, Name, Str};

use crate::fonts::FontEntry;
use crate::model::{
    Alignment, Block, BorderStyle, CellBorder, CellMargins, CellVAlign,
    Paragraph, SectionProperties, Table, TableAlignment, TableRow, TextDirection, VMerge,
};

use super::color::{fill_rgb, stroke_rgb};
use super::header_footer::{compute_effective_margin_bottom, effective_slot_top};

use super::RenderContext;
use super::layout::{
    encode_text_for_pdf, render_paragraph_lines,
};
use super::table_layout::{
    CellContentItem, CellLayout, CellParagraphLayout, HfSubstitution,
    RowLayout, apply_pct_width, auto_fit_columns, cell_span_width, cell_x_offset, compute_merge_spans,
    compute_row_layouts, find_cell_split, para_block_height,
};

fn draw_border(content: &mut Content, border: &CellBorder, x1: f32, y1: f32, x2: f32, y2: f32) {
    if !border.present {
        return;
    }
    let w = border.width;
    content.save_state();
    content.set_line_width(w);
    if let Some(c) = border.color {
        stroke_rgb(content, c);
    }
    match border.style {
        BorderStyle::Dotted => {
            content.set_line_cap(pdf_writer::types::LineCapStyle::RoundCap);
            content.set_dash_pattern([0.0, w * 3.0], 0.0);
        }
        BorderStyle::Dashed | BorderStyle::DashSmallGap => {
            let dash = if border.style == BorderStyle::DashSmallGap {
                w * 3.0
            } else {
                w * 4.0
            };
            content.set_dash_pattern([dash, w * 2.0], 0.0);
        }
        BorderStyle::DashDot => {
            content.set_dash_pattern([w * 4.0, w * 2.0, 0.0, w * 2.0], 0.0);
        }
        BorderStyle::DashDotDot => {
            content.set_dash_pattern(
                [w * 4.0, w * 2.0, 0.0, w * 2.0, 0.0, w * 2.0],
                0.0,
            );
        }
        BorderStyle::Double => {
            // Word renders each line of a double border at the full specified
            // width, separated by a clear gap of the same width. The gap here is
            // the center-to-center distance, so it must be 2×width: each line's
            // stroke spans ±width/2, and 2×width centers leave a width-wide gap
            // between their edges. (gap == width made the edges touch, so
            // antialiasing merged the pair into one thick line.)
            let thin = w.max(0.25);
            let gap = thin * 2.0;
            content.set_line_width(thin);
            content.move_to(x1, y1);
            content.line_to(x2, y2);
            content.stroke();
            let dx = if (x1 - x2).abs() < 0.01 { gap } else { 0.0 };
            let dy = if (y1 - y2).abs() < 0.01 { gap } else { 0.0 };
            content.move_to(x1 - dx, y1 - dy);
            content.line_to(x2 - dx, y2 - dy);
            content.stroke();
            content.restore_state();
            return;
        }
        BorderStyle::Single => {}
    }
    content.move_to(x1, y1);
    content.line_to(x2, y2);
    content.stroke();
    content.restore_state();
}

fn draw_cell_borders(
    content: &mut Content,
    borders: &crate::model::CellBorders,
    bx: f32,
    top: f32,
    bottom: f32,
    col_w: f32,
    draw_top: bool,
    draw_bottom: bool,
) {
    if draw_top {
        draw_border(content, &borders.top, bx, top, bx + col_w, top);
    }
    if draw_bottom {
        draw_border(content, &borders.bottom, bx, bottom, bx + col_w, bottom);
    }
    draw_border(content, &borders.left, bx, top, bx, bottom);
    draw_border(content, &borders.right, bx + col_w, top, bx + col_w, bottom);
}

/// Paint a cell background: hatching when a line/cross pattern is present,
/// otherwise a solid fill. No-op when both are absent.
fn paint_cell_background(
    content: &mut Content,
    shading: Option<[u8; 3]>,
    hatch: Option<crate::model::HatchPattern>,
    x: f32,
    y: f32,
    w: f32,
    h: f32,
) {
    if let Some(hp) = hatch {
        draw_hatch(content, &hp, x, y, w, h);
    } else if let Some(s) = shading {
        content.save_state();
        fill_rgb(content, s);
        content.rect(x, y, w, h);
        content.fill_nonzero();
        content.restore_state();
    }
}

/// Draw a `w:shd` line/cross pattern as real hatching: a background fill plus
/// thin stroked lines clipped to the cell rect.
fn draw_hatch(content: &mut Content, hp: &crate::model::HatchPattern, x: f32, y: f32, w: f32, h: f32) {
    use crate::model::HatchKind::*;
    if w <= 0.0 || h <= 0.0 {
        return;
    }
    content.save_state();
    fill_rgb(content, hp.bg);
    content.rect(x, y, w, h);
    content.fill_nonzero();
    // Clip subsequent strokes to the cell so the diagonal lines don't bleed out.
    content.rect(x, y, w, h);
    content.clip_nonzero();
    content.end_path();
    stroke_rgb(content, hp.fg);
    content.set_line_width(0.5);
    let s = 4.0_f32;
    if matches!(hp.kind, Horz | CrossHorzVert) {
        let mut yy = y + s;
        while yy < y + h {
            content.move_to(x, yy);
            content.line_to(x + w, yy);
            yy += s;
        }
    }
    if matches!(hp.kind, Vert | CrossHorzVert) {
        let mut xx = x + s;
        while xx < x + w {
            content.move_to(xx, y);
            content.line_to(xx, y + h);
            xx += s;
        }
    }
    if matches!(hp.kind, DiagFwd | CrossDiag) {
        let mut off = 0.0;
        while off <= w + h {
            content.move_to(x + off - h, y);
            content.line_to(x + off, y + h);
            off += s;
        }
    }
    if matches!(hp.kind, DiagBack | CrossDiag) {
        let mut off = 0.0;
        while off <= w + h {
            content.move_to(x + off - h, y + h);
            content.line_to(x + off, y);
            off += s;
        }
    }
    content.stroke();
    content.restore_state();
}

fn draw_cell_shading(
    content: &mut Content,
    shading: Option<[u8; 3]>,
    hatch: Option<crate::model::HatchPattern>,
    borders: &crate::model::CellBorders,
    x: f32,
    y: f32,
    w: f32,
    h: f32,
) {
    let bw = |b: &crate::model::CellBorder| if b.present { b.width } else { 0.0 };
    let inset = (bw(&borders.top) + bw(&borders.bottom) + bw(&borders.left) + bw(&borders.right)) / 8.0;
    paint_cell_background(
        content,
        shading,
        hatch,
        x + inset,
        y + inset,
        w - 2.0 * inset,
        h - 2.0 * inset,
    );
}

/// Render an inline image within a table cell paragraph, handling alignment,
/// shadow, glow, stroke, and the image transform. Returns the image height
/// consumed so the caller can advance its cursor.
fn render_cell_inline_image(
    content: &mut Content,
    para: &CellParagraphLayout,
    img_name: &str,
    cell_x: f32,
    col_w: f32,
    cursor_y: f32,
    cm: &CellMargins,
) -> f32 {
    let text_w = (col_w - cm.left - cm.right).max(0.0);
    let img_x = match para.alignment {
        Alignment::Center => cell_x + cm.left + (text_w - para.image_width) / 2.0,
        Alignment::Right => cell_x + cm.left + text_w - para.image_width,
        _ => cell_x + cm.left,
    };
    let img_y = cursor_y - para.image_height;

    if let Some(ref shadow) = para.image_shadow {
        super::color::draw_image_shadow(
            content, shadow, img_x, img_y,
            para.image_width, para.image_height,
            para.image_shadow_xobj.as_deref(),
        );
    }
    if let Some(ref glow) = para.image_glow {
        super::color::draw_image_glow(
            content, glow, img_x, img_y,
            para.image_width, para.image_height,
            para.image_glow_xobj.as_deref(),
        );
    }

    super::smartart::render_image_with_clip(
        content, img_name, img_x, img_y,
        para.image_width, para.image_height,
        para.image_clip.as_ref(),
    );

    if let Some(sc) = para.image_stroke_color {
        super::smartart::stroke_image_border(
            content, img_x, img_y,
            para.image_width, para.image_height,
            sc, para.image_stroke_width,
            para.image_clip.as_ref(),
        );
    }

    para.image_height
}

fn valign_offset(v_align: CellVAlign, available: f32, content_h: f32) -> f32 {
    match v_align {
        CellVAlign::Top => 0.0,
        CellVAlign::Center => ((available - content_h) / 2.0).max(0.0),
        CellVAlign::Bottom => (available - content_h).max(0.0),
    }
}

fn para_has_visible_content(para: &CellParagraphLayout) -> bool {
    !para.list_label.is_empty()
        || (!para.lines.is_empty() && para.lines.iter().any(|l| !l.chunks.is_empty()))
        || !para.floating_images.is_empty()
        || para.image_name.is_some()
        || para.has_textboxes
        || para.has_connectors
}

/// Total content height including trailing space_after, matching Word's vAlign calculation.
fn cell_content_h_for_valign(items: &[CellContentItem]) -> f32 {
    let mut h: f32 = items
        .iter()
        .map(|item| match item {
            CellContentItem::Paragraph(p) => p.space_before + para_block_height(p),
            CellContentItem::NestedTable { height } => *height,
        })
        .sum();
    // Word includes the last paragraph's space_after in the content block height
    // used for vertical alignment, so bottom/center-aligned cells position correctly.
    if let Some(CellContentItem::Paragraph(last_para)) = items.last() {
        h += last_para.space_after;
    }
    h
}

fn cell_has_visible_content(items: &[CellContentItem]) -> bool {
    items.iter().any(|item| match item {
        CellContentItem::Paragraph(p) => para_has_visible_content(p),
        CellContentItem::NestedTable { height } => *height > 0.0,
    })
}

fn render_cell_content(
    content: &mut Content,
    items: &[CellContentItem],
    blocks: &[Block],
    cell_x: f32,
    col_w: f32,
    cursor_y_start: f32,
    cm: &CellMargins,
    ctx: &RenderContext,
    gradient_specs: &mut Vec<super::GradientSpec>,
) {
    let mut cursor_y = cursor_y_start;
    let mut block_idx = 0;

    for item in items {
        match item {
            CellContentItem::Paragraph(para) => {
                // Advance block_idx past the corresponding Block::Paragraph
                let mut source_para: Option<&Paragraph> = None;
                while block_idx < blocks.len() {
                    if let Block::Paragraph(p) = &blocks[block_idx] {
                        source_para = Some(p);
                        block_idx += 1;
                        break;
                    }
                    block_idx += 1;
                }

                let para_top = cursor_y;
                if !para_has_visible_content(para)
                    && !para.has_textboxes
                    && !para.has_connectors
                {
                    cursor_y -= para.space_before + para_block_height(para);
                    continue;
                }

                cursor_y -= para.space_before;

                // Render floating images positioned relative to this paragraph
                for fi in &para.floating_images {
                    let fi_x = cell_x + fi.h_offset;
                    let fi_y_top = cursor_y - fi.v_offset;
                    let fi_y_bottom = fi_y_top - fi.display_height;
                    content.save_state();
                    push_center_rotation(
                        content, fi_x, fi_y_bottom, fi.display_width, fi.display_height,
                        fi.rotation_deg,
                    );
                    content.transform([
                        fi.display_width,
                        0.0,
                        0.0,
                        fi.display_height,
                        fi_x,
                        fi_y_bottom,
                    ]);
                    content.x_object(Name(fi.pdf_name.as_bytes()));
                    content.restore_state();
                }

                if let Some(ref img_name) = para.image_name {
                    // distT/distB in layout_extra_height contribute to row
                    // height but don't add spacing between image and text.
                    cursor_y -= render_cell_inline_image(
                        content, para, img_name, cell_x, col_w, cursor_y, cm,
                    );
                    continue;
                }

                let text_x = cell_x + cm.left + para.indent_left + para.float_indent_left;
                let text_w =
                    (col_w - cm.left - cm.right - para.indent_left - para.float_indent_left)
                        .max(0.0);
                // Word positions first baseline at cell_top - font_size (full em)
                let baseline_y = cursor_y - para.font_size;

                let first_line_hanging = if para.list_label.is_empty() {
                    para.indent_hanging
                } else {
                    let label_x = cell_x + cm.left + para.indent_left - para.indent_hanging;
                    draw_cell_label(content, para, label_x, baseline_y, ctx.fonts);
                    if para.indent_first_line > 0.0 && para.indent_hanging == 0.0 {
                        -para.indent_first_line
                    } else {
                        0.0
                    }
                };

                render_paragraph_lines(
                    content,
                    &para.lines,
                    &para.alignment,
                    text_x,
                    text_w,
                    baseline_y,
                    para.line_h,
                    para.lines.len(),
                    0,
                    &mut Vec::new(),
                    first_line_hanging,
                    ctx.fonts,
                    None,
                    gradient_specs,
                    None,
                    None,
                );

                cursor_y -= para.lines.len() as f32 * para.line_h;

                if let Some(src) = source_para {
                    render_cell_floating_shapes(
                        content, src, cell_x, col_w, para_top, ctx, gradient_specs,
                    );
                }
            }
            CellContentItem::NestedTable { height } => {
                // Find the corresponding Block::Table
                let table = loop {
                    if block_idx >= blocks.len() {
                        break None;
                    }
                    if let Block::Table(t) = &blocks[block_idx] {
                        block_idx += 1;
                        break Some(t);
                    }
                    block_idx += 1;
                };
                if let Some(table) = table {
                    render_nested_table(
                        table,
                        content,
                        cell_x + cm.left,
                        col_w - cm.left - cm.right,
                        &mut cursor_y,
                        ctx,
                        gradient_specs,
                    );
                } else {
                    cursor_y -= height;
                }
            }
        }
    }
}

/// Emit a CTM rotation about the center of a placed image box, matching the
/// body float path (OOXML clockwise → negated for PDF's CCW). Must be pushed
/// before the box's scale/translate transform so the box rotates about its center.
fn push_center_rotation(content: &mut Content, x: f32, y_bottom: f32, w: f32, h: f32, deg: f32) {
    if deg.abs() <= 0.01 {
        return;
    }
    let cx = x + w / 2.0;
    let cy = y_bottom + h / 2.0;
    let rad = -deg.to_radians();
    let (sin, cos) = rad.sin_cos();
    content.transform([
        cos, sin, -sin, cos,
        cx - cos * cx + sin * cy,
        cy - sin * cx - cos * cy,
    ]);
}

/// Render floating textboxes and connectors anchored to a cell paragraph.
fn render_cell_floating_shapes(
    content: &mut Content,
    para: &Paragraph,
    cell_x: f32,
    col_w: f32,
    para_top: f32,
    ctx: &RenderContext,
    gradient_specs: &mut Vec<super::GradientSpec>,
) {
    use crate::model::{HorizontalPosition, VerticalPosition};
    use super::positioning::render_connector;

    for conn in &para.connectors {
        let conn_x = match conn.connector_type {
            _ => conn.x,
        };
        let mut conn_clone = conn.clone();
        // Position relative to cell column origin and paragraph top
        conn_clone.x = conn_x;
        render_connector(&conn_clone, content, cell_x, para_top);
    }

    for tb in &para.textboxes {
        let h_off = match tb.h_position {
            HorizontalPosition::Offset(o) => o,
            HorizontalPosition::AlignCenter => (col_w - tb.width_pt) / 2.0,
            HorizontalPosition::AlignRight => col_w - tb.width_pt,
            HorizontalPosition::AlignLeft => 0.0,
        };
        let tb_x = cell_x + h_off;
        let tb_y_top = para_top - tb.v_offset_pt;
        render_simple_textbox(content, tb, tb_x, tb_y_top, ctx, gradient_specs);
    }
}

/// Minimal textbox rendering for cell contexts: stroke/fill the shape and
/// render text content. Doesn't support all features that body textboxes do.
fn render_simple_textbox(
    content: &mut Content,
    tb: &crate::model::Textbox,
    tb_x: f32,
    tb_y_top: f32,
    ctx: &RenderContext,
    gradient_specs: &mut Vec<super::GradientSpec>,
) {
    use crate::model::ShapeFill;
    use super::smartart::{draw_shape_path, draw_shape_stroke_path};
    use super::textbox_render::render_textbox_paragraphs;

    let tb_width = tb.width_pt;
    let tb_height = tb.height_pt;

    // Fill
    if let Some(ShapeFill::Solid(color)) = &tb.fill {
        content.save_state();
        fill_rgb(content, *color);
        draw_shape_path(content, tb_x, tb_y_top - tb_height, tb_width, tb_height, &tb.shape_type);
        content.fill_nonzero();
        content.restore_state();
    }

    // Stroke
    if let Some(stroke) = tb.stroke_color {
        if tb.stroke_width > 0.0 {
            content.save_state();
            content.set_line_width(tb.stroke_width);
            stroke_rgb(content, stroke);
            // Honor per-subpath stroke flags (brace/bracket pairs have a
            // fill-only outline subpath), same as body-anchored textboxes.
            draw_shape_stroke_path(content, tb_x, tb_y_top - tb_height, tb_width, tb_height, &tb.shape_type);
            content.stroke();
            content.restore_state();
        }
    }

    // Text: route through the shared textbox renderer (same path as body
    // textboxes). Cell context has no link sink, so hyperlinks are discarded.
    let content_x = tb_x + tb.margin_left;
    let content_w = (tb_width - tb.margin_left - tb.margin_right).max(0.0);
    render_textbox_paragraphs(
        &tb.paragraphs,
        content,
        content_x,
        content_w,
        content_w,
        tb_y_top - tb.margin_top,
        0.0,
        0.0,
        None,
        true,
        &mut Vec::new(),
        ctx,
        None,
        gradient_specs,
    );
}

/// Render a nested table inline within a parent cell at the given cursor position.
/// Render every row of `table` — cell backgrounds and content, then borders —
/// advancing `cursor_y`. Shared by nested and header/footer table rendering.
fn render_table_rows(
    table: &Table,
    row_layouts: &[RowLayout],
    col_widths: &[f32],
    table_left: f32,
    merge_spans: &HashMap<(usize, usize), f32>,
    content: &mut Content,
    cursor_y: &mut f32,
    ctx: &RenderContext,
    gradient_specs: &mut Vec<super::GradientSpec>,
) {
    let cm = &table.cell_margins;
    for (ri, (row, layout)) in table.rows.iter().zip(row_layouts.iter()).enumerate() {
        let row_h = layout.height;
        let row_top = *cursor_y;
        let row_bottom = row_top - row_h;

        let mut grid_col = 0usize;
        for (cell, cell_layout) in row.cells.iter().zip(layout.cells.iter()) {
            let span = cell.grid_span.max(1) as usize;
            let col_w = cell_span_width(col_widths, grid_col, span);
            let cx = cell_x_offset(col_widths, table_left, grid_col);
            let cell_grid_col = grid_col;
            grid_col += span;

            if cell.v_merge == VMerge::Continue {
                continue;
            }

            let merge_extra = merge_spans
                .get(&(ri, cell_grid_col))
                .copied()
                .unwrap_or(0.0);
            let effective_h = row_h + merge_extra;

            paint_cell_background(content, cell.shading, cell.hatch, cx, row_bottom, col_w, row_h);

            if cell_has_visible_content(&cell_layout.items) {
                let ecm = cell.cell_margins.as_ref().unwrap_or(cm);
                let content_h = cell_content_h_for_valign(&cell_layout.items);

                let avail = effective_h - ecm.top - ecm.bottom;
                let v_offset = valign_offset(cell.v_align, avail, content_h);
                let cell_cursor_y = row_top - ecm.top - v_offset;

                render_cell_content(
                    content,
                    &cell_layout.items,
                    &cell.content,
                    cx,
                    col_w,
                    cell_cursor_y,
                    ecm,
                    ctx,
                    gradient_specs,
                );
            }
        }

        let mut grid_col = 0usize;
        for cell in &row.cells {
            let span = cell.grid_span.max(1) as usize;
            let col_w = cell_span_width(col_widths, grid_col, span);
            let bx = cell_x_offset(col_widths, table_left, grid_col);
            let cell_grid_col = grid_col;
            grid_col += span;

            if cell.v_merge == VMerge::Continue {
                continue;
            }

            let merge_extra = merge_spans
                .get(&(ri, cell_grid_col))
                .copied()
                .unwrap_or(0.0);
            let effective_bottom = row_bottom - merge_extra;

            draw_cell_borders(
                content,
                &cell.borders,
                bx,
                row_top,
                effective_bottom,
                col_w,
                ri == 0,
                true,
            );
        }

        *cursor_y = row_bottom;
    }
}

fn render_nested_table(
    table: &Table,
    content: &mut Content,
    available_x: f32,
    available_w: f32,
    cursor_y: &mut f32,
    ctx: &RenderContext,
    gradient_specs: &mut Vec<super::GradientSpec>,
) {
    let mut col_widths = auto_fit_columns(table, ctx.fonts, Some(available_w), None);
    apply_pct_width(table, &mut col_widths, available_w);
    let row_layouts = compute_row_layouts(table, &col_widths, ctx, None);
    let table_total_w: f32 = col_widths.iter().sum();
    let table_left = match table.alignment {
        TableAlignment::Center => available_x + (available_w - table_total_w) / 2.0,
        TableAlignment::Right => available_x + available_w - table_total_w,
        TableAlignment::Left => available_x + table.table_indent,
    };

    let merge_spans = compute_merge_spans(table, &row_layouts);

    render_table_rows(
        table,
        &row_layouts,
        &col_widths,
        table_left,
        &merge_spans,
        content,
        cursor_y,
        ctx,
        gradient_specs,
    );
}

fn render_partial_cell_content(
    content: &mut Content,
    items: &[CellContentItem],
    blocks: &[Block],
    start: usize,
    end: usize,
    cell_x: f32,
    col_w: f32,
    cursor_y_start: f32,
    cm: &CellMargins,
    ctx: &RenderContext,
    gradient_specs: &mut Vec<super::GradientSpec>,
) {
    let mut cursor_y = cursor_y_start;
    // Build a mapping from item index to block index
    let mut block_idx = 0usize;
    let mut item_to_block: Vec<usize> = Vec::new();
    for item in items {
        item_to_block.push(block_idx);
        match item {
            CellContentItem::Paragraph(_) => {
                while block_idx < blocks.len() {
                    if matches!(&blocks[block_idx], Block::Paragraph(_)) {
                        block_idx += 1;
                        break;
                    }
                    block_idx += 1;
                }
            }
            CellContentItem::NestedTable { .. } => {
                while block_idx < blocks.len() {
                    if matches!(&blocks[block_idx], Block::Table(_)) {
                        block_idx += 1;
                        break;
                    }
                    block_idx += 1;
                }
            }
        }
    }

    for pi in start..end {
        match &items[pi] {
            CellContentItem::Paragraph(para) => {
                let sb = if pi == start { 0.0 } else { para.space_before };

                if !para_has_visible_content(para) {
                    cursor_y -= sb + para_block_height(para);
                    continue;
                }

                cursor_y -= sb;

                for fi in &para.floating_images {
                    let fi_x = cell_x + fi.h_offset;
                    let fi_y_top = cursor_y - fi.v_offset;
                    let fi_y_bottom = fi_y_top - fi.display_height;
                    content.save_state();
                    push_center_rotation(
                        content, fi_x, fi_y_bottom, fi.display_width, fi.display_height,
                        fi.rotation_deg,
                    );
                    content.transform([
                        fi.display_width,
                        0.0,
                        0.0,
                        fi.display_height,
                        fi_x,
                        fi_y_bottom,
                    ]);
                    content.x_object(Name(fi.pdf_name.as_bytes()));
                    content.restore_state();
                }

                if let Some(ref img_name) = para.image_name {
                    cursor_y -= render_cell_inline_image(
                        content, para, img_name, cell_x, col_w, cursor_y, cm,
                    );
                    continue;
                }

                let text_x = cell_x + cm.left + para.indent_left + para.float_indent_left;
                let text_w =
                    (col_w - cm.left - cm.right - para.indent_left - para.float_indent_left)
                        .max(0.0);
                // Word positions first baseline at cell_top - font_size (full em)
                let baseline_y = cursor_y - para.font_size;

                let first_line_hanging = if para.list_label.is_empty() {
                    para.indent_hanging
                } else {
                    let label_x = cell_x + cm.left + para.indent_left - para.indent_hanging;
                    draw_cell_label(content, para, label_x, baseline_y, ctx.fonts);
                    if para.indent_first_line > 0.0 && para.indent_hanging == 0.0 {
                        -para.indent_first_line
                    } else {
                        0.0
                    }
                };

                render_paragraph_lines(
                    content,
                    &para.lines,
                    &para.alignment,
                    text_x,
                    text_w,
                    baseline_y,
                    para.line_h,
                    para.lines.len(),
                    0,
                    &mut Vec::new(),
                    first_line_hanging,
                    ctx.fonts,
                    None,
                    gradient_specs,
                    None,
                    None,
                );

                cursor_y -= para.lines.len() as f32 * para.line_h;
            }
            CellContentItem::NestedTable { height } => {
                let bi = item_to_block.get(pi).copied().unwrap_or(0);
                if let Some(Block::Table(table)) = blocks.get(bi) {
                    render_nested_table(
                        table, content, cell_x + cm.left, col_w - cm.left - cm.right,
                        &mut cursor_y, ctx, gradient_specs,
                    );
                } else {
                    cursor_y -= height;
                }
            }
        }
    }
}

fn draw_cell_label(
    content: &mut Content,
    para: &CellParagraphLayout,
    label_x: f32,
    baseline_y: f32,
    fonts: &HashMap<String, FontEntry>,
) {
    let font_key = para
        .list_label_font
        .as_deref()
        .unwrap_or(para.first_run_font_key.as_str());
    let Some(entry) = fonts.get(font_key) else {
        return;
    };
    let bytes = entry.encode(&para.list_label);

    if let Some(c) = para.label_color {
        fill_rgb(content, c);
    }
    content
        .begin_text()
        .set_font(Name(entry.pdf_name.as_bytes()), para.font_size)
        .next_line(label_x, baseline_y)
        .show(Str(&bytes))
        .end_text();
    if para.label_color.is_some() {
        content.set_fill_gray(0.0);
    }
}

fn render_table_row(
    row: &TableRow,
    layout: &RowLayout,
    col_widths: &[f32],
    cm: &CellMargins,
    table_left: f32,
    pb: &mut super::PageBuilder,
    ctx: &RenderContext,
    row_idx: usize,
    merge_spans: &HashMap<(usize, usize), f32>,
) {
    let row_h = layout.height;
    let row_top = pb.slot_top;
    let row_bottom = row_top - row_h;

    let mut grid_col = 0usize;
    for (cell, cell_layout) in row.cells.iter().zip(layout.cells.iter()) {
        let span = cell.grid_span.max(1) as usize;
        let col_w = cell_span_width(col_widths, grid_col, span);
        let cell_x = cell_x_offset(col_widths, table_left, grid_col);
        let cell_grid_col = grid_col;
        grid_col += span;

        if cell.v_merge == VMerge::Continue {
            continue;
        }

        let merge_extra = merge_spans
            .get(&(row_idx, cell_grid_col))
            .copied()
            .unwrap_or(0.0);
        let effective_h = row_h + merge_extra;

        draw_cell_shading(
            &mut pb.content,
            cell.shading,
            cell.hatch,
            &cell.borders,
            cell_x,
            row_top - effective_h,
            col_w,
            effective_h,
        );

        let has_content = cell_has_visible_content(&cell_layout.items);
        let ecm = cell.cell_margins.as_ref().unwrap_or(cm);

        if has_content && cell_layout.text_direction == TextDirection::TbRl {
            render_vertical_cjk_cell(
                &mut pb.content,
                cell_layout,
                cell,
                cell_x,
                row_top,
                effective_h,
                col_w,
                ecm,
                ctx,
            );
        } else if has_content {
            let content_h = cell_content_h_for_valign(&cell_layout.items);

            let avail = effective_h - ecm.top - ecm.bottom;
            let v_offset = valign_offset(cell.v_align, avail, content_h);
            let cursor_y = row_top - ecm.top - v_offset;

            render_cell_content(
                &mut pb.content,
                &cell_layout.items,
                &cell.content,
                cell_x,
                col_w,
                cursor_y,
                ecm,
                ctx,
                &mut pb.gradient_specs,
            );
        }
    }

    let mut grid_col = 0usize;
    for cell in &row.cells {
        let span = cell.grid_span.max(1) as usize;
        let col_w = cell_span_width(col_widths, grid_col, span);
        let bx = cell_x_offset(col_widths, table_left, grid_col);

        if cell.v_merge == VMerge::Continue {
            grid_col += span;
            continue;
        }

        let merge_extra = merge_spans
            .get(&(row_idx, grid_col))
            .copied()
            .unwrap_or(0.0);
        let effective_bottom = row_bottom - merge_extra;

        draw_cell_borders(
            &mut pb.content,
            &cell.borders,
            bx,
            row_top,
            effective_bottom,
            col_w,
            true,
            true,
        );

        grid_col += span;
    }

    pb.slot_top = row_bottom;
}

fn render_vertical_cjk_cell(
    content: &mut Content,
    cell_layout: &CellLayout,
    cell: &crate::model::TableCell,
    cell_x: f32,
    row_top: f32,
    row_h: f32,
    col_w: f32,
    cm: &CellMargins,
    ctx: &RenderContext,
) {
    let pdf_name_to_entry: HashMap<&str, &FontEntry> = ctx
        .fonts
        .values()
        .map(|e| (e.pdf_name.as_str(), e))
        .collect();

    let paras: Vec<&CellParagraphLayout> = cell_layout
        .items
        .iter()
        .filter_map(|item| match item {
            CellContentItem::Paragraph(p) => Some(p),
            _ => None,
        })
        .collect();
    let total_char_h: f32 = paras
        .iter()
        .flat_map(|p| &p.lines)
        .flat_map(|l| &l.chunks)
        .filter(|c| !c.text.is_empty())
        .map(|c| c.text.chars().count() as f32 * c.font_size)
        .sum();

    let avail_h = row_h - cm.top - cm.bottom;
    // In vertical text cells, paragraph jc controls vertical positioning
    let effective_v_align = if cell.v_align == CellVAlign::Top {
        match paras.first().map(|p| p.alignment) {
            Some(Alignment::Center) => CellVAlign::Center,
            Some(Alignment::Right) => CellVAlign::Bottom,
            _ => CellVAlign::Center,
        }
    } else {
        cell.v_align
    };
    let v_offset = valign_offset(effective_v_align, avail_h, total_char_h);

    let avail_w = col_w - cm.left - cm.right;
    let mut char_y = row_top - cm.top - v_offset;
    let mut char_buf = [0u8; 4];

    for para in &paras {
        for line in &para.lines {
            for chunk in &line.chunks {
                if chunk.text.is_empty() {
                    continue;
                }
                let fs = chunk.font_size;
                let entry = pdf_name_to_entry.get(chunk.pdf_font.as_str());
                let ascender_ratio = entry.and_then(|e| e.ascender_ratio).unwrap_or(0.75);
                let widths = entry.and_then(|e| e.char_widths_1000.as_ref());

                if let Some(c) = chunk.color {
                    fill_rgb(content, c);
                }

                content.begin_text();
                content.set_font(Name(chunk.pdf_font.as_bytes()), fs);

                let mut td_x = 0.0f32;
                let mut td_y = 0.0f32;
                for ch in chunk.text.chars() {
                    let baseline_y = char_y - fs * ascender_ratio;
                    let char_w = widths
                        .and_then(|m| m.get(&ch))
                        .map(|w| w * fs / 1000.0)
                        .unwrap_or(fs);
                    let cx = cell_x + cm.left + (avail_w - char_w) / 2.0;

                    let ch_str = ch.encode_utf8(&mut char_buf);
                    let bytes = encode_text_for_pdf(ch_str, &chunk.pdf_font, &pdf_name_to_entry);
                    content.next_line(cx - td_x, baseline_y - td_y);
                    td_x = cx;
                    td_y = baseline_y;
                    content.show(Str(&bytes));

                    char_y -= fs;
                }
                content.end_text();

                if chunk.color.is_some() {
                    content.set_fill_gray(0.0);
                }
            }
        }
    }
}

/// Render a subset of each cell's paragraphs for a split row.
/// `starts[ci]..ends[ci]` gives the paragraph range for cell `ci`.
/// `is_first`/`is_last` control top/bottom border drawing.
fn render_partial_row(
    row: &TableRow,
    layout: &RowLayout,
    col_widths: &[f32],
    cm: &CellMargins,
    table_left: f32,
    pb: &mut super::PageBuilder,
    ctx: &RenderContext,
    starts: &[usize],
    ends: &[usize],
    is_first: bool,
    is_last: bool,
    fill_to_bottom_y: Option<f32>,
) {
    let mut max_h: f32 = cm.top + cm.bottom;
    for (ci, cell_layout) in layout.cells.iter().enumerate() {
        let start = starts[ci];
        let end = ends[ci];
        let mut h = cm.top + cm.bottom;
        for pi in start..end {
            let item_h = match &cell_layout.items[pi] {
                CellContentItem::Paragraph(para) => {
                    let sb = if pi == start { 0.0 } else { para.space_before };
                    sb + para_block_height(para)
                }
                CellContentItem::NestedTable { height } => *height,
            };
            h += item_h;
        }
        max_h = max_h.max(h);
    }

    let row_top = pb.slot_top;
    // For non-final chunks, extend the cell shading/borders to the page's
    // content-bottom so the table visually spans the full page height — Word
    // does this when splitting rows across pages.
    let fill_h = fill_to_bottom_y
        .map(|y_bot| (row_top - y_bot).max(max_h))
        .unwrap_or(max_h);
    let row_h = fill_h;
    let row_bottom = row_top - row_h;

    let mut grid_col = 0usize;
    for (ci, (cell, cell_layout)) in row.cells.iter().zip(layout.cells.iter()).enumerate() {
        let span = cell.grid_span.max(1) as usize;
        let col_w = cell_span_width(col_widths, grid_col, span);
        let cell_x = cell_x_offset(col_widths, table_left, grid_col);
        grid_col += span;

        if cell.v_merge == VMerge::Continue {
            continue;
        }

        let start = starts[ci];
        let end = ends[ci];

        draw_cell_shading(
            &mut pb.content,
            cell.shading,
            cell.hatch,
            &cell.borders,
            cell_x,
            row_bottom,
            col_w,
            row_h,
        );

        let has_content = (start..end).any(|pi| match &cell_layout.items[pi] {
            CellContentItem::Paragraph(p) => para_has_visible_content(p),
            CellContentItem::NestedTable { height } => *height > 0.0,
        });

        if has_content {
            render_partial_cell_content(
                &mut pb.content,
                &cell_layout.items,
                &cell.content,
                start,
                end,
                cell_x,
                col_w,
                row_top - cm.top,
                cm,
                ctx,
                &mut pb.gradient_specs,
            );
        }
    }

    let mut grid_col = 0usize;
    for cell in &row.cells {
        let span = cell.grid_span.max(1) as usize;
        let col_w = cell_span_width(col_widths, grid_col, span);
        let bx = cell_x_offset(col_widths, table_left, grid_col);
        grid_col += span;

        if cell.v_merge == VMerge::Continue {
            continue;
        }

        let draw_top = is_first;
        draw_cell_borders(
            &mut pb.content,
            &cell.borders,
            bx,
            row_top,
            row_bottom,
            col_w,
            draw_top,
            is_last,
        );
    }

    pb.slot_top = row_bottom;
}

fn render_header_rows(
    table: &Table,
    row_layouts: &[RowLayout],
    col_widths: &[f32],
    cm: &CellMargins,
    table_left: f32,
    pb: &mut super::PageBuilder,
    ctx: &RenderContext,
    merge_spans: &HashMap<(usize, usize), f32>,
    header_count: usize,
) {
    for hi in 0..header_count {
        render_table_row(
            &table.rows[hi],
            &row_layouts[hi],
            col_widths,
            cm,
            table_left,
            pb,
            ctx,
            hi,
            merge_spans,
        );
    }
}

/// `override_pos`: positioning info for floating tables.
pub(super) fn render_table(
    table: &Table,
    sp: &SectionProperties,
    ctx: &RenderContext,
    pb: &mut super::PageBuilder,
    sect_idx: usize,
    prev_space_after: f32,
    override_pos: Option<super::FloatingTablePos>,
    footnotes: &std::collections::HashMap<u32, crate::model::Footnote>,
    effective_margin_bottom: &mut f32,
    column_bounds: Option<(f32, f32)>,
) {
    let available_w = column_bounds.map(|(_, w)| w);
    // Top-level table: an AutoFit-to-Window table fills the available width
    // (page text column or newspaper column), so feed the content width even
    // when no column bound is set. Passed as the dedicated fill target so it
    // only steers the window-fill path, not the nested-table shrink path.
    let fit_w = available_w.unwrap_or(sp.page_width - sp.margin_left - sp.margin_right);
    let mut col_widths = if table.fixed_layout {
        table.col_widths.clone()
    } else {
        auto_fit_columns(table, ctx.fonts, available_w, Some(fit_w))
    };
    apply_pct_width(
        table,
        &mut col_widths,
        available_w.unwrap_or(sp.page_width - sp.margin_left - sp.margin_right),
    );
    let row_layouts = compute_row_layouts(table, &col_widths, ctx, None);
    let merge_spans = compute_merge_spans(table, &row_layouts);
    let cm = &table.cell_margins;

    let is_floating = override_pos.is_some();
    let (table_left, saved_slot_top, text_margins) =
        if let Some(ref fp) = override_pos {
            let saved = Some((pb.slot_top - prev_space_after, fp.y));
            pb.slot_top = fp.y;
            (fp.x, saved, (fp.top_from_text, fp.bottom_from_text))
        } else {
        use crate::model::TableAlignment;
        let (area_left, area_width) = column_bounds
            .unwrap_or((sp.margin_left, sp.page_width - sp.margin_left - sp.margin_right));
        let table_total_w: f32 = col_widths.iter().sum();
        let left = match table.alignment {
            TableAlignment::Center => area_left + (area_width - table_total_w) / 2.0,
            TableAlignment::Right => area_left + area_width - table_total_w,
            // When tblInd is explicitly set AND significantly different
            // from the cell margin, it positions the table edge directly.
            // When absent, or when tblInd ≈ cm.left (common in
            // LibreOffice-generated DOCX), legacy behavior subtracts
            // cm.left so first-cell text aligns with the page margin.
            TableAlignment::Left => {
                let ind = table.table_indent;
                let explicit_real_indent = table.table_indent_explicit
                    && (ind - cm.left).abs() > 1.0;
                if explicit_real_indent {
                    area_left + ind
                } else {
                    area_left + ind - cm.left
                }
            }
        };
        (left, None, (0.0, 0.0))
    };

    // For non-floating tables, prev_space_after offsets the table start.
    // For floating tables, it was already consumed into the saved cursor position.
    pb.slot_top -= prev_space_after;

    // Count contiguous header rows from the start of the table (per OOXML spec,
    // only contiguous header rows starting from row 0 are repeated).
    let header_count = table.rows.iter().take_while(|r| r.is_header).count();

    // Pre-scan each row for footnote and endnote references so we can reserve
    // space as rows containing notes are rendered.
    let row_footnote_ids: Vec<Vec<u32>> = table.rows.iter().map(|row| {
        let mut ids = Vec::new();
        for cell in &row.cells {
            for p in cell.all_paragraphs() {
                for run in &p.runs {
                    if let Some(id) = run.footnote_id {
                        ids.push(id);
                    }
                }
            }
        }
        ids
    }).collect();
    let row_endnote_ids: Vec<Vec<u32>> = table.rows.iter().map(|row| {
        let mut ids = Vec::new();
        for cell in &row.cells {
            for p in cell.all_paragraphs() {
                for run in &p.runs {
                    if let Some(id) = run.endnote_id {
                        ids.push(id);
                    }
                }
            }
        }
        ids
    }).collect();

    // Text width for footnote height computation (same as paragraph layout uses).
    let fn_text_width = sp.page_width - sp.margin_left - sp.margin_right;

    let flush_and_render_headers = |pb: &mut super::PageBuilder, ri: usize, emb: &mut f32| {
        pb.flush_page(sect_idx);
        pb.is_first_page_of_section = false;
        pb.slot_top = effective_slot_top(sp, false, ctx);
        pb.column_top_y = pb.slot_top;
        *emb = compute_effective_margin_bottom(sp, false, ctx);
        if header_count > 0 && ri >= header_count {
            render_header_rows(
                table,
                &row_layouts,
                &col_widths,
                cm,
                table_left,
                pb,
                ctx,
                &merge_spans,
                header_count,
            );
        }
    };

    let mut did_flush_while_floating = false;
    // Set to the fresh page's body top when a floating table is pushed whole
    // onto it. The table's anchor paragraph flows from here even though the
    // cursor is left below the table, so its paragraph-relative shapes anchor
    // correctly. `None` while the table stays on its original page.
    let mut flushed_page_top: Option<f32> = None;
    // tblpY to apply to the render start of a vertAnchor="text" table (0 for
    // page/margin anchors). Raised before rendering, restored after, so the
    // table sits where Word puts it without shifting the following flow.
    let text_anchor_offset = override_pos
        .as_ref()
        .filter(|fp| fp.v_anchor_text)
        .map_or(0.0, |fp| fp.v_offset_pt);

    // Split an oversized row across pages, rendering partial rows and
    // flushing pages between chunks until every cell is fully emitted.
    let split_row_across_pages = |row: &TableRow,
                                   layout: &RowLayout,
                                   pb: &mut super::PageBuilder,
                                   ri: usize,
                                   did_flush: &mut bool,
                                   emb: &mut f32| {
        let ncells = layout.cells.len();
        let mut starts = vec![0usize; ncells];
        let mut is_first_chunk = true;

        loop {
            let avail = pb.slot_top - *emb;
            let mut ends = Vec::with_capacity(ncells);
            let mut all_done = true;

            for ci in 0..ncells {
                let end = find_cell_split(&layout.cells[ci], starts[ci], avail, cm);
                if end < layout.cells[ci].items.len() {
                    all_done = false;
                }
                ends.push(end);
            }

            let fill_to_bottom_y = if all_done { None } else { Some(*emb) };
            render_partial_row(
                row, layout, &col_widths, cm, table_left,
                pb, ctx, &starts, &ends, is_first_chunk, all_done,
                fill_to_bottom_y,
            );

            if all_done {
                break;
            }

            starts = ends;
            is_first_chunk = false;
            if is_floating {
                *did_flush = true;
            }
            flush_and_render_headers(pb, ri, emb);
        }
    };

    // A floating table whose first row doesn't fit in the space left on the
    // current page is pushed whole to the next page rather than overlapping the
    // bottom content. vertAnchor="text" tables flow with their anchor text, so
    // Word starts them on the next page; the per-row split path below can't
    // rescue this when the first row's cells aren't splittable (e.g. headers
    // that are OMML math). Re-anchor to the top of the fresh page. Setting
    // did_flush_while_floating leaves the cursor on the new page so the
    // following content flows below the table instead of behind it.
    // (Pendulum #172/#173: the data table was landing on page 1 over list
    // item 10, which also pushed the following illustration off-page.)
    if is_floating && !row_layouts.is_empty() {
        let eff_top = effective_slot_top(sp, pb.is_first_page_of_section, ctx);
        let at_page_top = (pb.slot_top - eff_top).abs() < 1.0;
        let available = pb.slot_top - *effective_margin_bottom;
        let total_h: f32 = row_layouts.iter().map(|r| r.height).sum();
        let page_content_h = eff_top - *effective_margin_bottom;
        // Keep the floating table together: when it doesn't fit in the space
        // left here but would fit on a fresh page, move the whole table to the
        // next page (re-anchoring to the top). Using the full height (not just
        // the first row) is robust to short header rows. Tables taller than a
        // full page fall through to the per-row split path below.
        if !at_page_top && total_h > available && total_h <= page_content_h {
            pb.flush_page(sect_idx);
            pb.is_first_page_of_section = false;
            pb.slot_top = effective_slot_top(sp, false, ctx);
            pb.column_top_y = pb.slot_top;
            *effective_margin_bottom = compute_effective_margin_bottom(sp, false, ctx);
            did_flush_while_floating = true;
            // The body top is where the anchor paragraph flows (and where its
            // paragraph-relative shapes anchor). The table itself, however,
            // honors tblpY relative to that anchor — for vertAnchor="text" a
            // negative tblpY lifts it above the top margin. Render the table from
            // the offset position; the flow cursor is restored to the un-offset
            // bottom afterwards so following content is unaffected.
            flushed_page_top = Some(pb.slot_top);
            pb.slot_top -= text_anchor_offset;
        }
    }

    for (ri, (row, layout)) in table.rows.iter().zip(row_layouts.iter()).enumerate() {
        // Pre-compute extra footnote space this row introduces, so the
        // page-break check below accounts for it before rendering.
        let mut row_fn_extra = 0.0f32;
        for &fn_id in &row_footnote_ids[ri] {
            if !pb.footnote_ids_set.contains(&fn_id) {
                if let Some(footnote) = footnotes.get(&fn_id) {
                    row_fn_extra += super::footnotes::compute_footnote_height(
                        footnote, ctx, fn_text_width,
                    );
                }
            }
        }
        if row_fn_extra > 0.0 && pb.footnote_ids.is_empty() {
            row_fn_extra += 12.0; // separator gap for first footnote on page
        }

        let row_h = layout.height;
        log::debug!(
            "TABLE row={} row_h={:.2} cells={} slot_top={:.2}",
            ri,
            row_h,
            layout.cells.len(),
            pb.slot_top
        );
        let eff_top = effective_slot_top(sp, pb.is_first_page_of_section, ctx);
        let eff_bottom = *effective_margin_bottom + row_fn_extra;
        let at_page_top = (pb.slot_top - eff_top).abs() < 1.0;
        let available_h = pb.slot_top - eff_bottom;
        let page_content_h = eff_top - eff_bottom;

        // Word splits a row across pages rather than pushing it whole when
        // keeping it together would waste most of the current page. We only
        // do this for oversized rows (taller than half a page) so short rows
        // still migrate cleanly; the cell also must have multiple breakable
        // items for the split to produce anything useful.
        let any_cell_multi_item = layout.cells.iter().any(|c| c.items.len() > 1);
        let can_meaningfully_split = !row.cant_split
            && any_cell_multi_item
            && !at_page_top
            && row_h > page_content_h * 0.5
            && available_h > page_content_h * 0.25;

        if row_h > available_h && (row_h > page_content_h || is_floating) && !row.cant_split {
            split_row_across_pages(row, layout, pb, ri, &mut did_flush_while_floating, effective_margin_bottom);
        } else if row_h > available_h && can_meaningfully_split {
            split_row_across_pages(row, layout, pb, ri, &mut did_flush_while_floating, effective_margin_bottom);
        } else if !at_page_top && row_h > available_h {
            if is_floating {
                did_flush_while_floating = true;
            }
            flush_and_render_headers(pb, ri, effective_margin_bottom);
            // After flushing + rendering header rows, re-check if the row
            // fits on the fresh page.  If repeating headers consumed enough
            // space that the row no longer fits, split it across pages
            // instead of rendering blindly (which would overflow the footer).
            let new_eff_top = effective_slot_top(sp, pb.is_first_page_of_section, ctx);
            let new_eff_bot = *effective_margin_bottom;
            let new_available = pb.slot_top - new_eff_bot;
            let new_page_h = new_eff_top - new_eff_bot;
            if row_h > new_available && (row_h > new_page_h || is_floating) && !row.cant_split {
                split_row_across_pages(row, layout, pb, ri, &mut did_flush_while_floating, effective_margin_bottom);
            } else {
                render_table_row(
                    row, layout, &col_widths, cm, table_left,
                    pb, ctx, ri, &merge_spans,
                );
            }
        } else {
            render_table_row(
                row,
                layout,
                &col_widths,
                cm,
                table_left,
                pb,
                ctx,
                ri,
                &merge_spans,
            );
        }

        // Register footnotes from this row and reserve space for them.
        for &fn_id in &row_footnote_ids[ri] {
            if pb.footnote_ids_set.insert(fn_id) {
                pb.footnote_ids.push(fn_id);
                if let Some(footnote) = footnotes.get(&fn_id) {
                    let fn_h = super::footnotes::compute_footnote_height(
                        footnote, ctx, fn_text_width,
                    );
                    let sep = if pb.footnote_ids.len() == 1 { 12.0 } else { 0.0 };
                    *effective_margin_bottom += sep + fn_h;
                }
            }
        }

        // Register endnotes from this row; they render at end of document
        // (last page), so just collect IDs in encounter order.
        for &en_id in &row_endnote_ids[ri] {
            if pb.endnote_ids_set.insert(en_id) {
                pb.endnote_ids.push(en_id);
            }
        }

        if pb.slot_top < *effective_margin_bottom - 1.0 {
            log::warn!(
                "Table overflow: row={} slot_top={:.2} < eff_margin_bottom={:.2} row_h={:.2} page={}",
                ri, pb.slot_top, *effective_margin_bottom, row_h, pb.all_contents.len(),
            );
        }
    }

    if let Some((saved, table_top_y)) = saved_slot_top {
        if did_flush_while_floating {
            // Table spanned multiple pages — cursor is already on the new page,
            // don't restore to the pre-table position or register a float zone.
            // The cursor stays below the table so following text flows below it
            // (not behind it). But the table's anchor paragraph — the next block,
            // which carries vertAnchor="text" shapes — must anchor its
            // paragraph-relative shapes from the top of the page body where the
            // anchor naturally flows, not from the cursor below the table. Hand
            // that top down as a one-shot override (pendulum graph + pendulum
            // illustrations were dropping by the table's height). Only the
            // whole-table-to-next-page path sets flushed_page_top; the per-row
            // split path (taller-than-page tables) leaves it None, so the
            // override is skipped there rather than anchoring shapes off-page.
            if let Some(top) = flushed_page_top {
                pb.pending_float_anchor = Some(top);
                // Undo the tblpY offset applied to the render start so the flow
                // cursor sits at the un-offset table bottom — following content
                // (which is correctly placed) must not shift with the table.
                pb.slot_top += text_anchor_offset;
            }
        } else {
        let table_total_w: f32 = col_widths.iter().sum();
        let (top_margin, bottom_margin) = text_margins;
        let table_bottom = pb.slot_top;

        // Always restore cursor to body text position — the float zone lets
        // paragraph layout decide whether to wrap beside or push below.
        pb.slot_top = saved;

        if table_bottom < saved {
            let fp = override_pos.as_ref().unwrap();
            // Use BothSides wrapping when the table has >=72pt of space on each side
            let text_area_left = sp.margin_left;
            let text_area_right = sp.page_width - sp.margin_right;
            let space_left = table_left - text_area_left;
            let space_right = text_area_right - (table_left + table_total_w);
            let wrap_text = if space_left >= 72.0 && space_right >= 72.0 {
                crate::model::WrapText::BothSides
            } else {
                crate::model::WrapText::Largest
            };
            pb.float_zone = Some(super::FloatZone {
                top_y: table_top_y + top_margin,
                bottom_y: table_bottom - bottom_margin,
                obj_left: table_left,
                obj_right: table_left + table_total_w,
                left_from_text: fp.left_from_text,
                right_from_text: fp.right_from_text,
                polygon_pts: None,
                wrap_text,
                para_relative: false,
            });
        }
        }
    }
}

pub(super) fn compute_hf_table_height(table: &Table, ctx: &RenderContext, content_w: f32) -> f32 {
    let mut col_widths = auto_fit_columns(table, ctx.fonts, None, None);
    apply_pct_width(table, &mut col_widths, content_w);
    let row_layouts = compute_row_layouts(table, &col_widths, ctx, None);
    row_layouts.iter().map(|r| r.height).sum()
}

pub(super) fn render_header_footer_table(
    table: &Table,
    sp: &SectionProperties,
    ctx: &RenderContext,
    content: &mut Content,
    cursor_y: &mut f32,
    page_num: usize,
    total_pages: usize,
    styleref_values: &HashMap<String, String>,
    page_num_format: Option<&str>,
    gradient_specs: &mut Vec<super::GradientSpec>,
) {
    let mut col_widths = auto_fit_columns(table, ctx.fonts, None, None);
    apply_pct_width(
        table,
        &mut col_widths,
        sp.page_width - sp.margin_left - sp.margin_right,
    );
    let hf_sub = HfSubstitution {
        page_num,
        total_pages,
        styleref_values,
        page_num_format,
    };
    let row_layouts = compute_row_layouts(table, &col_widths, ctx, Some(&hf_sub));
    let cm = &table.cell_margins;
    let table_left = {
        use crate::model::TableAlignment;
        let text_width = sp.page_width - sp.margin_left - sp.margin_right;
        let table_total_w: f32 = col_widths.iter().sum();
        match table.alignment {
            TableAlignment::Center => sp.margin_left + (text_width - table_total_w) / 2.0,
            TableAlignment::Right => sp.margin_left + text_width - table_total_w,
            TableAlignment::Left => sp.margin_left + table.table_indent - cm.left,
        }
    };

    let merge_spans = compute_merge_spans(table, &row_layouts);

    render_table_rows(
        table,
        &row_layouts,
        &col_widths,
        table_left,
        &merge_spans,
        content,
        cursor_y,
        ctx,
        gradient_specs,
    );
}