Skip to content

Commit 3b840f0

Browse files
committed
Cut PdfGenerator over to page-per-fragmentainer rendering (F1)
Replaces the old measure-once-then-scroll-offset-loop pagination (while (scrollOffset > -container.ActualSize.Height) { AddPage(); scrollOffset -= pageSize.Height; PerformPaint(g); }) with foreach (var fragmentainer in container.FragmentTree.Fragmentainers). The fragment tree is now what actually drives real PDF output, not just an internal structure nothing consumed yet - the first point in this port where that's true. Blank-page skipping (CSS Paged Media 3 3.2) falls out for free: a content-empty page slot is never materialized as a fragmentainer (see FragmentEmitter), so it's simply absent from this loop instead of needing to be detected and special-cased. HandleLinks no longer maps a link's document-Y to a page via a bare pageSize.Height multiply/divide - slot indices aren't contiguous once blank-page skipping is live. It now builds a slot-to-page-index map from the materialized fragmentainers and tests each link's rectangle against each fragmentainer's own Geometry band. HtmlRenderer.PdfSharp gains InternalsVisibleTo access to the core assembly (matching the existing WinForms/WPF grant) so it can reach HtmlContainerInt.FragmentTree and the new PerformPaint(RGraphics, FragmentainerFragment) overload - both stay internal rather than becoming public API while this port is still underway. Found and fixed a real bug in FragmentEmitter while wiring this up: Finish() computed the last page slot from container.ActualSize.Height as if it were an absolute document-Y coordinate, but ActualSize.Height is document height *excluding* the root box's own top offset (ActualSize.Height = ActualBottom - Root.Location.Y) - using it directly double-subtracted MarginTop inside PageIndexOf and silently under-reported the fragment tree's page count whenever content's true bottom landed just past a boundary ActualSize.Height alone hadn't yet crossed. This had been latent since D1/D2 (FragmentTree was structurally present but never checked against real PDF page counts) and was only caught here because F1 is the first place the fragment tree's own page count actually has to be correct, not just non-empty. New StageF1VerificationTest.cs: web/anchor links across pages don't throw and produce link annotations, and a huge-margin document produces no run of blank pages through the real pipeline. Full existing suite (35 image-diff/fragment tests + 15 PDF/PdfSharp tests, up from 13 now that the new pipeline exercises every prior stage's page-count assertions for real) green.
1 parent 7f30f40 commit 3b840f0

5 files changed

Lines changed: 154 additions & 27 deletions

File tree

‎Source/HtmlRenderer.PdfSharp/HtmlContainer.cs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,31 @@ public void PerformPaint(XGraphics g)
349349
}
350350
}
351351

