Skip to content

Commit 7f30f40

Browse files
committed
Add table fragmentation: row-level avoidance and repeated <thead> (D4)
Two independent corrections, both gated on a real page grid: - Row-level break-inside: avoid (or the legacy page-break-inside) on the table itself: replaces the old crude per-cell CssRect.BreakPage retry loop (which re-ran the whole row from scratch via a decrement- and-continue) with the same local shift-the-whole-row-down approach D2 uses for blocks, built on the real page-grid math instead of BreakPage's modulo arithmetic. Rows aren't avoided from splitting by default - css-tables-3 6.1 permits a row to fragment (each cell independently), which already happens correctly with no correction at all, since a cell's own content already flows across the boundary via BlockFragmentation/InlineFragmentation. - Repeated <thead> (css-tables-3 6.2), gated on the header carrying an avoiding break-inside (the UA default stylesheet sets this - see the earlier "bring in PeachPDF's fragmentation UA defaults" commit). Unlike everything in D2/D3, this genuinely needs layout-time space reservation, not just a local position shift: painting a repeated header on top of a body row that already flows into that space would overlap it. CssLayoutEngineTable's row loop now reserves headerHeight at the top of every continuation page before positioning that page's first row, and builds a detached clone of the header's rows there via the new TableHeaderRepeat helper - real cloned CssBox instances (not a fragment-tree-only proxy, so the repeat is visible through both the existing scroll-offset PDF pipeline and the new fragment tree without teaching two rendering paths about "one source, several positions"). Clones are stored on a new CssBox.RepeatedHeaderRows list - not part of Boxes, so re-running table layout can never mistake them for real content - and painted/emitted the same way CssBox.ListItemBox already is, in both CssBox.PaintImp and FragmentEmitter. Found and fixed one real positioning bug while wiring this up: a <tr> box's own Location is never assigned by the row loop (only its cells' is), so using the source header row's Location as a clone's positioning reference silently offset every repeat by however far that stale value happened to be from the row's true rendered top - fixed by referencing the row's first cell instead, caught by a precision test asserting the repeat lands exactly at its page's content top, not off by that stale offset. New tests: StageD4RepeatedHeaderTest.cs (precise inspection - text content matches, position is exactly flush at each continuation page's top, never repeated onto the table's own first page) and StageD4VerificationTest.cs (PdfSharp: a 60-row table with a header spans multiple real PDF pages without error). Full existing suite (35 image-diff/fragment tests + 13 PDF/PdfSharp tests) unaffected.
1 parent 90729d4 commit 7f30f40

6 files changed

Lines changed: 289 additions & 19 deletions

File tree

‎Source/HtmlRenderer/Core/Dom/CssBox.cs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,15 @@ internal CssBox ListItemBox
8383
get { return _listItemBox; }
8484
}
8585

86+
/// <summary>
87+
/// For a table box only: detached clones of the table's own &lt;thead&gt; rows, one set per
88+
/// continuation page the table's body spans (css-tables-3 6.2's repeated headers) - not part
89+
/// of <see cref="Boxes"/> (so re-running table layout can never mistake them for real body
90+
/// content), rebuilt from scratch on every layout pass by <see cref="Fragmentation.TableHeaderRepeat"/>.
91+
/// Null when the table has no header or never crosses a page boundary.
92+
/// </summary>
93+
internal List<CssBox> RepeatedHeaderRows { get; set; }
94+
8695
private CssLineBox _firstHostingLineBox;
8796
private CssLineBox _lastHostingLineBox;
8897

@@ -1467,6 +1476,14 @@ protected virtual void PaintImp(RGraphics g)
14671476
{
14681477
_listItemBox.Paint(g);
14691478
}
1479+
1480+
if (RepeatedHeaderRows != null)
1481+
{
1482+
foreach (var repeatedRow in RepeatedHeaderRows)
1483+
{
1484+
repeatedRow.Paint(g);
1485+
}
1486+
}
14701487
}
14711488
}
14721489

‎Source/HtmlRenderer/Core/Dom/CssLayoutEngineTable.cs‎

