我有一个应用程序,用户可以在其中以发票的形式打印所选项目的文档。一切正常,但是在 PrintDocument 的PrintPage
事件中,我想捕获文档或图形,将其转换为位图,以便我可以保存一个.bmp
以供以后使用/查看。(注:本文档有多个页面)我把它设置成这样:
PrintDocument doc = new PrintDocument();
doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
doc.Print();
然后在PrintPage
事件中:
private void doc_PrintPage(object sender, PrintPageEventArgs ev)
{
// Use ev.Graphics to create the document
// I create the document here
// After I have drawn all the graphics I want to get it and turn it into a bitmap and save it.
}
我已经删除了所有ev.Graphics
代码,因为它有很多行。有没有办法在不更改将图形绘制到PrintDocument
上的任何代码的情况下将图形转换为位图?或者做类似的事情,也许复制文档并将其转换为位图?
实际上,您应该将页面绘制到位图中,然后使用 ev。用于在页面上绘制该位图的图形。
private void doc_PrintPage(object sender, PrintPageEventArgs ev)
{
var bitmap = new Bitmap((int)graphics.ClipBounds.Width,
(int)graphics.ClipBounds.Height);
using (var g = Graphics.FromImage(bitmap))
{
// Draw all the graphics using into g (into the bitmap)
g.DrawLine(Pens.Black, 0, 0, 100, 100);
}
// And maybe some control drawing if you want...?
this.label1.DrawToBitmap(bitmap, this.label1.Bounds);
ev.Graphics.DrawImage(bitmap, 0, 0);
}
实际上,Yorye Nathan 在 6 月 3'12 7:33 的回答是正确的,这是帮助我的起点。 但是,我无法让它按原样工作,所以我做了一些更正,使其在我的应用程序中工作。 更正是从 PrintPgeEventArgs.Graphics 设备上下文中获取打印机的页面大小,并将 PrintPage 图形作为第三个参数包含在新的 Bitmap(...) 构造中。
private void doc_PrintPage(object sender, PrintPageEventArgs ppea)
{
// Retrieve the physical bitmap boundaries from the PrintPage Graphics Device Context
IntPtr hdc = ppea.Graphics.GetHdc();
Int32 PhysicalWidth = GetDeviceCaps(hdc, (Int32)PHYSICALWIDTH);
Int32 PhysicalHeight = GetDeviceCaps(hdc, (Int32)PHYSICALHEIGHT);
ppea.Graphics.ReleaseHdc(hdc);
// Create a bitmap with PrintPage Graphic's size and resolution
Bitmap myBitmap = new Bitmap(PhysicalWidth, PhysicalHeight, ppea.Graphics);
// Get the new work Graphics to use to draw the bitmap
Graphics myGraphics = Graphics.FromImage(myBitmap);
// Draw everything on myGraphics to build the bitmap
// Transfer the bitmap to the PrintPage Graphics
ppea.Graphics.DrawImage(myBitmap, 0, 0);
// Cleanup
myBitmap.Dispose();
}
////////
// Win32 API GetDeviceCaps() function needed to get the DC Physical Width and Height
const int PHYSICALWIDTH = 110; // Physical Width in device units
const int PHYSICALHEIGHT = 111; // Physical Height in device units
// This function returns the device capability value specified
// by the requested index value.
[DllImport("GDI32.DLL", CharSet = CharSet.Auto, SetLastError = true)]
public static extern Int32 GetDeviceCaps(IntPtr hdc, Int32 nIndex);
再次感谢Yorye Nathan提供原始答案。AJ