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

mat*_*ewr 3 c# graphics bitmap

我有一个应用程序,用户可以以发票的形式打印所选项目的文档.一切都运行良好但是在PrintPagePrintDocument事件中我想要捕获文档或图形,将其转换为位图,以便我可以将其保存到.bmp以后供使用/查看.(注意:本文档中有多个页面)我将其设置如下:

PrintDocument doc = new PrintDocument();
doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
doc.Print();
Run Code Online (Sandbox Code Playgroud)

然后在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.
}
Run Code Online (Sandbox Code Playgroud)

我已经删除了所有ev.Graphics代码,因为它有很多行.有没有办法将图形转换为位图而不更改任何绘制图形的代码PrintDocument?或者做类似的事情,也许复制文档并将其转换为位图?

Sim*_*Var 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);
}
Run Code Online (Sandbox Code Playgroud)