Convert WPF (XAML) Control to XPS Document

匿名 (未验证) 提交于 2019-12-03 08:35:02

问题:

Can I take an Existing WPF (XAML) Control, databind 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 should I be doing ‘reporting’ in WPF using XPS/PDF/etc?

Basically I want to take an existing WPF control, databind it to get useful data into it and then make it printable and saveable for the end user. Ideally the document creation would be done in memory and wouldn’t hit the disk unless the user specifically saved the document. Is this feasible?

回答1:

Actually after messing around with heaps of different samples, all of which are incredibly convoluted and require the use of Document Writers, Containers, Print Queues and Print Tickets, I found Eric Sinks article about Printing in WPF
The simplified code is a mere 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 sample is fairly simplistic, it doesn't include Page Sizing and Orientation which contains a whole different set of issues that don't work as you would expect. Nor does it contain any save functionality as MS seem to have forgotten to include a Save button with the Document Viewer.

Save Functionality is relatively simple (and is also from Eric Sinks 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 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 (XAML) Control, databind it and turn it into an XPS document - and its not all that difficult.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!