使用IRONPRINT

如何在C#中将文件打印到打印机

发布 2024年四月29日
分享:

从 C# 应用程序直接打印 PDF 文件是一项非常有价值的功能,尤其是在开发需要与物理 PDF 文档无缝集成的应用程序时。无论您是在开发 PDF 文档管理系统、销售点应用程序,还是其他任何与打印有关的软件,C# 都能提供一套强大的库来促进 PDF 打印方法功能的实现。

为此,Microsoft C# 提供了一个 打印方法 将 PDF 文件打印到默认打印机。在本文中,我们将探讨使用 C# 将 PDF 文件打印到打印机的步骤。

如何在 C&num 中将文件打印到打印机;

1.创建 C# Windows 窗体应用程序

2.使用关键字导入 System.Drawing.Printing

3.设计带有按钮和其他必要控件的表单

4.使用PrintPage事件处理PrintDocument事件

5.启动打印工作

6.运行应用程序并单击打印按钮进行打印

先决条件

在开始之前,请确保具备以下先决条件:

1.C# 开发环境 (例如,Visual Studio).

2.拥有与打印机交互的足够权限。

3.对 C# 编程有基本了解。

第 1 步:设置项目

在首选开发环境中创建一个新的 C# 项目或打开一个现有项目。确保项目配置正确,并拥有打印机交互所需的权限。您可以通过以下流程完成此过程:

安装 Visual Studio

如果没有安装 Visual Studio,请从官方网站下载并安装: 视觉工作室.

创建一个新项目

1.打开 Visual Studio。

2.点击 "创建新项目"。

如何在 C# 中将文件打印到打印机:图 1 - 新项目

选择项目模板

1.在 "创建新项目 "对话框中,选择 "Windows 窗体应用程序 (.NET框架)"或 "Windows 窗体应用程序 (.NET Core)"根据您的喜好。

如何在 C# 中将文件打印到打印机:图 2 - Windows 窗体应用程序

2.提供项目名称和地点。

如何在 C# 中将文件打印到打印机:图 3 - 项目配置

3.单击 "下一步",在 "附加信息 "屏幕中选择 .NET Framework,然后单击 "创建"。

设计表格

1.项目创建后,主表单将显示在设计器中。

2.使用工具箱可根据需要在表单中添加按钮、文本框、标签等控件。

3.使用属性窗口自定义每个控件的属性。

如何在 C# 中将文件打印到打印机:图 4 - 表单设计

4.调整表单的外观和布局。

如何在 C# 中将文件打印到打印机:图 5 - 打印表单

第 2 步:导入所需库函数

在 C# 代码文件中,导入必要的命名空间,以访问与打印相关的类和方法。

using System.Drawing.Printing;
using System.Drawing.Printing;
Imports System.Drawing.Printing
VB   C#

这些命名空间提供了重要的类,如 PrintDocumentPrintPageEventArgsPrintController,用于处理打印操作。

第 3 步:处理打印文档事件

PrintDocument 类是 C# 中打印的基石。处理其 PrintPage 事件可定义要打印的内容及其格式。让我们从打印文本文件内容的简单示例开始:

private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
    // Specify the file path
    string filePath = "C:\\path\\to\\your\\file.txt";
    // Read the content of the file
    string line = System.IO.File.ReadAllText(filePath);
    // Create a Font object (adjust as needed)
    Font font = new Font("Arial", 12);
    // Create a RectangleF to define the printing area
    RectangleF area = new RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height);
    // Draw the content to the printing area
    e.Graphics.DrawString(line, font, Brushes.Black, area);
    // Set HasMorePages to false to indicate that there are no more pages to print
    e.HasMorePages = false;
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
    // Specify the file path
    string filePath = "C:\\path\\to\\your\\file.txt";
    // Read the content of the file
    string line = System.IO.File.ReadAllText(filePath);
    // Create a Font object (adjust as needed)
    Font font = new Font("Arial", 12);
    // Create a RectangleF to define the printing area
    RectangleF area = new RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height);
    // Draw the content to the printing area
    e.Graphics.DrawString(line, font, Brushes.Black, area);
    // Set HasMorePages to false to indicate that there are no more pages to print
    e.HasMorePages = false;
}
Private Sub printDocument1_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)
	' Specify the file path
	Dim filePath As String = "C:\path\to\your\file.txt"
	' Read the content of the file
	Dim line As String = System.IO.File.ReadAllText(filePath)
	' Create a Font object (adjust as needed)
	Dim font As New Font("Arial", 12)
	' Create a RectangleF to define the printing area
	Dim area As New RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height)
	' Draw the content to the printing area
	e.Graphics.DrawString(line, font, Brushes.Black, area)
	' Set HasMorePages to false to indicate that there are no more pages to print
	e.HasMorePages = False
End Sub
VB   C#

此示例读取文本文件的内容,并使用指定的字体和格式进行打印。

