- 添加PrintPreviewControl控件,并做如下设置,绑定printDocument控件:
- 初始化printdocument并绑定打印触发事件
1 2 3 4 5 | this.printDocument1.PrintController = null; //设置打印用的纸张,当设置为Custom的时候,可以自定义纸张的大小 printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custom", 800, 1150); //注册PrintPage事件,打印每一页时会触发该事件 printDocument1.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage); |
- 在画布上写内容:
1 2 3 4 5 6 7 8 9 10 11 12 | private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { //添加字符串 e.Graphics.DrawString("Hello World!", new Font(new FontFamily("宋体"), 10.5f), System.Drawing.Brushes.Black, x, y); //添加图片 e.Graphics.DrawImage(Image.FromFile(imgPath), x, y, imgwid,imgheg); //画线 Pen pen = new Pen(Color.Red, 2); e.Graphics.DrawLine(pen, x1, y1, x2, y2); //画矩形 e.Graphics.DrawRectangle(pen, x, y, wid, heg); } |
- 放大倍数设置,调整Zoom属性,值为1时放大倍数为100%,可设置成带小数的参数(0.75、1.2等)
- 分页:
1 2 | e.HasMorePages = true; printControl.Rows += 1; |
分页具体实现,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | int page=0; private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { if(page=0) { page++; //添加字符串 e.Graphics.DrawString("第一页", new Font(new FontFamily("宋体"), 10.5f), System.Drawing.Brushes.Black, x, y); e.HasMorePages = true; printControl.Rows += 1; } else { e.Graphics.DrawString("第二页", new Font(new FontFamily("宋体"), 10.5f), System.Drawing.Brushes.Black, x, y); } } |