c#图形创作

Pet*_*nge 0 c# printing graphics

我有一些代码用于以编程方式创建一个文档发送到打印机.它是这样的:

private void pd_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs ev) 
{      
      ev.Graphics.DrawImage(pictureBox1.Image, 50, 100);

      string drawToday="Date      : "+strToday;
      string drawPolicyNo="Policy # : " + strPolicyNo;
      string drawUser="User     : " + strUser;
      Font drawFont=new Font("Arial",30);
      SolidBrush drawBrush=new SolidBrush(Color.Black);
      PointF drawPointToday=new Point(50,400);
      PointF drawPointPolicyNo=new Point(50,450);
      PointF drawPointUser=new Point(50,500);
      ev.Graphics.DrawString(drawToday,drawFont,drawBrush,drawPointToday);
      ev.Graphics.DrawString(drawPolicyNo,drawFont,drawBrush,drawPointPolicyNo);
      ev.Graphics.DrawString(drawUser,drawFont,drawBrush,drawPointUser);
}
Run Code Online (Sandbox Code Playgroud)

它的有效代码,但现在我需要执行相同的过程,而是将其写入图像文件,以便可以将其发送到浏览器并从那里打印.重用这段代码应该相对简单,但不幸的是,我正在挂起用于替换PrintPageEventArgument的绘图表面.

谢谢

编辑:谢谢我得到的我只需要另一个Graphics对象,但Graphics对象本身没有公共构造函数,所以我要找的是关于我需要什么对象才能创建Graphics对象的建议借鉴.我想也许是位图?位图当然是基于像素而不是基于点的,所以我不确定这是最好的介质.

Fre*_*örk 5

如果我理解正确,你可以简单地将代码从事件处理程序分解为另一个接受Graphics对象作为参数的方法:

private void Print(Graphics g)
{
    g.DrawImage(pictureBox1.Image, 50, 100);

    string drawToday="Date      : "+strToday;
    string drawPolicyNo="Policy # : " + strPolicyNo;
    string drawUser="User     : " + strUser;
    Font drawFont=new Font("Arial",30);
    SolidBrush drawBrush=new SolidBrush(Color.Black);
    PointF drawPointToday=new Point(50,400);
    PointF drawPointPolicyNo=new Point(50,450);
    PointF drawPointUser=new Point(50,500);
    g.DrawString(drawToday,drawFont,drawBrush,drawPointToday);
    g.DrawString(drawPolicyNo,drawFont,drawBrush,drawPointPolicyNo);
    g.DrawString(drawUser,drawFont,drawBrush,drawPointUser);
}
Run Code Online (Sandbox Code Playgroud)

然后从事件处理程序中调用该方法:

private void pd_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs ev) 
{      
      Print(ev.Graphics);
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以重复使用相同的方法将输出打印到任何其他Graphics实例:

using (Bitmap img = new Bitmap(width, height))
using (Graphics g = Graphics.FromImage(img))
{
    Print(g);
    img.Save(fileName);
}
Run Code Online (Sandbox Code Playgroud)