[英]Convert WPF (XAML) Control to XPS Document
我可以使用現有的WPF(XAML)控件,對其進行數據綁定並將其轉換為可以使用WPF XPS文檔查看器顯示和打印的XPS文檔嗎? 如果是這樣,怎么樣? 如果沒有,我應該如何使用XPS / PDF /等在WPF中進行“報告”?
基本上我想采用現有的WPF控件,數據綁定它以獲取有用的數據,然后使其可打印並可供最終用戶保存。 理想情況下,文檔創建將在內存中完成,除非用戶專門保存文檔,否則不會訪問磁盤。 這可行嗎?
事實上,在弄亂了大量不同的樣本之后,所有這些都令人難以置信的復雜並且需要使用文檔編寫器,容器,打印隊列和打印票證,我找到了Eric Sinks關於在WPF中打印的文章
簡化的代碼只有10行
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;
}
我的示例相當簡單,它不包括頁面大小和方向,其中包含一組完全不同的問題。 它也不包含任何保存功能,因為MS似乎忘記在文檔查看器中包含“保存”按鈕。
保存功能相對簡單(也來自Eric Sinks的文章)
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();
}
}
所以答案是肯定的,您可以使用現有的WPF(XAML)控件,對其進行數據綁定並將其轉換為XPS文檔 - 並不是那么困難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.