winform 自动获取默认打印机并打印图片

using System.Drawing;
using System.Drawing.Printing;

private void PrintImage(string imagePath)
{
    // 创建 PrintDocument 对象
    PrintDocument pd = new PrintDocument();

    // 设置打印机
    pd.PrinterSettings.PrinterName = GetDefaultPrinterName();

    // 设置打印控制器为 StandardPrintController,以禁用打印对话框
    pd.PrintController = new StandardPrintController();

    // 注册 PrintPage 事件处理程序
    pd.PrintPage += (sender, e) => PrintPageHandler(sender, e, imagePath);

    // 调用 Print 方法开始打印
    pd.Print();
}

private void PrintPageHandler(object sender, PrintPageEventArgs e, string imagePath)
{
    // 加载图片
    using (Image image = Image.FromFile(imagePath))
    {
        // 计算图片需要打印的区域
        Rectangle printArea = e.MarginBounds;

        // 将图片调整为适合打印区域的大小
        if (image.Width > printArea.Width || image.Height > printArea.Height)
        {
            float aspectRatio = (float)image.Width / (float)image.Height;
            int newWidth = printArea.Width;
            int newHeight = (int)(printArea.Width / aspectRatio);

            if (newHeight > printArea.Height)
            {
                newHeight = printArea.Height;
                newWidth = (int)(printArea.Height * aspectRatio);
            }

            printArea.Width = newWidth;
            printArea.Height = newHeight;
        }

        // 将图片绘制到打印区域上
        e.Graphics.DrawImage(image, printArea);
    }
}

//获取默认打印机名称
private string GetDefaultPrinterName()
{
    string defaultPrinterName = string.Empty;

    using (var printDocument = new PrintDocument())
    {
        defaultPrinterName = printDocument.PrinterSettings.PrinterName;
    }

    return defaultPrinterName;
}

在上述示例中,我们首先创建了一个 PrintDocument 对象,并使用 GetDefaultPrinterName() 方法获取到默认打印机的名称。然后,我们将打印控制器设置为 StandardPrintController,以禁用打印对话框。

接下来,我们通过注册 PrintPage 事件处理程序,在每一页准备好打印时触发。在事件处理程序中,我们加载要打印的图片,并计算出适合打印区域的大小。最后,我们使用 DrawImage 方法将图片绘制到打印区域上。

最后,我们调用 PrintImage() 方法并传入要打印的图片路径,即可自动获取默认打印机并进行打印。

请确保在使用前已经添加了对 System.DrawingSystem.Drawing.Printing 命名空间的引用,并替换 imagePath 参数为实际的图片路径。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值