Lines changed: 64 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
using TheArtOfDev.HtmlRenderer.Adapters;
1616
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
1717
using TheArtOfDev.HtmlRenderer.Core.Entities;
18+
using TheArtOfDev.HtmlRenderer.Core.Fragmentation;
1819
using TheArtOfDev.HtmlRenderer.Core.Parse;
1920
using TheArtOfDev.HtmlRenderer.Core.Utils;
2021

@@ -624,12 +625,56 @@ private void LayoutCells(RGraphics g)
624625
_tableBox.Location = new RPoint(startx - _tableBox.ActualBorderLeftWidth - _tableBox.ActualPaddingLeft - GetHorizontalSpacing(), _tableBox.Location.Y);
625626
}
626627

628+
// css-tables-3 6.2: a <thead> repeats on every page the table's body/footer spans, where
629+
// the group carries an avoiding break-inside (the UA default stylesheet sets this).
630+
// Reserving the room here, before the first row of each continuation page is positioned,
631+
// is what keeps that row from being drawn underneath the repeated header instead of below
632+
// it - a fragment-tree-only repeat (no reservation) would just overlap real content.
633+
var pageGridContainer = _tableBox.HtmlContainer;
634+
var repeatsHeader = pageGridContainer != null && pageGridContainer.HasRealPageGrid
635+
&& _headerBox != null && BreakValues.AvoidsBreak(_headerBox.BreakInside);
636+
var headerRowCount = _headerBox?.Boxes.Count ?? 0;
637+
double headerHeight = 0;
638+
int? lastRepeatSlot = null;
639+
_tableBox.RepeatedHeaderRows = null;
640+
627641
for (int i = 0; i < _allRows.Count; i++)
628642
{
643+
if (repeatsHeader && i == headerRowCount)
644+
{
645+
// The header's own rows (i = 0..headerRowCount-1) just finished; maxBottom is
646+
// still theirs. Its own page is never itself a "repeat" - the header is already
647+
// there once, in flow.
648+
headerHeight = maxBottom - starty;
649+
lastRepeatSlot = pageGridContainer.PageIndexOf(starty);
650+
}
651+
652+
if (repeatsHeader && i >= headerRowCount && lastRepeatSlot.HasValue)
653+
{
654+
var slot = pageGridContainer.PageIndexOf(cury);
655+
if (slot > lastRepeatSlot.Value)
656+
{
657+
var pageTop = pageGridContainer.PageTopOf(slot);
658+
cury = pageTop + headerHeight;
659+
lastRepeatSlot = slot;
660+
661+
_tableBox.RepeatedHeaderRows ??= new List<CssBox>();
662+
for (var hi = 0; hi < headerRowCount; hi++)
663+
{
664+
var sourceRow = _allRows[hi];
665+
// A <tr> box's own Location is never assigned by this row loop (only its
666+
// cells' is) - the first cell is the real reference point for "where this
667+
// header row actually renders".
668+
var sourceRenderedTop = sourceRow.Boxes.Count > 0 ? sourceRow.Boxes[0].Location.Y : starty;
669+
var targetTop = pageTop + (sourceRenderedTop - starty);
670+
_tableBox.RepeatedHeaderRows.Add(TableHeaderRepeat.CloneAndPosition(sourceRow, sourceRenderedTop, targetTop));
671+
}
672+
}
673+
}
674+
629675
var row = _allRows[i];
630676
double curx = startx;
631677
int curCol = 0;
632-
bool breakPage = false;
633678

634679
for (int j = 0; j < row.Boxes.Count; j++)
635680
{
@@ -676,30 +721,31 @@ private void LayoutCells(RGraphics g)
676721
spacer.ExtendedBox.ActualBottom = maxBottom;
677722
CssLayoutEngine.ApplyCellVerticalAlignment(g, spacer.ExtendedBox);
678723
}
724+
}
679725

