2009-07-11 36 views
3

我想寫一些代碼在多個頁面上打印大圖像(1200寬x 475高)。使用C#在多個頁面上打印大圖像

我試圖在三個矩形(通過將寬度除以三)分割圖像和調用e.Graphics.DrawImage三次,這是行不通的。

如果我在一個頁面中指定大圖像,它可以工作,但我該如何將圖像分成多個頁面?

回答

3

訣竅是將圖像的每個部分放入其自己的頁面,並在PrintDocumentPrintPage事件中完成。

我認爲最簡單的方法是將圖像拆分爲單獨的圖像,每個圖像一個。我會假設你已經可以處理它了(假設你嘗試分割圖像;同樣的事情,只需將它們放在單獨的圖像上)。然後,我們創建PrintDocument的情況下,掛鉤PrintPage事件,並轉到:

private List<Image> _pages = new List<Image>(); 
private int pageIndex = 0; 

private void PrintImage() 
{ 
    Image source = new Bitmap(@"C:\path\file.jpg"); 
    // split the image into 3 separate images 
    _pages.AddRange(SplitImage(source, 3)); 

    PrintDocument printDocument = new PrintDocument(); 
    printDocument.PrintPage += PrintDocument_PrintPage; 
    PrintPreviewDialog previewDialog = new PrintPreviewDialog(); 
    previewDialog.Document = printDocument; 
    pageIndex = 0; 
    previewDialog.ShowDialog(); 
    // don't forget to detach the event handler when you are done 
    printDocument.PrintPage -= PrintDocument_PrintPage; 
} 

private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e) 
{ 
    // Draw the image for the current page index 
    e.Graphics.DrawImageUnscaled(_pages[pageIndex], 
           e.PageBounds.X, 
           e.PageBounds.Y); 
    // increment page index 
    pageIndex++; 
    // indicate whether there are more pages or not 
    e.HasMorePages = (pageIndex < _pages.Count); 
} 

請注意,您將需要重新打印文檔(例如之前的PageIndex重置爲0,如果你想後打印的文檔顯示預覽)。

+0

您的解決方案也適用於我,我一直在PrintDocument_PrintPage方法內重置頁面索引爲0,當它應該已經在PrintDocument_EndPrint方法中時... – coson 2009-07-11 17:31:27