Dav*_*man 6 printing wpf flowdocument
我正在WPF中写一个笔记记录应用程序,使用FlowDocument每个单独的笔记.该应用按标签搜索和过滤笔记.我想将当前筛选列表中的所有笔记打印为单独的文档,我只想在作业开头显示一个打印对话框.
我在这个帖子中找到了一个很好的打印示例,但它适用于打印单个FlowDocument,因此它使用CreateXpsDocumentWriter()显示打印对话框的重载.
所以,这是我的问题:任何人都可以提出一些好的代码来打印一个FlowDocument没有显示PrintDialog?我想我会在程序开始时显示打印对话框,然后循环我的笔记集以打印每个FlowDocument.
我重写了这个问题的答案,因为我确实找到了一种更好的方法来打印一组 FlowDocuments,同时仅显示一次打印对话框。答案来自 MacDonald,Pro WPF in C# 2008 (Apress 2008) 第 20 章,第 20 页。704.
我的代码将一组 Note 对象捆绑到一个名为notesToPrint 的 IList 中,并从我的应用程序中的 DocumentServices 类获取每个 Note 的 FlowDocument。它设置 FlowDocument 边界以匹配打印机并设置 1 英寸边距。然后,它使用文档的 DocumentPaginator 属性打印 FlowDocument。这是代码:
// Show Print Dialog
var printDialog = new PrintDialog();
var userCanceled = (printDialog.ShowDialog() == false);
if(userCanceled) return;
// Print Notes
foreach(var note in notesToPrint)
{
// Get next FlowDocument
var collectionFolderPath = DataStore.CollectionFolderPath;
var noteDocument = DocumentServices.GetFlowDocument(note, collectionFolderPath) ;
// Set the FlowDocument boundaries to match the page
noteDocument.PageHeight = printDialog.PrintableAreaHeight;
noteDocument.PageWidth = printDialog.PrintableAreaWidth;
// Set margin to 1 inch
noteDocument.PagePadding = new Thickness(96);
// Get the FlowDocument's DocumentPaginator
var paginatorSource = (IDocumentPaginatorSource)noteDocument;
var paginator = paginatorSource.DocumentPaginator;
// Print the Document
printDialog.PrintDocument(paginator, "FS NoteMaster Document");
}
Run Code Online (Sandbox Code Playgroud)
这是一种非常简单的方法,但有一个重大限制:它不能异步打印。为此,您必须在后台线程上执行此操作,这就是我的做法。