Skip to content

feat: add PrintAsync that sends the PDF export to the platform print service (#386) - #522

Open
michaelstonis wants to merge 1 commit into
feat/340-pdf-exporterfrom
feat/386-print-async
Open

michaelstonis wants to merge 1 commit into
feat/340-pdf-exporterfrom
feat/386-print-async

Conversation

@michaelstonis

@michaelstonis michaelstonis commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Closes #386.

Stacked on #502: until that PR merges, this one also shows its commits.

Changes

PrintAsync on the MAUI and Uno KumikoDataGrid exports the grid as the #340 PDF to a temporary file, shows the platform's print dialog for it, and deletes the file. It follows the IKumikoClipboard pattern: a small Core interface, with a default implementation per platform supplied by the host.

Core (KumikoUI.Core.Export)

  • IKumikoPrintService: IsSupported and PrintPdfAsync(Stream pdf, string jobName, CancellationToken). The stream is readable and seekable, positioned at 0, and valid until the task completes.
  • KumikoPrintResult: Printed, Canceled, NotSupported, Failed.
  • KumikoPrintExtensions.PrintAsync(this KumikoSource, IKumikoPrintService?, IKumikoExporter, string jobName, options, progress, cancellationToken). This is the platform-neutral flow, and it is usable without a grid:
    • A null or unsupported service returns NotSupported without exporting.
    • Otherwise it exports to Path.GetTempPath()/kumiko-print-{guid}.pdf, opened with FileShare.Read, rewinds the file, and calls the service on the caller's context. It uses no ConfigureAwait(false) because dialogs belong to the UI thread.
    • It deletes the file in finally. Export and service exceptions propagate after cleanup, and a canceled token throws OperationCanceledException.
  • KumikoStrings.PrintJobName ("Data grid"). The job name is the jobName argument, else the PDF's Metadata.Title, else this string (internal ResolveJobName).

Hosts (both KumikoDataGrids, KumikoDataGrid.Printing.cs)

  • PrintService { get; set; } defaults to the platform service and is created lazily. Setting null turns printing off.
  • CanPrint is PrintService?.IsSupported == true.
  • PrintAsync(KumikoExportOptions? options = null, KumikoPdfOptions? pdf = null, string? jobName = null, IProgress<KumikoExportProgress>? progress = null, CancellationToken cancellationToken = default).
  • PrintCommand (ICommand, parameter ignored, can execute while CanPrint; CanExecuteChanged fires when PrintService is replaced). Uno gets it too, for parity with ShowColumnChooserCommand.

Platform services. The code is shared by both hosts: src/Shared/Printing/*.cs, linked into each project with <Compile Include LinkBase="Printing">. Each file compiles only for its own platform (#if).

  • iOS / Mac Catalyst (ApplePrintService): UIPrintInteractionController with the temp file's NSUrl as the printing item, or NSData for a non-file stream. It uses PresentFromRectInView from the grid's bounds on iPad and Mac, and Present on iPhone. The completion handler maps to Printed, Canceled or Failed. IsSupported is PrintingAvailable.
    • MAUI anchors on the canvas's platform view.
    • Uno iOS anchors on the key window, at the grid's transformed bounds.
  • Android (AndroidPrintService): PrintManager.Print with a PrintDocumentAdapter that copies the PDF to the write descriptor. The page count is reported as unknown, so the framework paginates and previews the document itself. The task completes in OnFinish, and the result comes from the PrintJob state. No permission or manifest entry is needed.
    • The context is Platform.CurrentActivity on MAUI and ContextHelper.Current on Uno.
  • Windows: MAUI Windows head and Uno WinAppSDK head (WindowsPrintService). WinUI printing can only print XAML elements, so:
    • The issue's choice between rasterizing and opening the file in the default app was decided for rasterizing.
    • The service loads the PDF with Windows.Data.Pdf and renders each page to a BitmapImage at 150 dpi when the preview (GetPreviewPage) or the printer (AddPages) asks for it, sized to the printer's page.
    • It uses PrintManagerInterop.GetForWindow and ShowPrintUIForWindowAsync, and maps PrintTask.Completed to Printed, Canceled or Failed.
    • The window handle comes from WindowNative.GetWindowHandle on MAUI and from XamlRoot.ContentIslandEnvironment.AppWindowId → Win32Interop.GetWindowFromWindowId on Uno.
  • Uno WebAssembly (src/KumikoUI.Uno/Printing/BrowserPrintService.cs):
    • A small ES module is imported through JSHost.ImportAsync from a data: URL, so the package ships no web asset and check-uno-package is unaffected.
    • The module makes a blob URL of the PDF, loads it in a hidden iframe and calls the frame's print().
    • The browser does not report the outcome, so the result is Printed once the dialog opened (documented). The frame and the blob URL are removed when the page gets focus back, or after 10 minutes.
    • A CSP that blocks data: scripts makes the call return Failed.
  • Uno desktop (Skia on Windows, macOS, Linux): decided as no service. PrintService is null, CanPrint is false and PrintAsync returns NotSupported, as documented. Apps can assign their own service, for example one that opens the OS viewer.

Other changes

  • Samples: the MAUI and Uno Export pages get a Print button (shows the outcome in the status label). They share their PDF options with Export PDF.
  • Docs:
    • docs/EXPORT.md gets a new "Printing" section: per-platform table, threading, cancellation, preview, the Core flow.
    • README.md gets a print snippet under Exporting (compiled by the docs snippet projects), and PrintJobName is added to the strings list.
    • CHANGELOG.md gets an entry under Unreleased.

No renderer, input controller, hit tester or PDF page writer code is touched. The per-cell styling code that #385 changes is left alone: printing goes through the public KumikoPdfExporter, so #385's styling carries over.

Public API added

  • Core: IKumikoPrintService (IsSupported, PrintPdfAsync), KumikoPrintResult (4 members), KumikoPrintExtensions.PrintAsync, KumikoStrings.PrintJobName.
  • Maui and Uno, the same on every head, so in the common PublicAPI.Unshipped.txt: KumikoDataGrid.PrintService (get/set), CanPrint, PrintAsync(...), PrintCommand.

Acceptance criteria

  • PrintAsync prints a multi-page grouped report on iOS, Mac Catalyst, Android and Windows (MAUI), and on Uno WebAssembly, iOS, Android and WinAppSDK; Uno desktop behavior decided and documented.
    • Partly verified. The Uno desktop behavior is decided and documented (NotSupported). No device print dialog could be run here; per platform:
    • Exercised in a browser: Uno WebAssembly, which ran in a browser here. Clicking Print on the sample's grid exported the PDF, imported the module, created the hidden blob iframe titled "Employees" and called print(). The test browser blocks print dialogs it did not see a user open, so no dialog appeared.
    • Build-verified only:
      • MAUI net10.0-ios, net10.0-maccatalyst and net10.0-android.
      • Uno net10.0-ios and net10.0-android.
    • Not built in the repository on this Mac: the Windows heads (MAUI net10.0-windows10.0.19041.0, Uno net10.0-windows10.0.26100). WindowsPrintService.cs and both hosts' window-handle lookups were compiled without errors or warnings in a scratch net10.0-windows10.0.19041.0 WinUI project (Microsoft.WindowsAppSDK 1.8, MAUI 10.0.110 global usings, IsAotCompatible, latest-recommended). CI's Windows jobs are the first real build.
    • Not verified on a device: the grouped multi-page report has not been printed on any device. It needs a manual pass on each platform.
  • CanPrint/IsSupported report correctly per platform; NotSupported returned rather than thrown. Covered by tests for the null and unsupported service, the desktop factory returning null, and the MAUI grid on net10.0.
  • Temporary files are removed on success, cancel and failure. Core tests cover success, Canceled and Failed outcomes, cancellation before start, during the export and while the dialog is open, and export and service exceptions. MAUI tests check the file is gone after a grid print.
  • Tests in tests/KumikoUI.Core.Tests with a fake IKumikoPrintService (flow, cancellation, cleanup); host tests in tests/KumikoUI.Maui.Tests and tests/KumikoUI.Uno.Tests for wiring.
    • The MAUI tests drive a real grid: a grouped PDF reaches the service (%PDF- … %%EOF), the job name resolves, and CanPrint and PrintCommand follow the service.
    • A Uno KumikoDataGrid cannot be created in the desktop test project (missing Uno.WinUI.Graphics2DSK without a running app). The Uno tests therefore cover the pieces the grid's members delegate to: the platform factory (null on desktop) and PrintGridCommand.
  • Sample app has a Print button on MAUI and Uno.
  • XML docs on every new public member; PublicAPI.Unshipped.txt updated. No member is head-specific. As in Export: add a paginated PDF exporter in KumikoUI.SkiaSharp #340, eng/update-public-api.sh does not write members back in this worktree, so the RS0016 lines from the build were added by hand, sorted like the script (LC_ALL=C sort).
  • README and the Spec: export to CSV and Excel/PDF #105 export guide updated; CHANGELOG entry under Unreleased.
  • Trim and Native AOT builds stay warning-free. Both libraries build with IsAotCompatible and the trim and AOT analyzers on every head built here, with no warnings. The new code uses no reflection, and the JS interop is a [JSImport]. No AOT app publish was run locally.

Verification

  • dotnet build src/KumikoUI.Core (Debug and Release) and dotnet build src/KumikoUI.SkiaSharp -c Release: succeeded, no warnings.
  • dotnet build src/KumikoUI.Maui -f net10.0-maccatalyst, -f net10.0-ios (Debug and Release) and -f net10.0-android: succeeded, no warnings from this change. Android prints the machine's existing "Java SDK installation" environment warning.
  • dotnet build src/KumikoUI.Uno -f net10.0-desktop, -f net10.0, -f net10.0-ios, -f net10.0-android and -f net10.0-browserwasm (also -c Release): succeeded. The only warnings are the existing Uno0001 ones; none come from the printing files.
  • Windows compile check: scratch net10.0-windows10.0.19041.0 WinUI project compiling src/Shared/Printing/WindowsPrintService.cs plus probes of both hosts' window-handle code, built with -p:AppxGeneratePriEnabled=false: built, 0 warnings.
  • dotnet test tests/KumikoUI.Core.Tests: 4385 passed, 5 skipped. The 20 new PrintFlowTests cover flow, cleanup, cancellation, NotSupported, progress and job-name resolution; LocalizationTests covers German PrintJobName.
  • dotnet test tests/KumikoUI.Maui.Tests: 454 passed (5 new KumikoDataGridPrintingTests).
  • dotnet test tests/KumikoUI.Uno.Tests: 324 passed (3 new KumikoDataGridPrintingTests).
  • dotnet test tests/KumikoUI.SkiaSharp.Tests: 79 passed.
  • dotnet build samples/SampleApp.Uno -f net10.0-desktop and -f net10.0-browserwasm, and dotnet build samples/SampleApp.Maui -f net10.0-maccatalyst -p:KumikoDevFlow=false: succeeded.
  • 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.
  • Uno WebAssembly sample run in a browser: Export page, Print. The PDF iframe was created from a blob URL and print() was called; the browser blocked the dialog itself.

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.

1 participant