352+
/// <summary>
353+
/// The immutable fragment tree layout produced from the box tree on the last <see cref="PerformLayout"/>
354+
/// call - one fragmentainer per real page the document spans. Null before the first layout.
355+
/// </summary>
356+
internal Core.Fragments.FragmentTree FragmentTree
357+
{
358+
get { return _htmlContainerInt.FragmentTree; }
359+
}
360+
361+
/// <summary>
362+
/// Render one fragmentainer using the given device, reading from the immutable fragment tree
363+
/// rather than walking the mutable box tree directly.
364+
/// </summary>
365+
/// <param name="g">the device to use to render</param>
366+
/// <param name="fragmentainer">the fragmentainer to paint</param>
367+
internal void PerformPaint(XGraphics g, Core.Fragments.FragmentainerFragment fragmentainer)
368+
{
369+
ArgChecker.AssertArgNotNull(g, "g");
370+
371+
using (var ig = new GraphicsAdapter(g))
372+
{
373+
_htmlContainerInt.PerformPaint(ig, fragmentainer);
374+
}
375+
}
376+
352377
public void Dispose()
353378
{
354379
_htmlContainerInt.Dispose();

‎Source/HtmlRenderer.PdfSharp/PdfGenerator.cs‎

Lines changed: 56 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@
1414
using PdfSharp.Drawing;
1515
using PdfSharp.Pdf;
1616
using System;
17+
using System.Collections.Generic;
1718
using System.Threading.Tasks;
1819
using TheArtOfDev.HtmlRenderer.Adapters;
1920
using TheArtOfDev.HtmlRenderer.Core;
2021
using TheArtOfDev.HtmlRenderer.Core.Entities;
22+
using TheArtOfDev.HtmlRenderer.Core.Fragments;
2123
using TheArtOfDev.HtmlRenderer.Core.Utils;
2224
using TheArtOfDev.HtmlRenderer.PdfSharp.Adapters;
2325

@@ -195,9 +197,14 @@ public static async Task AddPdfPages(PdfDocument document, string html, PdfGener
195197
container.PerformLayout(measure);
196198
}
197199

198-
// while there is un-rendered HTML, create another PDF page and render with proper offset for the next page
199-
double scrollOffset = 0;
200-
while (scrollOffset > -container.ActualSize.Height)
200+
// One PDF page per fragmentainer the fragment tree actually materialized - a
201+
// content-empty page slot (CSS Paged Media 3 3.2, e.g. a huge margin that would
202+
// otherwise paginate through blank vertical space - see the margin-truncation
203+
// correction in BlockFragmentation) is simply never in this list, which is what
204+
// gives blank-page skipping for free here instead of the old ceil(height/pageHeight)
205+
// loop's naive page count.
206+
var tree = container.FragmentTree;
207+
foreach (var fragmentainer in tree?.Fragmentainers ?? (IReadOnlyList<FragmentainerFragment>)Array.Empty<FragmentainerFragment>())
201208
{
202209
var page = document.AddPage();
203210
page.Height = XUnit.FromPoint(orgPageSize.Height);
@@ -206,17 +213,14 @@ public static async Task AddPdfPages(PdfDocument document, string html, PdfGener
206213

207214
using (var g = XGraphics.FromPdfPage(page))
208215
{
209-
//g.IntersectClip(new XRect(config.MarginLeft, config.MarginTop, pageSize.Width, pageSize.Height));
210216
g.IntersectClip(new XRect(0, 0, page.Width.Point, page.Height.Point));
211217

212-
container.ScrollOffset = new XPoint(0, scrollOffset);
213-
container.PerformPaint(g);
218+
container.PerformPaint(g, fragmentainer);
214219
}
215-
scrollOffset -= pageSize.Height;
216220
}
217221

218222
// add web links and anchors
219-
HandleLinks(document, container, orgPageSize, pageSize);
223+
HandleLinks(document, container, orgPageSize, tree);
220224
}
221225
}
222226
}
@@ -228,44 +232,74 @@ public static async Task AddPdfPages(PdfDocument document, string html, PdfGener
228232
/// <summary>
229233
/// Handle HTML links by create PDF Documents link either to external URL or to another page in the document.
230234
/// </summary>
231-
private static void HandleLinks(PdfDocument document, HtmlContainer container, XSize orgPageSize, XSize pageSize)
235+
private static void HandleLinks(PdfDocument document, HtmlContainer container, XSize orgPageSize, FragmentTree tree)
232236
{
237+
if (tree == null || tree.Fragmentainers.Count == 0)
238+
return;
239+
240+
// Pagination slot -> PDF page index. Not a bare multiply/divide by page height any more:
241+
// a content-empty slot is never materialized as a fragmentainer at all (blank-page
242+
// skipping), so slot indices are not contiguous across tree.Fragmentainers the way a
243+
// fixed-size page grid's would be.
244+
var slotToPage = new Dictionary<int, int>();
245+
for (var pageIndex = 0; pageIndex < tree.Fragmentainers.Count; pageIndex++)
246+
{
247+
slotToPage[tree.Fragmentainers[pageIndex].SlotIndex] = pageIndex;
248+
}
249+
233250
foreach (var link in container.GetLinks())
234251
{
235-
int i = (int)(link.Rectangle.Top / pageSize.Height);
236-
for (; i < document.Pages.Count && pageSize.Height * i < link.Rectangle.Bottom; i++)
252+
foreach (var fragmentainer in tree.Fragmentainers)
237253
{
238-
var offset = pageSize.Height * i;
254+
var bandTop = fragmentainer.Geometry.Top;
255+
var bandBottom = bandTop + fragmentainer.Geometry.Height;
256+
if (link.Rectangle.Top >= bandBottom || link.Rectangle.Bottom <= bandTop)
257+
continue; // this link has no part on this fragmentainer's page
258+
259+
var pageIndex = slotToPage[fragmentainer.SlotIndex];
239260

240261
// fucking position is from the bottom of the page
241-
var xRect = new XRect(link.Rectangle.Left, orgPageSize.Height - (link.Rectangle.Height + link.Rectangle.Top - offset), link.Rectangle.Width, link.Rectangle.Height);
262+
var xRect = new XRect(link.Rectangle.Left, orgPageSize.Height - (link.Rectangle.Height + link.Rectangle.Top - bandTop), link.Rectangle.Width, link.Rectangle.Height);
242263

243264
if (link.IsAnchor)
244265
{
245266
// create link to another page in the document
246267
var anchorRect = container.GetElementRectangle(link.AnchorId);
247268
if (anchorRect.HasValue)
248269
{
270+
var anchorSlot = SlotContaining(tree, anchorRect.Value.Top);
249271
// document links to the same page as the link is not allowed
250-
int anchorPageIdx = (int)(anchorRect.Value.Top / pageSize.Height);
251-
252-
// in case that not find the page index, set to the first page.
253-
if (anchorPageIdx == 0)
254-
anchorPageIdx = 1;
255-
256-
if (i != anchorPageIdx)
257-
document.Pages[i].AddDocumentLink(new PdfRectangle(xRect), anchorPageIdx);
272+
if (anchorSlot.HasValue && slotToPage.TryGetValue(anchorSlot.Value, out var anchorPageIdx) && pageIndex != anchorPageIdx)
273+
{
274+
document.Pages[pageIndex].AddDocumentLink(new PdfRectangle(xRect), anchorPageIdx);
275+
}
258276
}
259277
}
260278
else
261279
{
262280
// create link to URL
263-
document.Pages[i].AddWebLink(new PdfRectangle(xRect), link.Href);
281+
document.Pages[pageIndex].AddWebLink(new PdfRectangle(xRect), link.Href);
264282
}
265283
}
266284
}
267285
}
268286

287+
/// <summary>
288+
/// The pagination slot whose content band contains document-space Y coordinate <paramref name="y"/>,
289+
/// or null if it falls in no materialized fragmentainer's band (e.g. an anchor inside a
290+
/// content-empty page slot that was skipped, or past the end of the document).
291+
/// </summary>
292+
private static int? SlotContaining(FragmentTree tree, double y)
293+
{
294+
foreach (var fragmentainer in tree.Fragmentainers)
295+
{
296+
var bandTop = fragmentainer.Geometry.Top;
297+
if (y >= bandTop && y < bandTop + fragmentainer.Geometry.Height)
298+
return fragmentainer.SlotIndex;
299+
}
300+
return null;
301+
}
302+
269303
#endregion
270304
}
271305
}

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,13 @@ internal FragmentTree Finish()
4646
return new FragmentTree(new List<FragmentainerFragment> { fragmentainer });
4747
}
4848

