实际开发过程中经常会遇到打印某种报表的情况,用C#实现打印报表的功能。第一,如果报表的大小合适,或者纸张的大小足够放得下报表,则可以选择直接截屏,打印截屏所得的图片;第二,如果报表和纸张的大小不匹配,则可能需要在程序中根据一定格式拼出合适大小的报表。
private void button3_Click(object sender, EventArgs e)
{
// 截屏
Form form = this;
if (form != null)
{
Graphics mygraphics = form.CreateGraphics();
memoryImage = new Bitmap(form.Width, form.Height, mygraphics);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(form.Location.X, form.Location.Y, 0, 0, form.Size);
}
// 设置打印文档名(如果使用Adobe PDF或者Microsoft Office Document Image Writer打印,则作为默认输出文件名)
this.printDocument1.DocumentName = this.label27.Text;
this.printDocument1.Print();
}
// printDocument1的PrintPage事件
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.Clear(Color.White);
e.Graphics.DrawImage(memoryImage, 0, 0);
}
//定义一个图片
private Bitmap memoryImage = null;
其中button3即为打印按钮,打印按钮的监听事件配置请自行完成(可直接在VS的button3的“属性”页中设置)。printDocument1为PrintDocument空间,请自行添加;其PrintPage事件的监听配置请自行完成。
private void button3_Click(object sender, EventArgs e)
{
this.printDocument1.DocumentName = this.label27.Text;
this.printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.Clear(Color.White);
// 开始绘制文档
// 默认为横排文字
e.Graphics.DrawString("标题",
new Font(new FontFamily("宋体"), 22, FontStyle.Bold),
System.Drawing.Brushes.Black,
170, 10);
e.Graphics.DrawString("性别:" + this.comboBox1.Text,
new Font(new FontFamily("宋体"), 14, FontStyle.Bold),
System.Drawing.Brushes.Black,
20, 50);
e.Graphics.DrawString("联系电话:" + this.textBox9.Text,
new Font(new FontFamily("宋体"), 14, FontStyle.Bold),
System.Drawing.Brushes.Black,
350, 50);
e.Graphics.DrawString("地址:" + this.textBox11.Text,
new Font(new FontFamily("宋体"), 14, FontStyle.Bold),
System.Drawing.Brushes.Black,
20, 80);
// 横线
e.Graphics.DrawLine(Pens.Black, 20, 110, 800, 110);
// 竖排文字
e.Graphics.DrawString("内容",
new Font(new FontFamily("宋体"), 14, FontStyle.Bold),
System.Drawing.Brushes.Black,
20, 120,
new StringFormat(StringFormatFlags.DirectionVertical));
}