背景:
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 }
