如何在 C# 中靜默列印文件

This article was translated from English: Does it need improvement?
Translated
View the article in English

靜默列印直接從程式碼將文件發送到列印機 — 無對話框,無使用者交互,無中斷。 對於批量發票處理、自助服務終端應用程式和 Windows 服務背景工作這樣的自動化工作流來說,取消列印對話框是硬性要求。 本機 System.Drawing.Printing 命名空間提供了靜默列印的路徑,但它需要事件驅動的樣板,而這種方式在團隊和項目中缺乏擴展性。

IronPrint 將靜默列印簡化為一個方法調用。 我們只需安裝一個 NuGet 套件並調用 Printer.Print() — 程式庫在幕後處理列印機通信、文件渲染和列印緩衝區交互。

快速開始:靜默列印

  1. 通過 NuGet 安裝 IronPrint:Install-Package IronPrint
  2. 新增 using IronPrint; 到文件中
  3. 調用 Printer.Print("filepath") 將文件發送到預設列印機
  4. 傳遞一個 PrintSettings 物件來控制列印機名稱、DPI、份數和紙張配置
  5. 當列印操作不應該阻塞調用執行緒時請使用 Printer.PrintAsync()
  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronPrint

    PM > Install-Package IronPrint
  2. 複製並運行這段程式碼片段。

    using IronPrint;
    
    // Silent print — no dialog, no user interaction
    Printer.Print("invoice.pdf");
  3. 部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronPrint,透過免費試用

    arrow pointer

靜默列印在 .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
Printer.Print("quarterly-report.pdf");

// Print from a byte array
byte[] pdfData = File.ReadAllBytes("shipping-label.pdf");
Printer.Print(pdfData);
Imports IronPrint

' Print a PDF silently
Printer.Print("quarterly-report.pdf")

' Print from a byte array
Dim pdfData As Byte() = File.ReadAllBytes("shipping-label.pdf")
Printer.Print(pdfData)
$vbLabelText   $csharpLabel

Print() 方法支持 PDF、PNG、TIFF、JPEG、GIF、HTML 和 BMP 文件格式。 我們將文件路徑作為字串或將原始文件資料作為 byte[] 傳遞,IronPrint 自動確定渲染策略。

如何配置靜默輸出的列印設置?

PrintSettings 類使我們能夠完全掌控列印工單。 我們配置目標列印機、紙張尺寸、方向、邊距、DPI、色彩模式、份數和雙工行為——然後將設定物件傳遞給 Printer.Print()DPI Grayscale PaperMargins

:path=/static-assets/print/content-code-examples/how-to/silent-printing/silent-printing-print-with-settings.cs
using IronPrint;

// Configure print settings
var settings = new PrintSettings
{
    PrinterName = "HP LaserJet Pro",
    PaperSize = PaperSize.A4,
    PaperOrientation = PaperOrientation.Portrait,
    Dpi = 300,
    NumberOfCopies = 2,
    Grayscale = false,
    PaperMargins = new Margins(10, 10, 10, 10)
};

// Print with custom settings
Printer.Print("report.pdf", settings);
Imports IronPrint

' Configure print settings
Dim settings As New PrintSettings With {
    .PrinterName = "HP LaserJet Pro",
    .PaperSize = PaperSize.A4,
    .PaperOrientation = PaperOrientation.Portrait,
    .Dpi = 300,
    .NumberOfCopies = 2,
    .Grayscale = False,
    .PaperMargins = New Margins(10, 10, 10, 10)
}

' Print with custom settings
Printer.Print("report.pdf", settings)
$vbLabelText   $csharpLabel

每個屬性都映射到標準的列印緩衝設定。 Resolution 控制輸出解析度 — 300 是商業文件的常見選擇,而 150 適合草稿。 ColorMode 在不需要顏色時可以降低墨粉使用。 Margins 值以毫米為單位指出。

如何選擇特定列印機?

我們使用 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"))
};

// Print the document
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"))
}

' Print the document
Printer.Print("document.pdf", settings)
$vbLabelText   $csharpLabel

當未指定 PrinterName 時,IronPrint 會將工作路由至作業系統的預設列印機。 對於有多台列印機的環境——共享辦公室、倉庫或列印室——使用程式列舉和選擇正確的列印機可以防止工作錯誤路徑。

如何批量列印多個文件?

批量列印遵循簡單的迴圈模式。 我們迭代文件路徑集合並為每個文件調用 Printer.Print()。 由於每次調用都是靜默的,整批工作完成不需要單一對話提示。

:path=/static-assets/print/content-code-examples/how-to/silent-printing/silent-printing-batch-print.cs
using IronPrint;

// Collect all PDFs in the batch folder
string[] invoices = Directory.GetFiles(@"C:\Invoices\Pending", "*.pdf");

// Configure print settings for the batch
var settings = new PrintSettings
{
    PrinterName = "Accounting Printer",
    NumberOfCopies = 1,
    Grayscale = true
};

// Print each invoice and track successes
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}");
    }
}

// Report batch results
Console.WriteLine($"Batch complete: {successCount}/{invoices.Length} documents printed.");
Imports IronPrint
Imports System.IO

' Collect all PDFs in the batch folder
Dim invoices As String() = Directory.GetFiles("C:\Invoices\Pending", "*.pdf")

' Configure print settings for the batch
Dim settings As New PrintSettings With {
    .PrinterName = "Accounting Printer",
    .NumberOfCopies = 1,
    .Grayscale = True
}

