How to: Invoke a Print Dialog

To provide the ability to print from you application, you can simply create and open a PrintDialog object.

The PrintDialog control provides a single entry point for UI, configuration, and XPS job submission. The control is easy to use and can be instantiated by using Extensible Application Markup Language (XAML) markup or code. The following example demonstrates how to instantiate and open the control in code and how to print from it. It also shows how to ensure that the dialog will give the user the option of setting a specific range of pages. The example code assumes that there is a file FixedDocumentSequence.xps in the root of the C: drive.


private void InvokePrint(object sender, RoutedEventArgs e)
    {
        // Create the print dialog object and set options
        PrintDialog pDialog = new PrintDialog();
        pDialog.PageRangeSelection = PageRangeSelection.AllPages;
        pDialog.UserPageRangeEnabled = true;

        // Display the dialog. This returns true if the user presses the Print button.
        Nullable<Boolean> print = pDialog.ShowDialog();
        if (print == true)
        {
            XpsDocument xpsDocument = new XpsDocument("C:\\FixedDocumentSequence.xps", FileAccess.ReadWrite);
            FixedDocumentSequence fixedDocSeq = xpsDocument.GetFixedDocumentSequence();
            pDialog.PrintDocument(fixedDocSeq.DocumentPaginator, "Test print job");
        }
    }


Once the dialog is open, users will be able to select from the printers installed on their computer. They will also have the option of selecting the Microsoft XPS Document Writer to create an XML Paper Specification (XPS) file instead of printing.

NoteNote

The System.Windows.Controls.PrintDialog control of WPF, which is discussed in this topic, should not be confused with the System.Windows.Forms.PrintDialog component of Windows Forms.

Strictly speaking, you can use the PrintDocument method without ever opening the dialog. In that sense, the control can be used as an unseen printing component. But for performance reasons, it would be better to use either the AddJob method or one of the many Write and WriteAsync methods of the XpsDocumentWriter. For more about this, see How to: Programmatically Print XPS Files and .

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft