使用 IRONPRINT

如何在 C# 中將檔案列印到印表機

查克尼思·賓
查克尼思·賓
2024年4月29日
分享:

從 C# 應用程序直接列印 PDF 檔案可以是一個非常有價值的功能,尤其是在開發需要與實體 PDF 文件無縫整合的應用程序時。 無論您是在開發 PDF 文檔管理系統、銷售點應用程式,還是其他與列印相關的軟體,C# 都提供了一套強大的庫來促進這個 PDF 列印方法的功能實現。

為此,Microsoft C# 提供了一個列印方法,用於將 PDF 文件列印到預設的印表機。 在本文中,我們將探索使用 C# 將 PDF 文件打印到打印機的步驟。

如何在 C# 中將文件打印到打印機

  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,請從官方網站下載並安裝:Visual Studio

建立新專案

  1. 打開 Visual Studio。

    1. 點擊「創建新專案」。

    如何在 C# 中將檔案列印到印表機:圖 1 - 新專案

選擇專案範本

  1. 在「建立新專案」對話方塊中,根據您的偏好選擇「Windows Forms App (.NET Framework)」或「Windows Forms App (.NET Core)」。

    如何在 C# 中將檔案列印到打印機:圖 2 - Windows Forms 應用程式

  2. 為您的專案提供名稱和位置。

    如何在 C# 中將文件列印到印表機:圖 3 - 專案配置

  1. 點擊下一步,從附加資訊畫面中選擇 .NET Framework,然後點擊「建立」。

設計表單

  1. 一旦專案建立,主表單將會在設計器中顯示。

  2. 使用工具箱按需將控制元件如按鈕、文本框、標籤等添加到您的表單中。

    1. 使用「屬性」視窗自訂每個控制項的屬性。

    如何在 C# 中將文件列印到印表機:圖 4 - 表單設計

    1. 調整表單的外觀和佈局。

    如何在 C# 中將檔案打印到打印機:圖 5 - 列印表單

第 2 步:導入所需的函式庫

在您的 C# 程式碼檔案中,匯入必要的命名空間,以存取與列印相關的類別和方法。

using System.Drawing.Printing;
using System.Drawing.Printing;
Imports System.Drawing.Printing
$vbLabelText   $csharpLabel

這些命名空間提供了處理打印操作所需的重要類,例如PrintDocumentPrintPageEventArgsPrintController

第 3 步:處理 PrintDocument 事件

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
$vbLabelText   $csharpLabel

此範例會讀取文字檔案的內容,並使用指定的字體和格式進行列印。

步驟四:啟動列印工作

通過創建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
$vbLabelText   $csharpLabel

此程式碼建立一個PrintDocument實例,附加PrintPage事件處理程序,然後列印文件。 可選的列印對話框允許用戶在開始列印作業之前配置列印設定。 這會將文字文件列印到本地連接的打印機。 如果不存在,則將檔案列印到「列印」對話框中顯示的預設印表機名稱(Microsoft Print to PDF):

如何在 C# 中將檔案列印到印表機:圖 6 - Microsoft 列印對話框

使用 IronPrint 函式庫在 C# 中的高級列印

在 C# 控制台應用程式中有效且高效地處理列印功能時,IronPrint 函式庫提供了一個強大的解決方案。

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 (7+)、macOS (10+)、iOS (11+) 和 Android API 21+ (v5 "Lollipop")。 它可無縫整合不同專案類型,如移動端 (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 Package Manager Console 輕鬆完成此操作:

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
$vbLabelText   $csharpLabel

使用 IronPrint 列印檔案

使用 IronPrint 列印文件非常簡單。 您可以使用Printer類別,指定檔案路徑到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
$vbLabelText   $csharpLabel

此範例演示列印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
$vbLabelText   $csharpLabel

以下是輸出的樣子:

如何在 C# 中將檔案打印到打印機:圖 8 - 自訂列印輸出

如果實體印表機未安裝,則使用預設印表機來列印 PDF 文件。 要獲取所有可用的列印機,您也可以使用GetPrinterNames 方法。

// 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
$vbLabelText   $csharpLabel

如需更詳細的資訊,請造訪文件頁面

結論

在 C# 中,使用 System.Drawing.Printing 命名空間提供的功能列印檔案是一個可管理的任務。 透過處理PrintPage事件和使用PrintDocument類別,您可以根據具體需求定制列印過程。 這本綜合指南涵蓋了從 C# 應用程式列印檔案的基本步驟,為您提供了一個將此功能整合到專案中的堅實基礎。 隨著我們進一步探索,我們查看了IronPrint以獲取額外的自定義選項,例如處理不同的文件類型、整合圖像以及根據應用程式的需求增強格式設定。

將 IronPrint 整合到您的 C# 應用程式中可以簡化將檔案列印至印表機的過程。 IronPrint 支援多種檔案格式及可自訂的列印設定,為尋求增強列印能力的開發者提供強大的解決方案。 無論您是在進行桌面、網路或行動專案,IronPrint 簡化了打印過程,使其成為您的 .NET 工具包中有價值的新增項目。

IronPrint 提供免費試用頁面以獲取更多資訊。 從這裡下載庫並嘗試一下。

查克尼思·賓
軟體工程師
Chaknith 致力於 IronXL 和 IronBarcode。他在 C# 和 .NET 方面擁有豐富的專業知識,協助改進軟體並支持客戶。他從用戶互動中獲得的洞察力有助於提高產品、文檔和整體體驗。
< 上一頁
如何在C#中列印QR Code
下一個 >
使用 IronPrint 在 C# 中列印 QR Codes

準備開始了嗎? 版本: 2025.4 剛剛發布

查看許可證 >