步骤 4:启动打印任务

创建PrintDocument类的实例,附加PrintPage事件处理程序,然后触发打印过程,从而启动打印任务。您还可以选择显示打印对话框,供用户配置:

private void btnPrint_Click(object sender, EventArgs e)
{
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
    // Optionally, display a print dialog for user configuration
    PrintDialog printDialog = new PrintDialog();
    if (printDialog.ShowDialog() == DialogResult.OK)
    {
        pd.PrinterSettings = printDialog.PrinterSettings;
        pd.Print();
    }
}
private void btnPrint_Click(object sender, EventArgs e)
{
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
    // Optionally, display a print dialog for user configuration
    PrintDialog printDialog = new PrintDialog();
    if (printDialog.ShowDialog() == DialogResult.OK)
    {
        pd.PrinterSettings = printDialog.PrinterSettings;
        pd.Print();
    }
}
Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As EventArgs)
	Dim pd As New PrintDocument()
	AddHandler pd.PrintPage, AddressOf printDocument1_PrintPage
	' Optionally, display a print dialog for user configuration
	Dim printDialog As New PrintDialog()
	If printDialog.ShowDialog() = DialogResult.OK Then
		pd.PrinterSettings = printDialog.PrinterSettings
		pd.Print()
	End If
End Sub
VB   C#

该代码创建一个 PrintDocument 实例,附加 PrintPage 事件处理程序,然后打印文档。可选的打印对话框允许用户在启动打印任务前配置打印设置。这将把文本文档打印到本地连接的打印机上。如果没有本地连接的打印机,文件将被打印到默认的打印机名称上。 (微软打印成 PDF) 如下图所示:

如何在 C# 中将文件打印到打印机:图 6 - Microsoft 打印对话框

C&num中的高级打印;通过IronPrint库

要在 C# 控制台应用程序中高效处理打印功能,IronPrint 库提供了一个强大的解决方案。

IronPrint 简介

铁印 是 Iron Software 开发的一个综合打印库,旨在与 .NET 应用程序无缝集成。无论您是在处理桌面、网络还是移动项目,IronPrint 都能提供多功能打印 PDF 文档的功能,支持各种文件格式并提供可定制的打印设置。

如何在 C# 中将文件打印到打印机:图 7 - IronPrint

主要功能

  1. 格式支持: IronPrint 支持多种文档格式,包括 PDF、PNG、HTML、TIFF、GIF、JPEG 和 BITMAP。这种多功能性确保了开发人员可以处理不同类型的打印内容。

  2. 可定制的设置: 开发人员可根据其应用程序的要求灵活定制打印设置。这包括设置 DPI (每英寸点数), 指定纸张方向 (纵向或横向)并控制副本的数量。

  3. 打印对话框: IronPrint 允许开发人员在打印前显示打印对话框,为用户提供无缝体验。这在用户需要与打印过程交互并选择特定选项的情况下非常有用。

  4. 跨平台兼容性: IronPrint 超越了平台限制,可兼容各种环境,包括 Windows、Mac OS X 和 Linux。 (7+)MacOS (10+)iOS (11+)和安卓应用程序接口 21+ (v5 "棒棒糖").它可与不同的项目类型无缝集成,如移动 (Xamarin、MAUI 和 Avalonia)桌面 (WPF、MAUI 和 Windows Avalonia)和控制台 (应用程序和图书馆).

  5. 广泛的 .NET 版本支持: 无论您使用的是最新的 .NET 8、7、6 还是 Core 3.1+,IronPrint 都能为您提供支持。它还扩展了对 .NET Framework 的支持。 (4.6.2+)确保各种开发环境的兼容性。

安装 IronPrint

在深入研究文件打印之前,您需要安装 IronPrint 库。您可以使用 NuGet 软件包管理器控制台轻松完成安装:

Install-Package IronPrint

此命令行将下载 IronPrint 库并安装到您的 C# 项目中。

初始化 IronPrint

安装 IronPrint 后,需要在 C# 代码中对其进行初始化。导入 IronPrint 命名空间,并设置许可证密钥以确保功能正常:

using IronPrint;
class Program
{
    public static void Main()
    {
        License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
    }
}
using IronPrint;
class Program
{
    public static void Main()
    {
        License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
    }
}
Imports IronPrint
Friend Class Program
	Public Shared Sub Main()
		License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY"
	End Sub
End Class
VB   C#

使用 IronPrint 打印文件

使用 IronPrint 打印文件非常简单。您可以使用 打印机 类,为 Print 方法指定文件路径,以静默方式打印 PDF:

