Ghost1372

everything can be handy

PrintHelper

  • Because PrintHelper has not yet been updated to the CommunityToolkit package, we added it. But note that whenever it is updated to the CommunityToolkit package, we will remove this helper class.

  • PrintHelper is Available Only in Windows10.0.19041_OR_Greater Target Frameworks.

Example

1
2
3
4
5
6
7
8
9
<Grid x:Name="DirectPrintContainer">
<Grid x:Name="PrintableContent">
<Rectangle x:Name="RectangleToPrint" Width="500" Height="500">
<Rectangle.Fill>
<ImageBrush ImageSource="ms-appx:///Assets/AusterNY.jpg" />
</Rectangle.Fill>
</Rectangle>
</Grid>
</Grid>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
private PrintHelper _printHelper;

if (PrintManager.IsSupported())
{
_printHelper = new PrintHelper(DirectPrintContainer);

_printHelper.OnPrintCanceled += PrintHelper_OnPrintCanceled;
_printHelper.OnPrintFailed += PrintHelper_OnPrintFailed;
_printHelper.OnPrintSucceeded += PrintHelper_OnPrintSucceeded;

var printHelperOptions = new PrintHelperOptions(false);
printHelperOptions.Orientation = PrintOrientation.Default;

await _printHelper.ShowPrintUIAsync(WinRT.Interop.WindowNative.GetWindowHandle(MainWindow.Instance), "Windows Community Toolkit Sample App", printHelperOptions, true);
}
else
{
PrintingIsNotSupported();
}

private void ReleasePrintHelper()
{
_printHelper.Dispose();

if (!DirectPrintContainer.Children.Contains(PrintableContent))
{
DirectPrintContainer.Children.Add(PrintableContent);
}
}

private async void PrintHelper_OnPrintSucceeded()
{
ReleasePrintHelper();
ContentDialog noPrintingDialog = new ContentDialog()
{
XamlRoot = this.Content.XamlRoot,
Title = "Printing Done",
Content = "\nDone, element printed.",
PrimaryButtonText = "OK"
};
await noPrintingDialog.ShowAsyncQueue();
}

private async void PrintHelper_OnPrintFailed()
{
ReleasePrintHelper();
ContentDialog noPrintingDialog = new ContentDialog()
{
XamlRoot = this.Content.XamlRoot,
Title = "Printing error",
Content = "\nSorry, failed to print.",
PrimaryButtonText = "OK"
};
await noPrintingDialog.ShowAsyncQueue();
}
private void PrintHelper_OnPrintCanceled()
{
ReleasePrintHelper();
}

Demo

you can run demo and see this feature.

0%