Convert WPF Management (XAML) to XPS Document

Can I use an existing WPF control (XAML), bind it to it and turn it into an XPS document that can be displayed and printed using the WPF XPS Document Viewer? If so, how? If not, how do I do reporting in WPF using XPS / PDF / etc?

Basically, I want to take an existing WPF control, bind it to it to get useful data, and then make it printable and save for the end user. Ideally, the creation of a document would be done in memory and would not get to disk, unless the user saved the document. Is it possible?

+42
c # wpf xaml xps
Feb 02 '09 at 4:36
source share
1 answer

Actually, after a mess with heaps of different patterns, all of which are incredibly confusing and require the use of documents, writers, containers, print queues and printed tickets, I found Eric Sanks's article on Printing in WPF
Simplified code - only 10 lines long

public void CreateMyWPFControlReport(MyWPFControlDataSource usefulData) { //Set up the WPF Control to be printed MyWPFControl controlToPrint; controlToPrint = new MyWPFControl(); controlToPrint.DataContext = usefulData; FixedDocument fixedDoc = new FixedDocument(); PageContent pageContent = new PageContent(); FixedPage fixedPage = new FixedPage(); //Create first page of document fixedPage.Children.Add(controlToPrint); ((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage); fixedDoc.Pages.Add(pageContent); //Create any other required pages here //View the document documentViewer1.Document = fixedDoc; } 

My example is quite simplified; it does not include the Page Size and Orientation options, which contain a number of problems that do not work as you expected. In addition, it does not contain any save functionality, since MS seems to have forgotten to turn on the Save button using the document viewer.

Save Functionality is relatively simple (and also from Eric Sanks article)

 public void SaveCurrentDocument() { // Configure save file dialog box Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "MyReport"; // Default file name dlg.DefaultExt = ".xps"; // Default file extension dlg.Filter = "XPS Documents (.xps)|*.xps"; // Filter files by extension // Show save file dialog box Nullable<bool> result = dlg.ShowDialog(); // Process save file dialog box results if (result == true) { // Save document string filename = dlg.FileName; FixedDocument doc = (FixedDocument)documentViewer1.Document; XpsDocument xpsd = new XpsDocument(filename, FileAccess.ReadWrite); System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd); xw.Write(doc); xpsd.Close(); } } 

So, the answer is β€œYes”, you can take an existing WPF control (XAML), bind it to it and turn it into an XPS document - and it’s not so difficult.

+61
Feb 03 '09 at 1:21
source share
β€” -



All Articles