使用 IRONPRINT

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

發佈 2024年4月29日
分享:

從 C# 應用程式直接列印 PDF 文件,尤其是在開發需要與實體 PDF 文件無縫整合的應用程式時,這是一個非常有價值的功能。無論您是在開發 PDF 文件管理系統、銷售點應用程式,還是任何涉及列印的軟體,C# 都提供了一組強大的庫來實現這種 PDF 列印方法的功能。

為此,微軟 C# 提供了一个 print 方法 將 PDF 文件列印到預設印表機。在本文中,我們將探討使用 C# 列印 PDF 文件到印表機的步驟。

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

  1. 創建一個 C# Windows Forms 應用程式

  2. 使用 using 關鍵字匯入 System.Drawing.Printing

  3. 設計具有按鈕和其他必要控制項的表單

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

  5. 啟動 Print 任務

  6. 執行應用程式並點擊打印按鈕進行列印

先決條件

在開始之前,請確保您具備以下先決條件:

  1. 一個 C# 開發環境 (例如,Visual Studio).

  2. 與印表機互動的足夠權限。

  3. 對 C# 程式設計的基本了解。

第一步:設定您的專案

創建一個新的 C# 專案或在您偏好的開發環境中打開一個現有的專案。確保專案配置正確,並且您擁有進行打印機互動所需的必要權限。以下過程將允許您完成此過程:

安裝 Visual Studio

如果您尚未安裝 Visual Studio,請從官方網站下載並安裝它: Visual Studio.

建立新專案

  1. 打開 Visual Studio。

  2. 點擊「建立新專案」。

如何在 C# 中將文件打印到打印機:圖 1 - 新項目

選擇專案模板

  1. 在「建立新專案」對話框中,選擇「Windows Forms App」 (.NET框架)或「Windows Forms 應用程式」 (.NET Core)根據您的偏好。

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

  1. 為您的項目提供名稱和位置。

如何在 C# 中將檔案列印至印表機:圖 3 - 專案設定

  1. 點擊下一步,從附加信息屏幕中選擇 .NET 框架並點擊“創建”。

設計表單

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

  2. 使用工具箱根據需求將按鈕、文本框、標籤等控制項添加到表單中。

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

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

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

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

步驟 2:匯入所需的庫

在你的C#代碼文件中,匯入必要的命名空間以訪問與打印相關的類和方法。

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

這些命名空間提供了必要的類別,例如 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
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事件處理程序,然後打印文件。可選的打印對話框允許用戶在啟動打印作業之前配置打印設置。這會將文本文件打印到本地連接的打印機。如果沒有此打印機,則文件將打印到預設的打印機名稱。 (Microsoft 打印為 PDF) 在列印對話框中如下所示:

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

使用 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 程式包管理控制台輕鬆完成此操作:

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文件。要獲取所有可用的打印機,您還可以使用 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
VB   C#

欲了解更多詳細信息,請訪問 文檔 頁面。

結論

使用 System.Drawing.Printing 命名空間,對於在 C# 中列印文件的任務是可以管理的。通過處理 PrintPage 事件和利用 PrintDocument 類,您可以根據具體需求定制列印過程。本綜合指南涵蓋了從 C# 應用程序列印文件所涉及的基本步驟,為您集成此功能提供了堅實的基礎。在進一步探索中,我們還研究了 IronPrint,用於額外的自訂選項,如處理不同的文件類型、合併圖像和根據應用程序需求增強格式。

將 IronPrint 集成到您的 C# 應用程序中可以簡化將文件列印到打印機的過程。憑藉對各種文件格式和可自定義列印設置的支持,IronPrint 為尋求增強其列印功能的開發人員提供了一個強大的解決方案。無論您是從事桌面、網絡還是移動項目,IronPrint 都能簡化列印過程,使其成為您的 .NET 工具包中寶貴的補充。

IronPrint 提供了一個 免費試用 請參閱頁面了解更多資訊。從 這裡 試試看。

< 上一頁
如何在C#中列印QR Code
下一個 >
如何在 C# 中列印 QR 碼

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

免費 NuGet 下載 總下載次數: 9,531 查看許可證 >