使用PrintDocument进行打印

背景:

  1.在winform中,需要直接调用打印机,进行打印处理

      2.找了很多实现方法是web的处理,然后查了下度娘,发现可以使用自带类PrintDocument进行处理,所以就有了这篇文章

说明:

  使用PrintDocument需要有几个步骤,如下:

  1. 需要定义全局变量PrintDocument

  2. 需要定义一个文本控件做处理

  3. 在程序初始化的时候,需要将设置画布的方法,加入到PrintDocument对象的PrintPage方法中

  4. 将打印机名赋值给PrintDocument对象的PrinterSettings对象的PrinterName

  5. 在自定义的文本控件中加入需要打印的内容

  6. 调用PrintDocument的Print方法进行打印输出

代码实现:

 1        
 2         private PrintDocument pd = new PrintDocument();
 3 
 4         /// <summary>
 5         /// 打印内容使用TextBox控件printTextBox
 6         /// </summary>
 7         private TextBox printTextBox = new TextBox();
 8  
 9         public Form1()
10         {
11             InitializeComponent();
12             // 加入打印页面的设置处理
13             pd.PrintPage += printdocument_PrintPage;
14            // 关联打印机  赋值打印机的名字
15             pd.PrinterSettings.PrinterName = "Microsoft Print to PDF";
16         }
17         
18          /// <summary>
19          /// 将打印内容 画在打印文档对象中
20          /// </summary>
21         private void printdocument_PrintPage(object sender, PrintPageEventArgs e)
22         {
23             try
24             {
25                 Font fnt = printTextBox.Font;
26                 Graphics g = e.Graphics;
27                 long rowheight = printTextBox.Font.Height;  //行距
28                 for (int i = 0; i < printTextBox.Lines.Length; i++)
29                 {
30                     g.DrawString(printTextBox.Lines[i], fnt, bsh, 3, 10 + rowheight);
31                     rowheight += printTextBox.Font.Height;
32                 }
33                 g.Dispose();
34             }
35             catch (Exception)
36             {
37                 throw new Exception("打印失败!消息类型:2");
38             }
39   
40         }
41   
42         private void Form1_Load(object sender, EventArgs e)
43         {
44             /*
45               * 填写内容
46               */
47   
48             printTextBox.AppendText("测试处理");
49             // 执行打印
50             pd.Print();
51         }            
原文地址:https://www.cnblogs.com/NoRoad/p/6255916.html