Search code examples
wpfxpsdocumentviewer

WPF - example of creating XPS document that is NOT from Visual


I'm looking for a reporting/printing solution that does not involve RDLC/SSRS. I'd like to use the DocumentViewer, which I know supports XPS. I have found plenty of examples that use Visual to XPS but I haven't found many examples where I can take an existing WPF page, with various controls like labels, listboxes, grids, etc and create that into an XPS document. Is there a code example out there that takes an entire XAML page and creates XPS?


Solution

  • It's not trivial, the basic problem here is that XPS represent fixed pages. An existing WPF page does not necessarily translate to pages on a document. How will your report be split if it cannot fit the page? This information is needed.

    What you can do is to create the report as a FlowDocument (see http://msdn.microsoft.com/en-us/library/aa970909.aspx). This will give the .NET framework enough info on how to paginate your report such that when you do this:

    FlowDocument flowDocument;
    
    // load, populate your flowDocument here
    
    XpsDocument xpsDocument = new XpsDocument("filename.xps", FileAccess.ReadWrite);
    XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
    writer.Write(((IDocumentPaginatorSource)flowDocument).DocumentPaginator);
    

    it works. (Code lifted from Pro WPF in C# Book).