2010-08-28 149 views
6

我正在用WPF写一个笔记记录应用程序,每个笔记使用FlowDocument。该应用程序通过标签搜索和过滤笔记。我想将当前过滤列表中的所有笔记作为单独的文档打印出来,而且我只想在作业开始时显示一个打印对话框。WPF:打印没有打印对话框的FlowDocument

我发现了一个很好的打印示例in this thread,但它适用于打印单个FlowDocument,所以它使用显示打印对话框的CreateXpsDocumentWriter()过载。

所以,这里是我的问题:任何人都可以提出一些不错的代码来打印FlowDocument而不显示PrintDialog?我想我会在程序开始时显示“打印对话框”,然后循环显示我的笔记集以打印每个FlowDocument

回答

3

我已经重写了我对这个问题的回答,因为我找到了更好的方法来打印一组FlowDocuments,同时只显示一次Print对话框。答案来自MacDonald,Pro WPF在C#2008(Apress 2008)第20章中的p。 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"); 
} 

这是一个非常简单的方法,有一个显着的限制:它不会异步打印。要做到这一点,你必须在后台线程上执行这个操作,这就是我的做法。

+0

我仍然想找到一个更好的方法来做到这一点。如果有人可以提出建议,我会改变接受的答案。 – 2010-08-30 22:38:17

+3

您可以尝试使用PrintDialog.PrintQueue和PrintDialog.PrintTicket成员。使用PrintQueue您可以创建XpsDocumentWriter,然后您可以使用WriteAsync()异步打印。 缓存队列和票证似乎比缓存PrintDialog更好。 – 2010-10-06 19:21:54

+0

谢谢 - 这很有帮助。从我+1。 – 2010-10-07 19:06:42

1

你得到了printDialog之后只是一个循环。

for(int i=0 i<document.count i++) 
    printdocument((document[i] as iDocumentPaginator),"title"+[i]);