使用C#在多个页面上打印大图像
问题描述:
我想写一些代码在多个页面上打印大图像(1200宽x 475高)。使用C#在多个页面上打印大图像
我试图在三个矩形(通过将宽度除以三)分割图像和调用e.Graphics.DrawImage三次,这是行不通的。
如果我在一个页面中指定大图像,它可以工作,但我该如何将图像分成多个页面?
答
诀窍是将图像的每个部分放入其自己的页面,并在PrintDocument
的PrintPage
事件中完成。
我认为最简单的方法是将图像拆分为单独的图像,每个图像一个。我会假设你已经可以处理它了(假设你尝试分割图像;同样的事情,只需将它们放在单独的图像上)。然后,我们创建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,如果你想后打印的文档显示预览)。
您的解决方案也适用于我,我一直在PrintDocument_PrintPage方法内重置页面索引为0,当它应该已经在PrintDocument_EndPrint方法中时... – coson 2009-07-11 17:31:27