2010-12-15 79 views
4

我有一個窗口對象,我想創建,設置一些值,然後直接發送到打印機而不顯示它。我認爲這是正確的做法,但顯示一個空白的文檔。在WPF中打印隱藏窗口

PrintDialog dlg = new PrintDialog(); 

ReportWindow rw = new ReportWindow(); //WPF Window object 

var sz = new Size(96*8.5, 96*11);  //size of a paper page, 8.5x11 

rw.Measure(sz); rw.Arrange(new Rect(sz)); 

// rw.Show(); //want to keep it hidden 

dlg.PrintVisual(rw, "report printout"); 

rw.Close(); 

要驗證打印代碼是好的,我把它的形式加載事件中,調用Show(),它工作正常。

+0

沒有它被渲染我懷疑視覺上就會產生。 – user7116 2010-12-15 17:08:21

+0

並且沒有辦法讓它在不調用Show()的情況下渲染? – 2010-12-15 20:14:23

+2

只是一個瘋狂的想法,如果你將窗口顯示在屏幕之外的某個地方,而沒有在任務欄中顯示並且沒有激活它,該怎麼辦? – 2010-12-15 21:08:08

回答

3

沒有必要創建一個隱藏的窗口,您可以通過使用DocumentPage呈現WPF控件進行打印。要打印DocumentPage s,您需要擴展DocumentPaginator類。

執行簡單DocumentPaginator的代碼將打印出UIElements的任何List如下。

class DocumentPaginatorImpl : DocumentPaginator 
{ 
    private List<UIElement> Pages { get; set; } 

    public DocumentPaginatorImpl(List<UIElement> pages) 
    { 
     Pages = pages; 
    } 

    public override DocumentPage GetPage(int pageNumber) 
    { 
     return new DocumentPage(Pages[pageNumber]); 
    } 

    public override bool IsPageCountValid 
    { 
     get { return true; } 
    } 

    public override int PageCount 
    { 
     get { return Pages.Count; } 
    } 

    public override System.Windows.Size PageSize 
    { 
     get 
     { 
      /* Assume the first page is the size of all the pages, for simplicity. */ 
      if (Pages.Count > 0) 
      { 
       UIElement page = Pages[0]; 

       if (page is Canvas) 
        return new Size(((Canvas)page).Width, ((Canvas)page).Height); 
       // else if ... 
      } 

      return Size.Empty; 
     } 
     set 
     { 
      /* Ignore the PageSize suggestion. */ 
     } 
    } 

    public override IDocumentPaginatorSource Source 
    { 
     get { return null; } 
    } 
} 

最後,做印刷,你只需要:

dialog.PrintDocument(new DocumentPaginatorImpl(pages), "Print Job Description");