680-
// If one cell crosses page borders then don't need to check other cells in the row
681-
if (_tableBox.PageBreakInside == CssConstants.Avoid)
726+
// break-inside: avoid (or the legacy page-break-inside) on the table: if this row
727+
// straddles a page boundary and fits whole on one page, shift the whole row - not
728+
// just one cell - down to the next page's content top. Rows aren't avoided from
729+
// splitting by default (css-tables-3 6.1 permits a row to fragment, each cell
730+
// independently, which is what happens here with no correction: a cell's own content
731+
// already flows across the boundary via BlockFragmentation/InlineFragmentation) -
732+
// only when the table author actually asked for it.
733+
if (pageGridContainer != null && pageGridContainer.HasRealPageGrid && BreakValues.AvoidsBreak(_tableBox.BreakInside)
734+
&& maxBottom > cury)
735+
{
736+
var topSlot = pageGridContainer.PageIndexOf(cury);
737+
var bottomSlot = pageGridContainer.PageIndexOf(Math.Max(cury, maxBottom - 0.01));
738+
if (bottomSlot > topSlot && maxBottom - cury < pageGridContainer.PageSize.Height)
682739
{
683-
breakPage = cell.BreakPage();
684-
if (breakPage)
740+
var delta = pageGridContainer.PageTopOf(topSlot + 1) - cury;
741+
foreach (CssBox cell in row.Boxes)
685742
{
686-
cury = cell.Location.Y;
687-
break;
743+
cell.OffsetTop(delta);
688744
}
745+
maxBottom += delta;
689746
}
690747
}
691748

692-
if (breakPage) // go back to move the whole row to the next page
693-
{
694-
if (i == 1) // do not leave single row in previous page
695-
i = -1; // Start layout from the first row on new page
696-
else
697-
i--;
698-
699-
maxBottom = 0;
700-
continue;
701-
}
702-
703749
cury = maxBottom + GetVerticalSpacing();
704750

705751
currentrow++;

‎Source/HtmlRenderer/Core/Fragmentation/FragmentEmitter.cs‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,17 @@ private static bool HasContentInBand(CssBox box, PageBand band)
100100
if (HasContentInBand(child, band)) return true;
101101
}
102102

103-
return box.ListItemBox != null && HasContentInBand(box.ListItemBox, band);
103+
if (box.ListItemBox != null && HasContentInBand(box.ListItemBox, band)) return true;
104+
105+
if (box.RepeatedHeaderRows != null)
106+
{
107+
foreach (var repeatedRow in box.RepeatedHeaderRows)
108+
{
109+
if (HasContentInBand(repeatedRow, band)) return true;
110+
}
111+
}
112+
113+
return false;
104114
}
105115

106116
/// <summary>
@@ -144,6 +154,15 @@ private BoxFragment BuildBoxFragment(CssBox box, int fragmentainerIndex, PageBan
144154
children.Add(BuildBoxFragment(child, fragmentainerIndex, band));
145155
}
146156

