3

我有一个应用程序,用户可以在其中以发票的形式打印所选项目的文档。一切正常,但是在PrintPage我想捕获文档或图形的 PrintDocument 事件中,将其转换为位图,以便我可以保存到它以.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?或者做类似的事情,也许复制文档并将其转换为位图?

4

2 回答 2

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);
}
于 2012-06-03T07:33:52.233 回答
0

实际上,Yorye Nathan 在 2012 年 6 月 3 日 7:33 的回答是正确的,这是帮助我的起点。但是,我无法让它按原样工作,所以我做了一些更正以使其在我的应用程序中工作。更正方法是从 PrintPgeEventArgs.Graphics 设备上下文中获取打印机的页面大小,并将 PrintPage Graphics 作为第三个参数包含在新的 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

于 2014-05-12T20:32:07.667 回答