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.
Scott Feb 03 '09 at 1:21 2009-02-03 01:21
source share