Generating XPS Output

Whether you are printing, or writing your output to an XPS file, you can use the same API: the XpsDocumentWriter class. If you wish to print, you can obtain one of these from the printing API, as Example 15-9 shows.

Example 15-9. Obtaining an XpsDocumentWriter for printing

PrintDocumentImageableArea imageArea = null;
XpsDocumentWriter xpdw = PrintQueue.CreateXpsDocumentWriter(ref imageArea);
if (xpdw != null) {
    ...provide XpsDocumentWriter with output here...
}

This will cause the standard print dialog to be shown, allowing the user to select a printer. If the user cancels the dialog, CreateXpsDocumentWriter returns null, but otherwise it returns an XpsDocumentWriter, along with an object that describes the size of the target's paper and the margins of the printable area. If you wish to exercise more control over the print dialog and printer selection, there are several variations on this theme, described later in this chapter.

If you wish to send your output to an XPS file instead of a printer, you can obtain the document writer using the code shown in Example 15-10.

Example 15-10. Obtaining an XpsDocumentWriter for file output

using (XpsDocument xpsFile = new XpsDocument(xpsOutputPath, FileAccess.Write)) {
    XpsDocumentWriter xpdw = XpsDocument.CreateXpsDocumentWriter(xpsFile);

    ...provide XpsDocumentWriter with output here...

}

Once you have obtained an XPS document writer, you can use the same code whether you are writing to an XPS file or to a printer. For clarity, ...

Get Programming WPF, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.