157+
if (box.RepeatedHeaderRows != null)
158+
{
159+
foreach (var repeatedRow in box.RepeatedHeaderRows)
160+
{
161+
if (HasContentInBand(repeatedRow, band))
162+
children.Add(BuildBoxFragment(repeatedRow, fragmentainerIndex, band));
163+
}
164+
}
165+
147166
var rect = ToLocal(Clip(box.Bounds, band), band);
148167
var wholeBoxRect = ToLocal(box.Bounds, band);
149168

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
using TheArtOfDev.HtmlRenderer.Core.Dom;
2+
3+
namespace TheArtOfDev.HtmlRenderer.Core.Fragmentation
4+
{
5+
/// <summary>
6+
/// Builds the detached row clones <see cref="CssBox.RepeatedHeaderRows"/> holds - css-tables-3
7+
/// 6.2's repeated &lt;thead&gt; content, one clone per continuation page a table's body spans.
8+
/// </summary>
9+
/// <remarks>
10+
/// Unlike PeachPDF's proxy-based approach (a shared source subtree re-emitted at each page's
11+
/// position purely at the fragment-tree level), this clones real, laid-out <see cref="CssBox"/>
12+
/// instances. That's a deliberate simplification for this port: it makes the repeat visible
13+
/// through both the existing scroll-offset PDF pipeline and the new fragment tree without
14+
/// teaching two different rendering paths about "one source, several positions" - at the cost of
15+
/// only reproducing what a clone can cheaply carry over (a header's own decoration and words;
16+
/// multi-line per-box decoration rectangles inside a header cell are not reproduced, since that
17+
/// needs cloning CssLineBox instances too - an accepted gap for the common single-line-header
18+
/// case this feature targets).
19+
/// </remarks>
20+
internal static class TableHeaderRepeat
21+
{
22+
/// <summary>
23+
/// Clones <paramref name="source"/> (a &lt;thead&gt; row, recursively with its cells and their
24+
/// content) and shifts the clone so the row's rendered top - <paramref name="sourceRenderedTop"/>,
25+
/// the caller's own reference, since a &lt;tr&gt; box's own Location is never assigned by table
26+
/// layout (only its cells' is - see <see cref="Dom.CssLayoutEngineTable"/>'s row loop) - lands
27+
/// at <paramref name="targetTop"/>. The clone is fully detached - not part of any box's
28+
/// <see cref="CssBox.Boxes"/> - so re-running table layout can never mistake it for real content.
29+
/// </summary>
30+
internal static CssBox CloneAndPosition(CssBox source, double sourceRenderedTop, double targetTop)
31+
{
32+
var clone = CloneSubtree(source, null);
33+
var delta = targetTop - sourceRenderedTop;
34+
if (delta != 0)
35+
clone.OffsetTop(delta);
36+
return clone;
37+
}
38+
39+
private static CssBox CloneSubtree(CssBox source, CssBox newParent)
40+
{
41+
var clone = new CssBox(newParent, source.HtmlTag);
42+
clone.InheritStyle(source, everything: true);
43+
clone.HtmlContainer = source.HtmlContainer;
44+
clone.Location = source.Location;
45+
clone.Size = source.Size;
46+
clone.ActualBottom = source.ActualBottom;
47+
clone.ActualRight = source.ActualRight;
48+
49+
if (source.Words.Count > 0)
50+
{
51+
clone.Text = source.Text;
52+
clone.ParseToWords();
53+
54+
// Reuses the source's already-measured word geometry rather than re-measuring - the
55+
// clone's tokenization matches the source's own (same Text, same ParseToWords), so a
56+
// positional pairing is safe here.
57+
var count = clone.Words.Count < source.Words.Count ? clone.Words.Count : source.Words.Count;
58+
for (var i = 0; i < count; i++)
59+
{
60+
clone.Words[i].Left = source.Words[i].Left;
61+
clone.Words[i].Top = source.Words[i].Top;
62+
clone.Words[i].Width = source.Words[i].Width;
63+
clone.Words[i].Height = source.Words[i].Height;
64+
}
65+
}
66+
67+
foreach (var child in source.Boxes)
68+
{
69+
CloneSubtree(child, clone);
70+
}
71+
72+
return clone;
73+
}
74+
}
75+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
using System.Drawing;
2+
using System.Reflection;
3+
using System.Text;
4+
using Microsoft.VisualStudio.TestTools.UnitTesting;
5+
using TheArtOfDev.HtmlRenderer.Core;
6+
using TheArtOfDev.HtmlRenderer.Core.Utils;
7+
using TheArtOfDev.HtmlRenderer.WinForms;
8+
9+
namespace TheArtOfDev.HtmlRenderer.IntegrationTest;
10+
11+
// See StageD2FragmentBucketingSmokeTest for why this opts out of this assembly's default
12+
// method-level parallelization (MSTestSettings.cs).
13+
[TestClass]
14+
[DoNotParallelize]
15+
public sealed class StageD4RepeatedHeaderTest
16+
{
17+
[TestMethod]
18+
public void ThreadRepeatsOnEveryPageTheTableSpans()
19+
{
20+
// break-inside: avoid is explicit here rather than relied on from the UA default stylesheet's
21+
// "@media print { thead, tfoot { break-inside: avoid } }" - this test renders via WinForms,
22+
// whose adapter reports a "screen" media type, so that print-scoped rule never matches here
23+
// (confirmed intentional: only PdfSharpAdapter overrides DefaultMediaType to "print").
24+
var sb = new StringBuilder("<html><body><table border='1'><thead style='break-inside:avoid;'><tr><th>Col A</th><th>Col B</th></tr></thead><tbody>");
25+
for (var i = 0; i < 60; i++)
26+
{
27+
sb.Append($"<tr><td style='height:20px;'>row {i} a</td><td>row {i} b</td></tr>");
28+
}
29+
sb.Append("</tbody></table></body></html>");
30+
31+
using var wrapper = new HtmlContainer();
32+
wrapper.SetHtml(sb.ToString()).GetAwaiter().GetResult();
33+
34+
var prop = typeof(HtmlContainer).GetProperty("HtmlContainerInt", BindingFlags.NonPublic | BindingFlags.Instance)!;
35+
var container = (HtmlContainerInt)prop.GetValue(wrapper)!;
36+
container.PageSize = new TheArtOfDev.HtmlRenderer.Adapters.Entities.RSize(500, 700);
37+
container.MarginTop = 0;
38+
wrapper.MaxSize = new SizeF(500, 0);
39+
40+
using var bitmap = new Bitmap(500, 5000);
41+
using var g = Graphics.FromImage(bitmap);
42+
wrapper.PerformLayout(g);
43+
44+
var table = DomUtils.GetBoxByTagName(container.Root, "table");
45+
Assert.IsNotNull(table);
46+
47+
// The table must genuinely span multiple pages for this test to be meaningful.
48+
Assert.IsTrue(container.PageIndexOf(table.ActualBottom - 0.01) > container.PageIndexOf(table.Location.Y),
49+
"expected the table to span more than one page");
50+
51+
Assert.IsNotNull(table.RepeatedHeaderRows, "expected at least one repeated header row set");
52+
Assert.IsTrue(table.RepeatedHeaderRows.Count > 0);
53+
54+
// Each repeated row's text content should match the original header's text (Col A / Col B).
55+
var headerRow = table.RepeatedHeaderRows[0];
56+
var text = string.Join(" ", CollectWords(headerRow));
57+
StringAssert.Contains(text, "Col A");
58+
StringAssert.Contains(text, "Col B");
59+
60+
// Every repeated header must land at the top of a page slot the table's body actually spans,
61+
// and must not be positioned on the table's own first page (it's already there once, in flow).
62+
// The row itself carries no Location (only its cells do - see CssLayoutEngineTable's row loop),
63+
// so the first cell is the reference point.
64+
var firstSlot = container.PageIndexOf(table.Location.Y);
65+
var slot = container.PageIndexOf(headerRow.Boxes[0].Location.Y);
66+
Assert.IsTrue(slot > firstSlot, "repeated header should not land back on the table's own first page");
67+
Assert.AreEqual(container.PageTopOf(slot), headerRow.Boxes[0].Location.Y, 0.5, "repeated header should sit flush at its page's content top");
68+
}
69+
70+
private static System.Collections.Generic.IEnumerable<string> CollectWords(TheArtOfDev.HtmlRenderer.Core.Dom.CssBox box)
71+
{
72+
foreach (var word in box.Words)
73+
{
74+
if (!string.IsNullOrWhiteSpace(word.Text))
75+
yield return word.Text;
76+
}
77+
foreach (var child in box.Boxes)
78+
{
79+
foreach (var w in CollectWords(child))
80+
yield return w;
81+
}
82+
}
83+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using PdfSharp;
2+
using TheArtOfDev.HtmlRenderer.PdfSharp;
3+
4+
namespace HtmlRenderer.PdfSharp.Test;
5+
6+
[TestClass]
7+
public sealed class StageD4VerificationTest
8+
{
9+
[TestMethod]
10+
public async Task LargeTableWithHeader_SpansMultiplePagesWithoutError()
11+
{
12+
var config = new PdfGenerateConfig { PageSize = PageSize.A4 };
13+
config.SetMargins(20);
14+
15+
var rows = string.Concat(Enumerable.Range(0, 60)
16+
.Select(i => $"<tr><td>row {i} a</td><td>row {i} b</td></tr>"));
17+
var html = $"""
18+
<html><body>
19+
<table border="1" style="width:100%;">
20+
<thead><tr><th>Column A</th><th>Column B</th></tr></thead>
21+
<tbody>{rows}</tbody>
22+
</table>
23+
</body></html>
24+
""";
25+
26+
using var document = await PdfGenerator.GeneratePdf(html, config);
27+
28+
Assert.IsGreaterThan(1, document.Pages.Count);
29+
}
30+
}

0 commit comments

Comments
 (0)