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.Drawing
和 System.Drawing.Printing
命名空间的引用,并替换 imagePath
参数为实际的图片路径。