' Print each invoice and track successes
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

' Report batch results
Console.WriteLine($"Batch complete: {successCount}/{invoices.Length} documents printed.")
$vbLabelText   $csharpLabel

將每次 Print() 調用包裹在 try/catch 中可確保單個損毀文件或列印機超時不會中止整批作業。 對於在後台服務中運行的大型批次,將每次結果記錄到資料庫或監控系統提供了一個操作團隊可以審查的審計跟蹤。

如何異步列印而不阻塞執行緒?

Printer.PrintAsync() 方法返回 Task,使其與 await 模式相容。 這對於 UI 應用程式來說至關重要,因為阻塞列印會凍結介面,也適用於處理併發操作的服務。

:path=/static-assets/print/content-code-examples/how-to/silent-printing/silent-printing-async-print.cs
using IronPrint;

// Print asynchronously without blocking the thread
await Printer.PrintAsync("report.pdf");

// Print a batch of reports asynchronously
string[] files = Directory.GetFiles(@"C:\Reports", "*.pdf");
foreach (string file in files)
{
    await Printer.PrintAsync(file);
}
Imports IronPrint

' Print asynchronously without blocking the thread
Await Printer.PrintAsync("report.pdf")

' Print a batch of reports asynchronously
Dim files As String() = Directory.GetFiles("C:\Reports", "*.pdf")
For Each file As String In files
    Await Printer.PrintAsync(file)
Next
$vbLabelText   $csharpLabel

PrintAsync() 接受與 Print() 相同的參數 — 文件路徑或位元組陣列,以及可選的 PrintSettings 物件。 異步重載防止在高吞吐量場景中隊列中都有多個文件同時等候列印時的執行緒池匱乏。 這遵循了整個現代 .NET 開發中推薦使用的基於任務的異步模式

平台考量因素有哪些?

IronPrint 支持跨桌面和移動平台的靜默列印,儘管這些系統的行為因作業系統而異。

平台 靜默列印 備註
Windows (7+) 完全支持 無對話全 PrintSettings 控制
macOS (10+) 支持 使用本機 macOS 列印子系統
iOS (11+) 顯示對話框 Print() 仍顯示系統列印對話框
Android (API 21+) 顯示對話框 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 消除了數週的開發時間和持續的維護成本。 列印速度提高 30% 的優化於 2025 年 5 月的版本中發佈,這類優化若在內部構建會消耗工程時間。

下一步

使用 IronPrint 進行靜默列印可以歸結為三個核心方法:Printer.Print() 用於同步靜默輸出,Printer.PrintAsync() 用於不阻塞的執行,以及 PrintSettings 用於完全掌控列印工單。 合在一起,這些方法覆蓋單文件、批次和並行列印場景在桌面平台上的情況。

瀏覽 IronPrint 教程 以獲得更深入的演練,或查看 Printer 類 API 參考 以獲取完整的改變方法。 列印設置使用範例包含額外的配置選項如紙盤選擇與扁化。

開始免費的30天試用以在真實環境中測試靜默列印 — 無需信用卡。 準備好部署時,瀏覽起選擇低至 $999 的授權選項

與 Iron Software 工程師聊天以獲取特定部署場景的幫助。

常見問題

什麼是C#中的靜默列印?

C#中的靜默列印是指能夠直接將文件列印到印表機而不顯示任何列印對話框或要求使用者操作提示。IronPrint通過允許開發人員程式化地配置列印設定來實現此功能。

我如何使用IronPrint進行靜默列印?

使用IronPrint,您可以通過在C#程式碼中直接設置印表機配置如DPI、副本數以及啟用非同步批量列印來進行靜默列印,從而繞過任何列印對話框。

IronPrint能夠處理PDF文件進行靜默列印嗎?

是的,IronPrint專門設計來處理PDF文件的靜默列印,使您能夠無縫地列印PDF文件而不被任何對話框中斷。

可以使用IronPrint配置印表機設定嗎?

絕對可以。IronPrint允許您配置各種印表機設定,例如選擇印表機,設置DPI和指定副本數,這些都可以通過程式碼實現而不需使用者干預。

IronPrint是否支持非同步批次列印?

是的,IronPrint支持非同步批次列印,這使您能夠將多個列印作業排列在佇列中並在背景中執行,從而提高C#應用中的效率和效能。

IronPrint與哪種程式語言相容?

IronPrint與C#相容,使其成為需要穩健的靜默列印功能的.NET框架內開發人員的理想選擇。

IronPrint可以在不打開任何列印對話框的情況下列印嗎?

是的,IronPrint專門設計用於靜默列印,這意味著它能夠直接將文件發送到印表機而不打開任何列印對話框或需要使用者輸入。

IronPrint可以列印哪些型別的文件?

IronPrint主要支援PDF文件列印,提供了從您的C#應用程式中無縫且無對話框干擾的列印體驗。

使用IronPrint進行靜默列印適合批次處理嗎?

是的,使用IronPrint進行靜默列印非常適合批次處理,因為它可以讓您非同步管理和執行多個列印作業,從而提高生產力並簡化工作流程。

IronPrint如何改善C#應用程式中的列印過程?

IronPrint通過提供無對話框的列印解決方案,讓開發人員程式化地控制列印配置,並支援高效批量處理的非同步操作,從而改善C#應用中的列印過程。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備好開始了嗎?
Nuget 下載 44,051 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

仍在滾動?

想要快速證明嗎? PM > Install-Package IronPrint
運行範例 看看您的文件如何到達印表機。