49-
var lastSlot = _container.PageIndexOf(Math.Max(0, _container.ActualSize.Height - Epsilon));
49+
// root.ActualBottom (Location.Y + Size.Height), not _container.ActualSize.Height: the
50+
// latter is document height *excluding* the root's own top offset (ActualSize.Height =
51+
// ActualBottom - Root.Location.Y, set at the end of CssBox.PerformLayoutImp/Epilogue), so
52+
// using it directly here as an absolute Y would double-subtract MarginTop inside
53+
// PageIndexOf and under-report the last slot whenever content's true bottom lands just
54+
// past a page boundary that ActualSize.Height alone doesn't yet cross.
55+
var lastSlot = _container.PageIndexOf(Math.Max(0, root.ActualBottom - Epsilon));
5056
var fragmentainers = new List<FragmentainerFragment>();
5157

5258
for (var slot = 0; slot <= lastSlot; slot++)

‎Source/HtmlRenderer/HtmlRenderer.csproj‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,16 @@ For existing implementations see: HtmlRenderer.WinForms, HtmlRenderer.WPF and Ht
2626
<None Include="..\..\README.md" Pack="true" PackagePath="\" />
2727
</ItemGroup>
2828
<ItemGroup>
29-
<!-- Grants the WinForms/WPF adapters (which read SystemColorSchemeOverride from their own
30-
SystemColorScheme override) and the image-regression test assembly (which sets it) access to
31-
RAdapter's internal members. SystemColorSchemeOverride is a test-only seam that makes
32-
prefers-color-scheme rendering deterministic regardless of the host machine's own theme setting. -->
29+
<!-- Grants the WinForms/WPF/PdfSharp adapters access to internal members: originally just
30+
RAdapter.SystemColorSchemeOverride (a test-only seam that makes prefers-color-scheme
31+
rendering deterministic regardless of the host machine's own theme setting), now also
32+
HtmlContainerInt.FragmentTree and its FragmentainerFragment-based PerformPaint overload -
33+
the fragment tree stays internal rather than becoming public API while this port is still
34+
underway. The image-regression test assembly also needs this (it sets the color-scheme
35+
override and reaches deep into layout/fragment internals for precision assertions). -->
3336
<InternalsVisibleTo Include="HtmlRenderer.WinForms" />
3437
<InternalsVisibleTo Include="HtmlRenderer.WPF" />
38+
<InternalsVisibleTo Include="HtmlRenderer.PdfSharp" />
3539
<InternalsVisibleTo Include="HtmlRenderer.IntegrationTest" />
3640
</ItemGroup>
3741
<ItemGroup>
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
using PdfSharp;
2+
using TheArtOfDev.HtmlRenderer.PdfSharp;
3+
4+
namespace HtmlRenderer.PdfSharp.Test;
5+
6+
[TestClass]
7+
public sealed class StageF1VerificationTest
8+
{
9+
[TestMethod]
10+
public async Task WebLinkAndAnchorLink_AcrossPages_DoNotThrow()
11+
{
12+
var config = new PdfGenerateConfig { PageSize = PageSize.A4 };
13+
config.SetMargins(20);
14+
15+
var filler = string.Concat(Enumerable.Repeat("<p style='margin:0;'>filler line of text</p>", 60));
16+
var html = $"""
17+
<html><body>
18+
<a href="https://example.com">external link on page one</a>
19+
<a href="#target">jump to anchor</a>
20+
{filler}
21+
<p id="target">anchor target, on a later page</p>
22+
</body></html>
23+
""";
24+
25+
using var document = await PdfGenerator.GeneratePdf(html, config);
26+
27+
Assert.IsGreaterThan(1, document.Pages.Count);
28+
29+
// At least one page carries some link annotation (either the web link or the document link) -
30+
// this is a smoke check that HandleLinks' new slot-to-page mapping runs without throwing and
31+
// actually attaches annotations, not a check of which exact page holds which link.
32+
var anyLinks = false;
33+
for (var i = 0; i < document.PageCount; i++)
34+
{
35+
if (document.Pages[i].Annotations.Count > 0)
36+
{
37+
anyLinks = true;
38+
break;
39+
}
40+
}
41+
Assert.IsTrue(anyLinks, "expected at least one page to carry a link annotation");
42+
}
43+
44+
[TestMethod]
45+
public async Task HugeMargin_ProducesNoBlankPages()
46+
{
47+
var config = new PdfGenerateConfig { PageSize = PageSize.A4 };
48+
config.SetMargins(20);
49+
50+
const string html = "<html><body><div style='margin-top:2000pt;'>content</div></body></html>";
51+
52+
using var document = await PdfGenerator.GeneratePdf(html, config);
53+
54+
// css-break-3 5.2 margin truncation (D2) keeps this on very few pages; blank-page skipping
55+
// (F1's page-per-fragmentainer loop) means whatever pages exist are never content-empty.
56+
Assert.IsLessThanOrEqualTo(2, document.Pages.Count);
57+
}
58+
}

0 commit comments

Comments
 (0)