一、WPF 打印操作之PrintDocument,WPF获取打印机列表,WPF指定打印机

PrintDocument

定义一个可重用的对象,当从Windows Forms应用程序进行打印时,该对象将输出发送到打印机


通常,您将创建​​PrintDocument​​​类的实例,设置诸如​​DocumentName​​​和​​PrinterSettings之​​​类的属性,然后调用​​Print​​​方法来启动打印过程。通过使用​​PrintPageEventArgs​​​的​​Graphics ​​​​Graphics​​​属性,在您指定要打印输出的地方处理​​PrintPage​​事件。


注意:使用此类需要提前安装 System.Drawing.Common


WPF 打印操作之PrintDocument,WPF获取打印机列表,WPF指定打印机_WPF获取打印机列表

更多参考:

​https://docs.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument?view=dotnet-plat-ext-3.1​


二、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; }




更多:

​WPF 打印操作之PrintDialog​

​WPF 皮肤之MathApps.Metro UI库​

​WPF RichTextBox滚动条自动滚动实例、文本自动滚动实例​