2013-08-26 59 views
0

下面是我在Windows窗體中打印的過程。 我使用了PrintDocument類。它包含PrintPage事件,我用它來繪製我需要打印的圖形,並按我的預期成功獲得結果。在WPF中打印與Winforms相似

下面是代碼:

public PrintDocument Printing 
{ 
    m_printDocument = new PrintDocument(); 
    m_printDocument.PrintPage += new PrintPageEventHandler(OnPrintPage); 
} 

爲OnPrintPage的代碼如下:

protected virtual void OnPrintPage(object sender, PrintPageEventArgs e) 
{ 
     //Image img = I have the things to be printing in the form of image. 
     e.Graphics.DrawImage(img, new Point(0,0)); 
} 

在WPF:

我有固定的文件,並通過使用下面的代碼,我的工作可打印

PrintDialog print = new PrintDialog(); 
print.PrintDocument(FixedDocument.DocumentPaginator, "Print") //Where Fixed document contains the data to be printed. 

結果是內存不足以繼續執行程序。 但我得到固定文件沒有任何問題。 任何解決方案...? 我希望類似的東西就像Windows窗體一樣也會出現在WPF中...

回答

3

當我的頁面包含大量可視元素(圖形/圖像/複雜圖形)時,我曾經得到過這個。而不是一次打印完整的文檔(這可能導致內存不足)

print.PrintDocument(FixedDocument.DocumentPaginator, "Print") 

我打印了它的一頁。

PrintQueue selectedPrntQueue = printDialog.PrintQueue;  
XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(selectedPrntQueue); 
SerializerWriterCollator collator = writer.CreateVisualsCollator(); 
collator.BeginBatchWrite(); 
var paginator = FixedDocument.DocumentPaginator; 
FixedPage fixedPage = paginator.GetFixedPage(printedPageCount) 
ContainerVisual newPage = new ContainerVisual(); 
Size sz = new Size(pageSize.Height.Value, pageSize.Width.Value); 
fixedPage.Measure(sz); 
fixedPage.Arrange(new Rect(new Point(), sz)); 
fixedPage.UpdateLayout(); 
newPage.Children.Add(fixedPage); 
collator.Write(newPage); 

打印幾頁後我不得不做GC(我的幻數是10)。 您可能需要根據您的要求調整這一點。

+0

感謝朋友.... –

+0

這可直接打印到默認打印機。有沒有辦法讓我選擇打印機? –