将打印页面图形转换为位图 C#

3

我有一个应用程序,用户可以打印选定项目的文档作为发票。一切都运行良好,但是在PrintDocumentPrintPage事件中,我希望捕获文档或图形,将其转换为位图,以便稍后使用/查看时保存为.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代码,因为它有很多行。有没有一种方法可以将Graphics转换成Bitmap而不改变绘制图形到PrintDocument的任何代码?或者类似于这样做,可能复制文档并将其转换为位图?

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);
}

谢谢!我会尽快尝试,如果有效的话,我会回报的。 - matthewr

0

实际上,Yorye Nathan在2012年6月3日7:33的回答是正确的,并且这是帮助我的起点。然而,我无法按原样使其正常工作,因此我进行了一些更正以使其在我的应用程序中正常工作。更正是从PrintPgeEventArgs.Graphics设备上下文获取打印机页面大小,并将PrintPage Graphics作为新位图(...)构造的第三个参数。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接