using IronPrint;
class Program
{
// static void main
    public static void Main()
    {
        License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
        // Specify the file path
        var document = "C:\\path\\to\\your\\file.pdf";
        // Print PDFs
        Printer.Print(document);
    }
}
using IronPrint;
class Program
{
// static void main
    public static void Main()
    {
        License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
        // Specify the file path
        var document = "C:\\path\\to\\your\\file.pdf";
        // Print PDFs
        Printer.Print(document);
    }
}
Imports IronPrint
Friend Class Program
' static void main
	Public Shared Sub Main()
		License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY"
		' Specify the file path
		Dim document = "C:\path\to\your\file.pdf"
		' Print PDFs
		Printer.Print(document)
	End Sub
End Class
VB   C#

本例演示打印 PDF 文件,但 IronPrint 支持多种文件格式,包括 PDF、PNG、HTML、TIFF、GIF、JPEG、IMAGE 和 BITMAP。

自定义打印设置

IronPrint 允许您自定义 打印设置 根据应用程序的要求进行设置。您可以使用 PrintSettings 类配置 DPI、份数、纸张方向等设置。以下代码示例可帮助您设置页面设置并打印 PDF 文档:

using IronPrint;
class Program
{
    public static void Main()
    {
        IronPrint.License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
    Console.WriteLine("Printing Started...");
        // Specify the file path
        string filePath = "C:\\path\\to\\your\\file.pdf";
        // Configure print settings
        PrintSettings printSettings = new PrintSettings();
        printSettings.Dpi = 300;
        printSettings.NumberOfCopies = 2;
        printSettings.PaperOrientation = PaperOrientation.Landscape;
        // Print the document with custom settings
        Printer.Print(filePath, printSettings);
    // Print using the Print dialog
    Printer.ShowPrintDialog(filePath, printSettings);
    }
}
using IronPrint;
class Program
{
    public static void Main()
    {
        IronPrint.License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
    Console.WriteLine("Printing Started...");
        // Specify the file path
        string filePath = "C:\\path\\to\\your\\file.pdf";
        // Configure print settings
        PrintSettings printSettings = new PrintSettings();
        printSettings.Dpi = 300;
        printSettings.NumberOfCopies = 2;
        printSettings.PaperOrientation = PaperOrientation.Landscape;
        // Print the document with custom settings
        Printer.Print(filePath, printSettings);
    // Print using the Print dialog
    Printer.ShowPrintDialog(filePath, printSettings);
    }
}
Imports IronPrint
Friend Class Program
	Public Shared Sub Main()
		IronPrint.License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY"
	Console.WriteLine("Printing Started...")
		' Specify the file path
		Dim filePath As String = "C:\path\to\your\file.pdf"
		' Configure print settings
		Dim printSettings As New PrintSettings()
		printSettings.Dpi = 300
		printSettings.NumberOfCopies = 2
		printSettings.PaperOrientation = PaperOrientation.Landscape
		' Print the document with custom settings
		Printer.Print(filePath, printSettings)
	' Print using the Print dialog
	Printer.ShowPrintDialog(filePath, printSettings)
	End Sub
End Class
VB   C#

输出结果如下:

如何在 C# 中将文件打印到打印机:图 8 - 自定义打印输出

如果没有安装物理打印机,则使用默认打印机打印 PDF 文档。要获取所有可用的打印机,也可以使用 获取打印机名称 方法。

// Retrieve printers' name
List<string> printersName = Printer.GetPrinterNames();
foreach (string printer in printersName)
{
    Console.WriteLine(printer);
}
// Retrieve printers' name
List<string> printersName = Printer.GetPrinterNames();
foreach (string printer in printersName)
{
    Console.WriteLine(printer);
}
' Retrieve printers' name
Dim printersName As List(Of String) = Printer.GetPrinterNames()
For Each printer As String In printersName
	Console.WriteLine(printer)
Next printer
VB   C#

更多详细信息,请访问 文件 page.

结论

利用System.Drawing.Printing命名空间提供的功能,在 C# 中打印文件是一项易于管理的任务。通过处理PrintPage事件和利用PrintDocument类,您可以根据自己的具体要求定制打印过程。本综合指南涵盖了从 C# 应用程序打印文件的基本步骤,为您将此功能集成到项目中奠定了坚实的基础。在进一步探索的过程中,我们研究了 IronPrint 的其他自定义选项,例如处理不同的文件类型、合并图像以及根据应用程序的需求增强格式。

将 IronPrint 集成到 C# 应用程序中可简化将文件打印到打印机的过程。IronPrint 支持各种文件格式和可定制的打印设置,为希望增强打印功能的开发人员提供了强大的解决方案。无论您是在开发桌面、Web 还是移动项目,IronPrint 都能简化打印过程,使其成为您的 .NET 工具包的重要补充。

IronPrint 提供了 免费试用 页面获取更多信息。从以下网址下载图书馆 *这里*** 并试一试。

< 前一页
如何在C#中打印QR码
下一步 >
如何在C#中打印QR码

准备开始了吗? 版本: 2024.8 刚刚发布

免费NuGet下载 总下载量: 7,289 查看许可证 >