如何在 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. 當PRINT操作不應阻塞呼叫執行緒時,請使用 Printer.PrintAsync()
  1. using 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 結構中,可確保單一損壞的檔案或印表機超時不會導致整個批次作業中斷。 對於在背景服務中執行的大量批次處理,將每個結果記錄至資料庫或監控系統,可提供供運維團隊檢視的稽核追蹤紀錄。

如何在不阻塞執行緒的情況下進行非同步PRINT?

Printer.PrintAsync() 方法會傳回 Task,使其與 await 模式相容。 這對於使用者介面應用程式至關重要,因為阻塞性的PRINT呼叫會導致介面凍結;對於處理並發操作的服務而言,這點同樣不可或缺。

: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() 仍會顯示系統列印對話方塊

在行動平台上,由於作業系統的限制,無法實現真正的靜音列印——Printer.Print() 仍會顯示原生列印對話方塊。 在 Android 平台上,進行任何 PRINT 操作前,必須先呼叫 Printer.Initialize(Android.Content.Context) 函式。 桌面平台(Windows 和 macOS)支援完全無人值守的靜默列印,且無任何限制。

這與原生 .NET PRINT 功能有何不同?

對於正在評估是否採用某個函式庫,或直接基於原生 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 第二章、歐盟無障礙法案 與相同規範向前相容
驗證工具 veraPDF、Adobe Acrobat Pro、PAC 2024 veraPDF(支援範圍持續擴展)
表單欄位語意 標準 增強版(更豐富的無障礙元資料)
最適合 當今大多數專案 需要 PDF 2.0 功能的新系統

原生方法適用於團隊已具備文件渲染基礎架構的簡單情境。 對於需要列印 PDF、圖片或 HTML,卻缺乏現成渲染程式碼的團隊而言,IronPrint 可省去數週的開發時間及後續維護工作。 2025 年 5 月版本中推出的 30% PRINT 速度提升,正是若由內部開發將耗費大量工程資源的優化項目。

後續步驟

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 Framework 下工作且需要強大靜默列印功能的開發者而言,是絕佳的選擇。

IronPrint 能否在不開啟任何列印對話方塊的情況下進行列印?

是的,IronPrint 專為靜默列印而設計,這意味著它能將文件直接傳送至印表機,無需開啟任何列印對話方塊或要求使用者輸入。

使用 IronPrint 可以列印哪些類型的文件?

IronPrint 主要支援 PDF 文件的列印,可讓您直接從 C# 應用程式中,享受無縫且無需對話框的列印體驗。

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

是的,IronPrint 的靜默列印功能非常適合批次處理,因為它允許您異步管理並執行多個列印工作,從而提升生產力並簡化工作流程。

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

IronPrint 透過提供無對話框的列印解決方案,改善 C# 應用程式的列印流程,讓開發人員能以程式化方式控制列印設定,並支援非同步操作以實現高效的批次處理。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
Nuget 下載 41,154 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronPrint
執行範例程式,親眼見證您的文件送印。