如何在 C# 中靜默列印 PDF 及其他文件
靜默列印可直接從程式碼將文件傳送至印表機——無對話方塊、無使用者互動、無中斷。 對於批次發票處理、自助服務機應用程式及 Windows 服務背景工作等自動化工作流程而言,移除列印對話方塊是一項硬性要求。 內建的 System.Drawing.Printing 命名空間雖提供了一種無需干預的列印途徑,但其需仰賴事件驅動的常規程式碼,這類程式碼在跨團隊與跨專案的擴展性上表現不佳。
IronPrint 將靜默列印簡化為單一方法呼叫。 我們安裝一個 NuGet 套件並呼叫 Printer.Print() — 該函式庫會在後台處理印表機通訊、文件渲染以及與列印佇列的互動。
快速入門:靜默列印
- 透過 NuGet 安裝 IronPrint:
Install-Package IronPrint - 將
using IronPrint;加入檔案中 - 呼叫
Printer.Print("filepath")將文件傳送至預設印表機 - 傳遞
PrintSettings物件以控制印表機名稱、DPI、份數及紙張設定 - 當列印操作不應阻塞呼叫執行緒時,請使用
Printer.PrintAsync()
最小工作流程(5 個步驟)
- 安裝 IronPrint C# 程式庫
- 呼叫 `Printer.Print("filepath")` 以進行靜默輸出
- 傳入 `PrintSettings` 物件以進行自訂設定
- 使用 `Printer.PrintAsync()` 進行非阻塞執行
- 執行專案以靜默方式列印,不顯示任何對話方塊
.NET 中的靜默列印如何運作?
.NET 的 System.Drawing.Printing 命名空間包含一個 StandardPrintController 類別,該類別可在列印操作期間抑制狀態對話方塊的顯示。 預設情況下,.NET 使用 PrintControllerWithStatusDialog,這會顯示"正在列印第 X 頁,共 Y 頁"的彈出視窗。切換至 StandardPrintController 可消除該對話框——但設定成本依然相當高。
若要使用原生方法進行靜默列印,我們會建立一個 PrintDocument,附加一個 PrintPage 事件處理常式以將內容繪製至列印圖形表面,指派 StandardPrintController,設定 PrinterSettings,並呼叫 Print()。 這需要為單一文件編寫約 15 至 25 行的設定程式碼,且每種新的文件類型或格式都需要在 PrintPage 事件中擁有專屬的渲染邏輯。 特別是 PDF 渲染功能並未內建於 System.Drawing.Printing 中——我們需要一個獨立的 PDF 解析函式庫,才能擷取頁面並將其繪製到 Graphics 介面上。
IronPrint 將整個處理流程封裝於靜態的 Printer 類別中。 Print() 方法接受檔案路徑或位元組陣列,偵測檔案格式,透過適當的引擎進行渲染,並將其傳送至預設印表機——整個過程均不顯示對話方塊。
:path=/static-assets/print/content-code-examples/how-to/silent-printing/silent-printing-print-pdf-and-byte-array.cs
using IronPrint;
// Print a PDF silently to the default printer
Printer.Print("quarterly-report.pdf");
// Print from a byte array (e.g., retrieved from a database or API)
byte[] pdfData = File.ReadAllBytes("shipping-label.pdf");
Printer.Print(pdfData);
Imports IronPrint
' Print a PDF silently to the default printer
Printer.Print("quarterly-report.pdf")
' Print from a byte array (e.g., retrieved from a database or API)
Dim pdfData As Byte() = File.ReadAllBytes("shipping-label.pdf")
Printer.Print(pdfData)
Print() 方法支援 PDF、PNG、TIFF、JPEG、GIF、HTML 及 BMP 檔案格式。 我們將檔案路徑作為字串傳入,或將原始檔案資料作為 byte[] 傳入,IronPrint 會自動決定渲染策略。
如何設定靜默輸出列印設定?
PrintSettings 類別讓我們能夠完全掌控列印工作。 我們設定目標印表機、紙張尺寸、方向、邊距、DPI、色彩模式、份數及雙面列印行為,然後將設定物件傳遞給 Printer.Print()。
:path=/static-assets/print/content-code-examples/how-to/silent-printing/silent-printing-print-with-settings.cs
using IronPrint;
// Configure detailed print settings
var settings = new PrintSettings
{
PrinterName = "HP LaserJet Pro",
PaperSize = PaperSize.A4,
Orientation = PaperOrientation.Portrait,
DPI = 300,
NumberOfCopies = 2,
Grayscale = false,
PaperMargins = new Margins(10, 10, 10, 10)
};
// Print with custom settings — still silent, no dialog
Printer.Print("monthly-summary.pdf", settings);
Imports IronPrint
' Configure detailed print settings
Dim settings As New PrintSettings With {
.PrinterName = "HP LaserJet Pro",
.PaperSize = PaperSize.A4,
.Orientation = PaperOrientation.Portrait,
.DPI = 300,
.NumberOfCopies = 2,
.Grayscale = False,
.PaperMargins = New Margins(10, 10, 10, 10)
}
' Print with custom settings — still silent, no dialog
Printer.Print("monthly-summary.pdf", settings)
每個屬性皆對應至標準的列印佇列設定。 DPI 控制輸出解析度 — 300 是商務文件的常見選擇,而 150 則適用於草稿。 Grayscale 在無需彩色列印時可減少碳粉用量。 PaperMargins 的數值以毫米為單位。
如何選擇特定的印表機?
我們使用 Printer.GetPrinterNames() 列出系統上安裝的所有印表機,然後將目標印表機名稱指派給 PrintSettings.PrinterName。
:path=/static-assets/print/content-code-examples/how-to/silent-printing/silent-printing-select-specific-printer.cs
using IronPrint;
// List all available printers
List<string> printers = Printer.GetPrinterNames();
foreach (string name in printers)
{
Console.WriteLine(name);
}
// Target a specific network printer
var settings = new PrintSettings
{
PrinterName = printers.First(p => p.Contains("LaserJet"))
};
Printer.Print("document.pdf", settings);
Imports IronPrint
' List all available printers
Dim printers As List(Of String) = Printer.GetPrinterNames()
For Each name As String In printers
Console.WriteLine(name)
Next
' Target a specific network printer
Dim settings As New PrintSettings With {
.PrinterName = printers.First(Function(p) p.Contains("LaserJet"))
}
Printer.Print("document.pdf", settings)
若未指定 PrinterName,IronPrint 會將列印任務轉發至作業系統的預設印表機。 在擁有多台印表機的環境中(例如共用辦公室、倉庫或列印室),透過程式化方式枚舉並選取正確的印表機,可避免列印工作被誤送。
如何批次列印多個文件?
批次列印採用直觀的迴圈模式。 我們遍歷一組檔案路徑,並針對每個文件呼叫 Printer.Print()。 由於每個呼叫皆為靜默執行,整個批次會在沒有任何對話框提示的情況下完成。
:path=/static-assets/print/content-code-examples/how-to/silent-printing/silent-printing-batch-print.cs
using IronPrint;
string[] invoices = Directory.GetFiles(@"C:\Invoices\Pending", "*.pdf");
var settings = new PrintSettings
{
PrinterName = "Accounting Printer",
NumberOfCopies = 1,
Grayscale = true
};
int successCount = 0;
foreach (string invoice in invoices)
{
try
{
Printer.Print(invoice, settings);
successCount++;
Console.WriteLine($"Printed: {Path.GetFileName(invoice)}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed: {Path.GetFileName(invoice)} — {ex.Message}");
}
}
Console.WriteLine($"Batch complete: {successCount}/{invoices.Length} documents printed.");
Imports IronPrint
Dim invoices As String() = Directory.GetFiles("C:\Invoices\Pending", "*.pdf")
Dim settings As New PrintSettings With {
.PrinterName = "Accounting Printer",
.NumberOfCopies = 1,
.Grayscale = True
}
Dim successCount As Integer = 0
For Each invoice As String In invoices
Try
Printer.Print(invoice, settings)
successCount += 1
Console.WriteLine($"Printed: {Path.GetFileName(invoice)}")
Catch ex As Exception
Console.WriteLine($"Failed: {Path.GetFileName(invoice)} — {ex.Message}")
End Try
Next
Console.WriteLine($"Batch complete: {successCount}/{invoices.Length} documents printed.")
將每個 Print() 呼叫包裹在 try/catch 結構中,可確保單一損壞的檔案或印表機超時不會導致整個批次作業中斷。 對於在背景服務中執行的大批量處理,將每個結果記錄至資料庫或監控系統,可提供供運維團隊檢視的稽核追蹤紀錄。
如何在不阻塞執行緒的情況下進行非同步列印?
Printer.PrintAsync() 方法會傳回 Task,使其相容於 await 模式。 這對於使用者介面應用程式至關重要,因為阻塞性的列印呼叫會導致介面凍結;對於處理並發操作的服務而言,這點同樣不可或缺。
:path=/static-assets/print/content-code-examples/how-to/silent-printing/silent-printing-async-print.cs
using IronPrint;
// Non-blocking silent print
await Printer.PrintAsync("report.pdf");
// Async batch printing
string[] files = Directory.GetFiles(@"C:\Reports", "*.pdf");
foreach (string file in files)
{
await Printer.PrintAsync(file);
}
Imports IronPrint
' Non-blocking silent print
Await Printer.PrintAsync("report.pdf")
' Async batch printing
Dim files As String() = Directory.GetFiles("C:\Reports", "*.pdf")
For Each file As String In files
Await Printer.PrintAsync(file)
Next
PrintAsync() 接受與 Print() 相同的參數 — 檔案路徑或位元組陣列,以及一個可選的 PrintSettings 物件。 在數十份文件同時排隊待印的高吞吐量情境下,非同步重載可防止執行緒池資源耗盡。 此設計遵循現代 .NET 開發中普遍推薦的"基於任務的非同步模式"。
平台考量有哪些?
IronPrint 支援在桌面及行動平台間進行無互動列印,但實際行為會因作業系統而異。
| 平台 | 無聲印刷 | 筆記 |
|---|---|---|
| Windows (7+) | 全面支援 | 無對話框,完全 PrintSettings 控制 |
| macOS (10+) | 支援 | 使用原生 macOS 列印子系統 |
| iOS (11+) | 顯示的對話框 | Print() 仍會顯示系統列印對話方塊 |
| Android (API 21+) | 顯示的對話框 | Print() 仍會顯示系統列印對話方塊 |
在行動平台上,由於作業系統的限制,無法實現真正的靜音列印——Printer.Print() 仍會顯示原生列印對話方塊。 在 Android 平台上,執行任何列印操作前,必須先呼叫 Printer.Initialize(Android.Content.Context) 函式。 桌面平台(Windows 和 macOS)支援完全無人值守的靜默列印,且無任何限制。
這與原生 .NET 列印功能有何不同?
對於正在評估是否採用某個函式庫,或直接基於原生 System.Drawing.Printing 命名空間進行開發的工程團隊而言,其權衡考量可歸納如下:
| PDF/UA-1 | PDF/UA-2 | |
|---|---|---|
| 已發布 | 2012 | 2024 |
| 基本規格 | PDF 1.7 (ISO 32000-1) | PDF 2.0 (ISO 32000-2) |
| 法規涵蓋範圍 | 第 508 條、ADA 第 II 篇、歐盟無障礙法案 | 與相同規範向前相容 |
| 驗證工具 | veraPDF、Adobe Acrobat Pro、PAC 2024 | veraPDF(支援範圍持續擴展中) |
| 表單欄位語義 | 標準 | 增強版(更豐富的無障礙元資料) |
| 最適合 | 當今大多數專案 | 需要 PDF 2.0 功能的新系統 |
原生方法適用於團隊已具備文件渲染基礎架構的簡單情境。 對於需要列印 PDF、圖片或 HTML,卻缺乏現成渲染程式碼的團隊而言,IronPrint 能省去數週的開發時間及後續維護工作。 2025 年 5 月版本中推出的 30% 列印速度提升,若由內部開發團隊自行建置,將耗費大量工程資源。
後續步驟
IronPrint 的靜默列印功能主要透過三種核心方法實現:Printer.Print() 用於同步靜默輸出,Printer.PrintAsync() 用於非阻塞執行,以及 PrintSettings 用於完全控制列印工作。 這些工具共同涵蓋了桌面平台上的單一文件、批次及並行列印情境。
請參閱 IronPrint 教學指南以獲取更深入的逐步說明,或查閱 Printer 類別的 API 參考以了解完整的方法介面。 這份列印設定指南涵蓋了其他配置選項,例如紙匣選擇與平放列印。
立即開始 30天試用,在實際環境中測試靜默列印功能 — 無需信用卡。 準備部署時,請查看起價 $749 的授權方案。
若需協助處理特定部署情境,請與 Iron Software 工程師聯繫。

