我有一个应用程序,用户可以以发票的形式打印所选项目的文档。一切正常,但是在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
上的代码?或者做类似的事情,也许复制文档并将其转换为位图?
答案 0 :(得分:5)
您应该将页面绘制到位图中,然后使用ev.Graphics在页面上绘制该位图。
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);
}
答案 1 :(得分:0)
实际上,Yorye Nathan在6月3日和12日在7:33的回答是正确的,这是帮助我的起点。但是,我无法让它按原样运行,所以我做了一些修正,使其在我的应用程序中工作。更正是从PrintPgeEventArgs.Graphics设备上下文获取打印机的页面大小,并在新的位图(...)构造中包含PrintPage图形作为第三个参数。
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