Quickstart: Printing from your app (XAML)
This Quickstart shows the simplest way to add print functionality to your Windows Store app using C++, C#, or Visual Basic.
Watch this brief video for an overview of the process.
At a high level, to print from your Windows Store app using C++, C#, or Visual Basic, your app must:
Register for the Print contract in each display of the app from which you want users to be able to print.
Provide formatted content to print.
The default print experience shown in this Quickstart is for Windows to print your app's screen display. For more info about formatting your app's content for printing, see the Summary and next steps.
- You must be familiar with C# or Visual Basic, XAML, Windows events, and event handling.
- You must have Microsoft Visual Studio installed.
- You must have a printer installed.
- You must have an app to which you want to add printing. If you don't have your own app, you can download the Print Sample sample app and use that app.
This procedure describes how to open the Print Sample sample app. If you are using your own app, open it in Visual Studio and skip to the next step.
- Open the Windows Store app Print sample and download the C# example to your computer.
- In Visual Studio, click File > Open Project and go to the folder that contains the solution file of the sample app that you downloaded in the previous step.
- Select the PrintSample solution file and click Open.
- Click Build > Build Solution to build the app you are working on. Make sure that there are no error messages in the Output pane at the bottom of the screen.
- Click Debug > Start Without Debugging.
- Verify that, after a few seconds, the screen displays the PrintSample app.
- If the app runs without error, return to Visual Studio and click Debug > Stop Debugging.
At this point, you should have an app that displays a screen with some content.
The first step to add printing to your app is to register for the Print contract. Your app must do this on every screen from which you want your customer to be able to print.
BasePrintPageclass in the Print Sample sample app.
First, declare the PrintManager and PrintDocument. The PrintManager type is in the Windows.Graphics.Printing namespace along with types to support other Windows printing functionality. The PrintDocument type is in the Windows.UI.Xaml.Printing namespace along with other types that support preparing XAML content for printing. You can make it easier to write your printing code by adding the following using or Imports statements to your page.
Create the registration method to initialize the properties your app will require for printing.
In the Print Sample sample app, this method is in the base class that is used by the different displays of the app.
Protected Overridable Sub RegisterForPrinting() ' Create the PrintDocument. printDocument = New PrintDocument ' Save the DocumentSource. printDocumentSource = printDocument.DocumentSource ' Add an event handler which creates preview pages. AddHandler printDocument.Paginate, AddressOf CreatePrintPreviewPages ' Add an event handler which provides a specified preview page. AddHandler printDocument.GetPreviewPage, AddressOf GetPrintPreviewPage ' Add an event handler which provides all final print pages. AddHandler printDocument.AddPages, AddressOf AddPrintPages ' Create a PrintManager and add a handler for printing initialization. Dim printMan As PrintManager = PrintManager.GetForCurrentView AddHandler printMan.PrintTaskRequested, AddressOf PrintTaskRequested ' Initialize print content for this scenario PreparePrintContent() End Sub
Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs) ' Get a pointer to our main page rootPage = TryCast(e.Parameter, MainPage) ' init printing RegisterForPrinting() End Sub
When the user leaves the page, disconnect the printing event handlers. If you have a multiple-page app and don't disconnect printing, an exception is thrown when the user leaves the page and then comes back to it.
Protected Overrides Sub OnNavigatedFrom(e As NavigationEventArgs) UnregisterForPrinting() End Sub
Windows printing raises events when the user wants to print and when it wants the app to provide the formatted content to print.
When a user selects a printer on the Devices charm, the PrintTaskRequested event is raised. The PrintTaskRequested event handler shown in this step creates a PrintTask by calling the PrintTaskRequest.CreatePrintTask method and passes the title for the print page and the name of a PrintTaskSourceRequestedHandler delegate. Notice that in this example, the PrintTaskSourceRequestedHandler is defined inline. The PrintTaskSourceRequestedHandler provides the formatted content for printing and is described later.
In this example, a completion handler is also defined to catch errors. It's a good idea to handle completion events because then your app can let the user know if an error occurred and provide possible solutions. Likewise, your app could use the completion event to indicate subsequent steps for the user to take after the print job is successful.
Protected Overridable Sub PrintTaskRequested(sender As PrintManager, e As PrintTaskRequestedEventArgs) Dim printTask As PrintTask = Nothing printTask = e.Request.CreatePrintTask("VB Printing SDK Sample", Sub(sourceRequested) ''' <summary> ''' Option change event handler ''' </summary> ''' <param name="s">The print task option details for which an option changed.</param> ''' <param name="args">The event arguments containing the id of the changed option.</param> AddHandler printTask.Completed, Async Sub(s, args) '' Notify the user when the print operation fails. If args.Completion = PrintTaskCompletion.Failed Then Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Sub() rootPage.NotifyUser("Failed to print.", NotifyType.ErrorMessage) End Sub) End If End Sub sourceRequested.SetSource(printDocumentSource) End Sub) End Sub
After the print task is created, the PrintManager requests a collection of print pages to show in the print preview UI by raising the Paginate event. In the Paginate event handler, you create the pages to show in the print preview UI and to send to the printer. The code you use to prepare your app's content for printing is specific to your app and the content you print.
Protected Overridable Sub CreatePrintPreviewPages(sender As Object, e As PaginateEventArgs) ' Clear the cache of preview pages printPreviewPages.Clear() ' Clear the printing root of preview pages PrintingRootCanvas.Children.Clear() ' This variable keeps track of the last RichTextBlockOverflow element that was added to a page which will be printed Dim lastRTBOOnPage As RichTextBlockOverflow ' Get the PrintTaskOptions Dim printingOptions As PrintTaskOptions = DirectCast(e.PrintTaskOptions, PrintTaskOptions) ' Get the page description to deterimine how big the page is Dim pageDescription As PrintPageDescription = printingOptions.GetPageDescription(0) ' We know there is at least one page to be printed. passing null as the first parameter to ' AddOnePrintPreviewPage tells the function to add the first page. lastRTBOOnPage = AddOnePrintPreviewPage(Nothing, pageDescription) ' For this app: we know there are more pages to be added as long as the last RichTextBlockOverflow ' added to a print preview page has extra content and is visible While lastRTBOOnPage.HasOverflowContent And lastRTBOOnPage.Visibility = Xaml.Visibility.Visible lastRTBOOnPage = AddOnePrintPreviewPage(lastRTBOOnPage, pageDescription) End While RaiseEvent pagesCreated(printPreviewPages, Nothing) Dim printDoc As PrintDocument = sender ' Report the number of preview pages created printDoc.SetPreviewPageCount(printPreviewPages.Count, PreviewPageCountType.Intermediate) End Sub
The preceding example shows a very simple print scenario. Only one page is created, and the content is scaled to fill all of the available area. Other topics in this section show examples of more complex printing scenarios.
In the AddPages event handler, you add pages from the page collection to the PrintDocument object to be sent to the printer. If a user specifies particular pages or a range of pages to print, you use that information here to add only the pages that will actually be sent to the printer.
Protected Overridable Sub AddPrintPages(sender As Object, e As AddPagesEventArgs) Dim printDoc As PrintDocument = sender ' Loop over all of the preview pages and add each one to add each page to be printied For i = 0 To printPreviewPages.Count - 1 printDoc.AddPage(printPreviewPages(i)) Next ' Indicate that all of the print pages have been provided printDoc.AddPagesComplete() End Sub
In this Quickstart, you added Windows printing to your app, without modifying how users interact with your app.
In the next tutorial, How to print using an in-app print button, you will invoke print functionality from a Windows Store app using C++, C#, or Visual Basic with a print button in the app. From there, you can explore some more advanced printing functions.
Your app can give the user even more print options, as How to change standard options in the print preview UI and How to add custom options to the print preview UI demonstrate.
And for more printing scenarios that are available in Windows Store apps, see the Windows Store app Print sample sample app.