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

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

PrintDocument

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

 

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

 

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

 

更多参考:

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滚动条自动滚动实例、文本自动滚动实例

posted @   天马3798  阅读(5459)  评论(0编辑  收藏  举报
编辑推荐:
· 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)环境配
点击右上角即可分享
微信分享提示