views:

719

answers:

2

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?

A: 

Usually your WPF page has a root UI element, say Grid. As Grid is a specific type of Visual(please vide "Inheritance Hierarchy" part @http://msdn.microsoft.com/en-us/library/system.windows.controls.grid.aspx for more details), you just need to write that root Grid element like other visuals into XPS. And then all embedded controls will be automatically written into XPS document.

YIMING ZENG
+1  A: 

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).

moogs