Repository navigation
feat: add a paginated PDF exporter in KumikoUI.SkiaSharp (#340) - #502
Open
michaelstonis wants to merge 4 commits into
Open
michaelstonis wants to merge 4 commits into
michaelstonis wants to merge 4 commits into
Conversation
This was referenced Nov 30, 2026
| 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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'sSKDocumentPDF backend through aSkiaDrawingContextover the exporter's ownSkiaResourceCache, 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
KumikoRendererandKumikoLayoutEngine(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.ShrinkToFitscales widths (pinned atMinWidth) and the text down toMinFontScale, then falls back toSplitColumns;SplitColumnsbuilds column bands with the firstRepeatColumnsrepeated;Fixedcuts at the margin.Orientation.Autopicks 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 reusedKumikoExportRow) and draws one page per column band onto whatever canvas its page callback returns. Numeric columns default to right alignment;TextAlignmentand a column's staticCellStyleare honored; summary titles run on over empty cells; ellipsis orWrapText.Export/Internal/PdfOutputBuffer: Skia writes into a buffer that reaches the destination in 64 KB writes (synchronously on the pool thread, asynchronously between chunks withReadOnCallerThread). The destination is never closed and need not be seekable.Without
WrapTextevery 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. WithWrapText,{pages}is empty and the default footer is "Page n", unlessMeasurePageCountruns a measuring pre-pass (spec Q10).Extension points for the follow-ups: per-cell look is resolved in one place in
PdfPageWriter.DrawLine(the staticCellStyletoday), which is where #385's per-cell callback and styles plug in.PdfLayout,PdfPaginatorandPdfPageWritertake a page callback rather than anSKDocument, 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.KumikoExportSnapshot.GetRowKind(int)andGetRowLevel(int), which give a row's shape without reading values.KumikoStrings.ExportGroupContinued,ExportPageFooterandExportPageFooterWithoutCount, so "(continued)" and the footer localize.Differences from the proposal in the issue:
Footerisnullby default, meaning "useKumikoStrings.ExportPageFooter" so it localizes; an empty string turns it off.Metadatais nullable. There is a newMeasurePageCountoption for the wrap pre-pass.Also in this PR:
FileSavePickerwith a.pdfchoice.eng/AotSmokeexports a grouped PDF and checks the header,%%EOF, pages and an embedded font.bench/KumikoUI.Benchmarks/PdfExportBenchmarks(100K rows, plain and grouped) and apdf-memoryrunner that prints time, allocations and sampled peak working set. The numbers are inbench/README.mdanddocs/EXPORT.md.docs/EXPORT.mdgets a PDF section (options table, fonts and licensing, threading and memory, saving).README.mdgets the exporting section, package table and strings list. The SkiaSharp NuGet README and the CHANGELOG are updated too.Acceptance criteria
%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 intests/KumikoUI.SkiaSharp.Tests.PdfTextExtractordecodes 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.ShrinkToFitnever exceeds the content width (randomized test of the fitting plus an end-to-end test with smaller text);SplitColumnsrepeats key columns (each other column on exactly one band, the key column on all);Orientation.Autopicks landscape for wide grids./BaseFontsubset name and/FontFile2); right alignment for numeric columns (andCellStyleor explicit alignment honored); ellipsizing;WrapTextgrows rows, with and withoutMeasurePageCount.MaxPagesguard (ArgumentExceptionbefore writing when the count is known,InvalidOperationExceptionmid-stream otherwise); stream left open.eng/AotSmokeexports a PDF under Native AOT with no trim warnings (published on osx-arm64 and run: "AOT smoke OK").SkiaAllocationTestsand 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.PublicAPI.Unshipped.txtfor KumikoUI.SkiaSharp (and Core) updated.eng/update-public-api.shemptied the files in this worktree without writing members back (dotnet formatfound nothing to fix here), so I added the RS0016 lines from the build by hand, sorted the way the script sorts them.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.Coreanddotnet 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 buildssrc/KumikoUI.Unofor 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 (newExportRowShapeTests;LocalizationTestsGerman table extended).dotnet test tests/KumikoUI.Export.Excel.Tests: 122 passed.dotnet run --project eng/DocsSnippets -c Release, thendotnet build tests/KumikoUI.Docs.Snippets.Uno -f net10.0-desktop -c Releaseanddotnet 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-arm64and run: "AOT smoke OK", no IL2xxx/IL3xxx warnings. Locally this neededLIBRARY_PATHpointing 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 shortand-- pdf-memory [rows] [--grouped]: numbers above.