一、WPF 打印操作之PrintDocument,WPF獲取打印機列表,WPF指定打印機
PrintDocument
定義一個可重用的對象,當從Windows Forms應用程序進行打印時,該對象將輸出發送到打印機
通常,您將創建PrintDocument類的實例,設置諸如DocumentName和PrinterSettings之類的屬性,然后調用Print方法來啟動打印過程。通過使用PrintPageEventArgs的Graphics Graphics屬性,在您指定要打印輸出的地方處理PrintPage事件。
注意:使用此類需要提前安裝 System.Drawing.Common
更多參考:
二、wpf獲取系統可用打印機列表
//獲取打印機列表 StringCollection strList = PrinterSettings.InstalledPrinters;
使用打印機名稱,指定特定的打印機進行打印。
PrintDocument pd = new PrintDocument(); pd.PrinterSettings.PrinterName = "Canon TS3100 series (副本 1)";
三、打印示例
Font printFont = null; StreamReader streamToPrint = null; private void Button_Click_1(object sender, RoutedEventArgs e) { try { streamToPrint = new StreamReader ("G:\\桌面\\新建文本文檔.txt"); try { printFont = new Font("Arial", 10); PrintDocument pd = new PrintDocument(); pd.PrinterSettings.PrinterName = "Canon TS3100 series (副本 1)"; pd.PrintPage += new PrintPageEventHandler (this.pd_PrintPage); pd.Print(); } finally { streamToPrint.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } // The PrintPage event is raised for each page to be printed. private void pd_PrintPage(object sender, PrintPageEventArgs ev) { float linesPerPage = 0; float yPos = 0; int count = 0; float leftMargin = ev.MarginBounds.Left; float topMargin = ev.MarginBounds.Top; string line = null; // Calculate the number of lines per page. linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics); // Print each line of the file. while (count < linesPerPage && ((line = streamToPrint.ReadLine()) != null)) { yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); ev.Graphics.DrawString(line, printFont, System.Drawing.Brushes.Black, leftMargin, yPos, new StringFormat()); count++; } // If more lines exist, print another page. if (line != null) ev.HasMorePages = true; else ev.HasMorePages = false; }
更多: