Skip to content

feat: add a paginated PDF exporter in KumikoUI.SkiaSharp (#340) - #502

Open
michaelstonis wants to merge 4 commits into
mainfrom
feat/340-pdf-exporter
Open

michaelstonis wants to merge 4 commits into
mainfrom
feat/340-pdf-exporter

Conversation

@michaelstonis

Copy link
Copy Markdown
Contributor

Closes #340.

Changes

A paginated PDF exporter in KumikoUI.SkiaSharp, built on the format-neutral export core (IKumikoExporter, KumikoExportSnapshot, KumikoExportOptions) that CSV and Excel use. Pages are drawn with SkiaSharp's SKDocument PDF backend through a SkiaDrawingContext over the exporter's own SkiaResourceCache, so text gets the same registered fonts, fallback families and emoji shaping as the screen, and the fonts used are embedded as subsets.

The table has its own layout, independent of KumikoRenderer and KumikoLayoutEngine (no renderer, layout engine, input controller or hit tester file is touched):

  • Export/Internal/PdfLayout: page geometry and the column plan, computed before the first page. ShrinkToFit scales widths (pinned at MinWidth) and the text down to MinFontScale, then falls back to SplitColumns; SplitColumns builds column bands with the first RepeatColumns repeated; Fixed cuts at the margin. Orientation.Auto picks landscape when the grid-width columns do not fit portrait.
  • Export/Internal/PdfPaginator: breaks the row stream into page slices (column header on every page, the open groups' headers repeated with "(continued)", a group header kept with its first row). The same pass counts pages up front with no sink and places rows when drawing, so {pages} and the document always agree.
  • Export/Internal/PdfPageWriter: holds one slice of rows (texts copied out of the reused KumikoExportRow) and draws one page per column band onto whatever canvas its page callback returns. Numeric columns default to right alignment; TextAlignment and a column's static CellStyle are honored; summary titles run on over empty cells; ellipsis or WrapText.
  • Export/Internal/PdfOutputBuffer: Skia writes into a buffer that reaches the destination in 64 KB writes (synchronously on the pool thread, asynchronously between chunks with ReadOnCallerThread). The destination is never closed and need not be seekable.

Without WrapText every row has one height, so the page count is known before any byte is written, from the row kinds alone. That needs two small additive Core members on the snapshot. With WrapText, {pages} is empty and the default footer is "Page n", unless MeasurePageCount runs a measuring pre-pass (spec Q10).

Extension points for the follow-ups: per-cell look is resolved in one place in PdfPageWriter.DrawLine (the static CellStyle today), which is where #385's per-cell callback and styles plug in. PdfLayout, PdfPaginator and PdfPageWriter take a page callback rather than an SKDocument, so #386 (PrintAsync) can reuse the layout and pagination with another canvas. Neither follow-up is implemented here.

Public API added:

  • KumikoUI.SkiaSharp.Export: KumikoPdfExporter (IKumikoExporter: "PDF", .pdf, application/pdf), KumikoPdfExportExtensions.ExportToPdfAsync, KumikoPdfOptions (PageSize, Orientation, Margins, ColumnFitting, MinFontScale, RepeatColumns, WrapText, MeasurePageCount, RepeatHeader, RepeatGroupHeader, Header, Footer, Style, Metadata, MaxPages), KumikoPageSize (A4, Letter, Legal, Custom), KumikoPageOrientation, KumikoPdfColumnFitting, KumikoPdfStyle (Print, FromGridStyle(KumikoStyle)), KumikoPdfMetadata.
  • Core: KumikoExportSnapshot.GetRowKind(int) and GetRowLevel(int), which give a row's shape without reading values. KumikoStrings.ExportGroupContinued, ExportPageFooter and ExportPageFooterWithoutCount, so "(continued)" and the footer localize.

Differences from the proposal in the issue: Footer is null by default, meaning "use KumikoStrings.ExportPageFooter" so it localizes; an empty string turns it off. Metadata is nullable. There is a new MeasurePageCount option for the wrap pre-pass.

Also in this PR:

  • Samples: the MAUI and Uno Export pages get an "Export PDF" button. MAUI saves to the cache directory and opens the share sheet; Uno uses FileSavePicker with a .pdf choice.
  • AOT smoke: eng/AotSmoke exports a grouped PDF and checks the header, %%EOF, pages and an embedded font.
  • Benchmark: bench/KumikoUI.Benchmarks/PdfExportBenchmarks (100K rows, plain and grouped) and a pdf-memory runner that prints time, allocations and sampled peak working set. The numbers are in bench/README.md and docs/EXPORT.md.
  • Docs: docs/EXPORT.md gets a PDF section (options table, fonts and licensing, threading and memory, saving). README.md gets the exporting section, package table and strings list. The SkiaSharp NuGet README and the CHANGELOG are updated too.

Acceptance criteria

  • Output starts with %PDF-; page count matches the prediction for fixed row height; header and footer repeat on every page; group headers repeat with "(continued)", verified with a test-only text extractor in tests/KumikoUI.SkiaSharp.Tests. PdfTextExtractor decodes Skia's Type0 and Type3 fonts through their ToUnicode maps. The page-count test predicts rows per page from font metrics alone. A localized "(continued)" and nested groups (outermost first) are covered too.
  • ShrinkToFit never exceeds the content width (randomized test of the fitting plus an end-to-end test with smaller text); SplitColumns repeats key columns (each other column on exactly one band, the key column on all); Orientation.Auto picks landscape for wide grids.
  • Registered font embedded (the /BaseFont subset name and /FontFile2); right alignment for numeric columns (and CellStyle or explicit alignment honored); ellipsizing; WrapText grows rows, with and without MeasurePageCount.
  • Cancellation between pages (checked when each slice begins and before each page, plus every 256 rows); progress is monotonic and ends at the row total; MaxPages guard (ArgumentException before writing when the count is known, InvalidOperationException mid-stream otherwise); stream left open.
  • eng/AotSmoke exports a PDF under Native AOT with no trim warnings (published on osx-arm64 and run: "AOT smoke OK").
  • 100K-row export time and peak memory recorded as a benchmark (not a gate): about 1.8 to 1.9 s and 167 MB allocated (188 MB grouped) for 1,924 A4 pages; the working set grew 3 to 10 MB during the export.
  • Works from both hosts (MAUI and Uno samples gain an "Export PDF" button). Both samples build (MAUI on Mac Catalyst, Uno desktop). Not exercised by hand in a running app.
  • No allocations added to the grid's per-frame render path (export uses its own cache). No renderer or host code changed; the existing SkiaAllocationTests and Core render allocation tests pass. While measuring for this, I found and fixed a growth issue: a measuring context left open for the whole export kept the cache in one long frame, so evicted text runs piled up. Measuring contexts are now opened only while measuring.
  • XML docs on every new public member; PublicAPI.Unshipped.txt for KumikoUI.SkiaSharp (and Core) updated. eng/update-public-api.sh emptied the files in this worktree without writing members back (dotnet format found nothing to fix here), so I added the RS0016 lines from the build by hand, sorted the way the script sorts them.
  • Export guide (docs/EXPORT.md) and README updated; CHANGELOG entry under Unreleased.

Not in scope, per the issue: per-cell export customization (#385), printing (#386), band rows (#346), range export (#336). Pages are laid out left to right; RTL follows #349.

Verification

  • dotnet build src/KumikoUI.Core and dotnet build src/KumikoUI.SkiaSharp (Debug and Release): succeeded, no warnings.
  • dotnet build src/KumikoUI.Maui -f net10.0-maccatalyst: succeeded.
  • dotnet build samples/SampleApp.Maui -f net10.0-maccatalyst -p:KumikoDevFlow=false: succeeded. In Debug with DevFlow on, restore fails with NU1605 on the Microsoft.Maui.Controls DevFlow pin (10.0.41 against SkiaSharp's 10.0.110 floor). That also happens without this change.
  • dotnet build samples/SampleApp.Uno -f net10.0-desktop (which builds src/KumikoUI.Uno for net10.0-desktop): succeeded; the only warnings are the existing Uno0001 ones in the host.
  • dotnet test tests/KumikoUI.SkiaSharp.Tests: 79 passed (37 new PDF tests).
  • dotnet test tests/KumikoUI.Core.Tests: 4365 passed, 5 skipped (new ExportRowShapeTests; LocalizationTests German table extended).
  • dotnet test tests/KumikoUI.Export.Excel.Tests: 122 passed.
  • dotnet run --project eng/DocsSnippets -c Release, then dotnet build tests/KumikoUI.Docs.Snippets.Uno -f net10.0-desktop -c Release and dotnet build tests/KumikoUI.Docs.Snippets.Maui -f net10.0-maccatalyst -c Release: succeeded.
  • dotnet run --project eng/DocsIdentifiers -c Release: 0 problems.
  • dotnet publish eng/AotSmoke -c Release -r osx-arm64 and run: "AOT smoke OK", no IL2xxx/IL3xxx warnings. Locally this needed LIBRARY_PATH pointing at Homebrew's openssl and brotli for the native link step; that is a machine setup issue, not part of the change.
  • dotnet run -c Release --project bench/KumikoUI.Benchmarks -- --filter '*PdfExport*' --job short and -- pdf-memory [rows] [--grouped]: numbers above.

await bench.ExportPdfAsync(counted);
string text = System.Text.Encoding.Latin1.GetString(counted.GetBuffer(), 0, (int)counted.Length);
int pages = System.Text.RegularExpressions.Regex.Count(text, @"/Type /Page(?!s)");
counted = null;
string text = System.Text.Encoding.Latin1.GetString(counted.GetBuffer(), 0, (int)counted.Length);
int pages = System.Text.RegularExpressions.Regex.Count(text, @"/Type /Page(?!s)");
counted = null;
GC.Collect();
return bands;
}

private static KumikoFont Scale(KumikoFont font, float scale) => scale == 1f ? font : font with { Size = font.Size * scale };
Comment on lines +149 to +157
if (fitting == KumikoPdfColumnFitting.ShrinkToFit)
{
if (!TryShrink(columns, content, pdf.MinFontScale, out fontScale))
{
fitting = KumikoPdfColumnFitting.SplitColumns;
fontScale = 1f;
foreach (var c in columns) c.Width = c.NaturalWidth;
}
}
if (pdf.MaxPages < 1) throw new ArgumentException("MaxPages must be at least 1.", nameof(pdf));
if (pdf.Style == null) throw new ArgumentException("The style cannot be null.", nameof(pdf));
var style = pdf.Style;
if (!(style.GridUnitScale > 0) || !float.IsFinite(style.GridUnitScale)) throw new ArgumentException("GridUnitScale must be more than 0.", nameof(pdf));
if (pdf.Style == null) throw new ArgumentException("The style cannot be null.", nameof(pdf));
var style = pdf.Style;
if (!(style.GridUnitScale > 0) || !float.IsFinite(style.GridUnitScale)) throw new ArgumentException("GridUnitScale must be more than 0.", nameof(pdf));
if (!(style.CellFont.Size > 0) || !(style.HeaderFont.Size > 0) || !(style.GroupHeaderFont.Size > 0) ||
var style = pdf.Style;
if (!(style.GridUnitScale > 0) || !float.IsFinite(style.GridUnitScale)) throw new ArgumentException("GridUnitScale must be more than 0.", nameof(pdf));
if (!(style.CellFont.Size > 0) || !(style.HeaderFont.Size > 0) || !(style.GroupHeaderFont.Size > 0) ||
!(style.SummaryFont.Size > 0) || !(style.PageTextFont.Size > 0))
var style = pdf.Style;
if (!(style.GridUnitScale > 0) || !float.IsFinite(style.GridUnitScale)) throw new ArgumentException("GridUnitScale must be more than 0.", nameof(pdf));
if (!(style.CellFont.Size > 0) || !(style.HeaderFont.Size > 0) || !(style.GroupHeaderFont.Size > 0) ||
!(style.SummaryFont.Size > 0) || !(style.PageTextFont.Size > 0))
Comment on lines +156 to +161
foreach (var page in pdf.Pages.Skip(1))
{
var texts = page.Texts.ToList();
int header = texts.IndexOf("Amount");
Assert.Matches(@"^Region: (North|South|West) \(80\) \(continued\)$", texts[header + 1]);
}
Comment on lines +161 to +211
foreach (Match token in TokenRegex().Matches(content))
{
string t = token.Value;
if (t == "Tf")
{
if (operands.Count >= 2 && operands[^2].StartsWith('/'))
{
fonts.TryGetValue(operands[^2][1..], out font);
size = float.Parse(operands[^1], CultureInfo.InvariantCulture);
}
operands.Clear();
}
else if (t == "Tm")
{
// The first matrix of a text object is where it starts (the page is flipped: y grows downward).
if (!positioned && operands.Count >= 6)
{
x = float.Parse(operands[^2], CultureInfo.InvariantCulture);
y = float.Parse(operands[^1], CultureInfo.InvariantCulture);
positioned = true;
}
operands.Clear();
}
else if (t == "Tj" || t == "TJ")
{
foreach (var operand in operands)
foreach (Match hex in Regex.Matches(operand, @"<([0-9A-Fa-f]*)>"))
current.Append(Decode(hex.Groups[1].Value, font));
operands.Clear();
}
else if (t == "BT")
{
current.Clear();
operands.Clear();
positioned = false;
}
else if (t == "ET")
{
texts.Add(new PdfText(current.ToString(), x, y, size));
current.Clear();
operands.Clear();
}
else if (Regex.IsMatch(t, @"^[A-Za-z'""*]+$"))
{
operands.Clear();
}
else
{
operands.Add(t);
}
}

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Export: add a paginated PDF exporter in KumikoUI.SkiaSharp

2 participants