WPF 打印操作之PrintDocument,WPF获取打印机列表,WPF指定打印机
一、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; }
更多:
分类:
C#-WPF
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
2015-05-01 WIN7系统JavaEE(java+tomcat7+Eclipse)环境配