2010-08-28 71 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]);