How to Print Preview when using a DocumentPaginator to print?

So I got it working after reading Pro WPF in C# 2008 (Page 726).

Basically the DocumentViewer class needs an XPS file to present a print preview of it. So I do the following:

PrintDialog dialog = new PrintDialog();
var paginator = new RowPaginator(rowsToPrint) { PageSize = new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight) };

string tempFileName = System.IO.Path.GetTempFileName();

//GetTempFileName creates a file, the XpsDocument throws an exception if the file already
//exists, so delete it. Possible race condition if someone else calls GetTempFileName
using (XpsDocument xpsDocument = new XpsDocument(tempFileName, FileAccess.ReadWrite))
    XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);

    PrintPreview previewWindow = new PrintPreview
                                         Owner = this,
                                         Document = xpsDocument.GetFixedDocumentSequence()

I’m creating the print dialog to get the default page size. There’s probably a better way to do this.
XpsDocument is in ReachFramework.dll (Namespace System.Windows.Xps.Packaging);

Here’s the PrintPreview Window.

<Window x:Class="WPFPrintTest.PrintPreview"
    Title="PrintPreview" Height="800" Width="800">
        <DocumentViewer Name="viewer" 
                        Document="{Binding ElementName=previewWindow, Path=Document}" />

The code behind just has a Document property like so:

public IDocumentPaginatorSource Document
    get { return viewer.Document; }
    set { viewer.Document = value; }

Leave a Comment