Printing

Print API

The print button from the main toolbar triggers an event that you can subscribe to. You can then use PrintHelper to present a print dialog to the user. Note that it is not necessary to subscribe to the event in order to initiate printing; it is merely a convenience.

Toolbar Print Button

The following code taken from the Catalog app demonstrates how to subscribe to the print button click event in the toolbar. It is important to only subscribe once the PDFView has completed initialization:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public PrintPage()
{
    InitializeComponent();
    ViewModel.Initialize(PDFView);

    PDFView.InitializationCompletedHandler += PDFView_InitializationCompletedHandler;
}

// Once the API is initialized, we tell it we want to know when the user clicks the print button.
private void PDFView_InitializationCompletedHandler(PSPDFKit.PDFView sender, int args)
{
    sender.Controller.OnPrint += API_OnPrint;
}

private void API_OnPrint(PSPDFKit.API sender, object args)
{
    ViewModel.OnPrint(this);
}

Windows Print Service Dialog

In order to display the Windows printing service dialog, you will need to place a named Canvas UIElement in your page’s XAML:

1
<Canvas x:Name="PrintCanvas" Opacity="0"/>

To open the dialog, register an instance of the PSPDFKit.PrintHelper class with the PSPDSFKit.API, the page you are printing from, and the name of the Canvas element.

To be informed of the status of the print job, add an event handler to PrintHelper.PrintingCompleteHandler:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
internal async void OnPrint(Windows.UI.Xaml.Controls.Page owningPage)
{
    try
    {
        // For printing a `Canvas`, UIElement is required in the visual tree on the current page.
        var printHelper = new PrintHelper(PDFView.Document, owningPage, "PrintCanvas", "MyDocumentFileName.pdf");

        printHelper.PrintingCompleteHandler += PrintHelper_PrintingCompleteHandler;

        await printHelper.ShowPrintUIAsync();
    }
    catch (Exception e)
    {
        var messageDialog = new MessageDialog(e.ToString());
        await messageDialog.ShowAsync();
    }
}

The print status tells you if the job was canceled or completed or something else:

Copy
1
2
3
4
5
6
7
8
private static async void PrintHelper_PrintingCompleteHandler(PrintHelper sender, Windows.Graphics.Printing.PrintTaskCompletedEventArgs args)
{
    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
    {
        var messageDialog = new MessageDialog("Print Status: " + args.Completion.ToString());
        await messageDialog.ShowAsync();
    });
}