如何在 C# 中靜默列印文件
靜默列印直接從程式碼將文件發送到印表機 - 無對話框、無使用者互動、無中斷。 對於批次發票處理、自助服務機應用程式及 Windows 服務背景工作等自動化工作流程而言,移除列印對話方塊是一項硬性要求。 本機System.Drawing.Printing命名空間提供靜默列印的路徑,但需要事件驅動的樣板,對團隊和專案的擴展性不佳。
IronPrint將靜默列印簡化為單一方法呼叫。 我們安裝一個NuGet套件並呼叫Printer.Print() - 此程式庫在幕後處理印表機通訊、文件渲染和列印緩衝交互。
- 透過NuGet安裝IronPrint:
Install-Package IronPrint - 將
using IronPrint;新增到檔案中 - 呼叫
Printer.Print("filepath")將文件發送到預設印表機 - 傳遞
PrintSettings物件以控制印表機名稱、DPI、份數和紙張配置 - 當列印操作不應該阻塞呼叫執行緒時,請使用
Printer.PrintAsync()
-
1使用 IronPrint 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
using IronPrint; // Silent print — no dialog, no user interaction Printer.Print("invoice.pdf");Imports IronPrint ' Silent print — no dialog, no user interaction Printer.Print("invoice.pdf")Imports IronPrint ' Silent print — no dialog, no user interaction Printer.Print("invoice.pdf") -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronPrint,並使用 免費試用
最小工作流程(5 個步驟)
- 安裝IronPrint C#列印程式庫
- 呼叫
Printer.Print("filepath")以進行靜默輸出 - 傳入
PrintSettings物件以進行自訂設定 - 使用
Printer.PrintAsync()進行非阻塞執行 - 執行專案以靜默方式列印,不顯示任何對話方塊
.NET 中的靜默列印如何運作?
.NET System.Drawing.Printing 命名空間包含一個 StandardPrintController 類別,在列印操作期間抑制狀態對話框。 預設情況下,.NET 使用 PrintControllerWithStatusDialog,會顯示 "Printing page X of Y" 快顯窗口。切換到 StandardPrintController 可以消除該對話框,但設定成本仍然很高。
要使用本機方法無聲列印,我們創建一個 PrintDocument,然後附加一個 PrintPage 事件處理器,將內容繪製到列印圖形表面,分配 StandardPrintController,配置 PrinterSettings,然後呼叫 Print()。 這需要大約15-25行設置程式碼來處理單一文件,而每種新文件類型或格式都需要在PrintPage事件中自行渲染邏輯。 尤其是PDF渲染,並未內建於System.Drawing.Printing中 - 我們需要一個單獨的PDF解析程式庫來提取頁面並將其繪製到Graphics表面上。
IronPrint將整個管道包裝到靜態Printer類別中。 Print()方法接受文件路徑或位元組數組,偵測文件格式,透過合適的引擎進行渲染,並將其分派到預設印表機 - 所有過程都不顯示對話框。
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);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)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)Print()方法支援PDF、PNG、TIFF、JPEG、GIF、HTML和BMP文件格式。 我們將文件路徑作為字串傳遞,或將原始文件數據作為byte[]傳遞,IronPrint會自動確定渲染策略。
如何設定靜默輸出列印設定?
PrintSettings類別使我們可以完全控制列印任務。 我們配置目標印表機、紙張尺寸、方向、邊距、DPI、顏色模式和份數,然後將設定物件傳遞給Printer.Print()。
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);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)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)每個屬性皆對應至標準的列印佇列設定。 Dpi控制輸出解析度 - 300是商務文件的常用選擇,而150則適用於草稿。 將 Grayscale 設定為 true 可以減少在顏色不必要時的碳粉使用量。 Margins值以毫米為單位指定。
如何選擇特定印表機?
我們使用 Printer.GetPrinterNames() 枚舉系統上所有安裝的印表機,然後將目標印表機名稱分配給 PrintSettings.PrinterName。
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);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)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)當PrinterName未指派時,IronPrint將任務路由到作業系統的預設印表機。 在有多臺印表機的環境中 - 共用辦公室、倉庫或列印室 - 透過程式碼列舉並選擇正確的印表機以防止誤導任務。
如何批次列印多個文件?
批次列印採用直觀的迴圈模式。 我們遍歷文件路徑集合,為每個文件呼叫Printer.Print()。 由於每個呼叫皆為靜默執行,整個批次會在沒有任何對話框提示的情況下完成。
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.");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.")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.")用try/catch包裹每個Print()呼叫以確保單一損壞文件或印表機超時不會使整個批次停止。 對於在背景服務中執行的大批量處理,將每個結果記錄至資料庫或監控系統,可提供供運維團隊檢視的稽核追蹤紀錄。
如何在不阻塞執行緒的情況下進行非同步列印?
Printer.PrintAsync() 方法返回一個 Task,使其與 async/await 模式兼容。 這對於使用者介面應用程式至關重要,因為阻塞性的列印呼叫會導致介面凍結;對於處理並發操作的服務而言,這點同樣不可或缺。
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);
}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)
NextImports 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)
NextPrintAsync() 接受與 Print() 相同的參數 - 文件路徑或位元組數組,和一個可選的 PrintSettings 物件。 在數十份文件同時排隊待印的高吞吐量情境下,非同步重載可防止執行緒池資源耗盡。 這與現代.NET開發中建議的基於任務的非同步模式一致。
平台考量有哪些?
IronPrint 支援在桌面及行動平台間進行無互動列印,但實際行為會因作業系統而異。
| 平台 | 無聲印刷 | 筆記 |
|---|---|---|
| Windows (7+) | 全面支援 | 無對話框,完全PrintSettings控制 |
| macOS (10+) | 支援 | 使用原生 macOS 列印子系統 |
| iOS (11+) | 顯示的對話框 | Print()仍顯示系統列印對話框 |
| Android (API 21+) | 顯示的對話框 | Print()仍顯示系統列印對話框 |
在行動平台上,作業系統限制阻止真正的靜默列印 - Printer.Print()將不論如何顯示本機列印對話框。 桌面平台(Windows 和 macOS)支援完全無人值守的靜默列印,且無任何限制。
這與原生 .NET 列印功能有何不同?
對於評估是採用程式庫還是基於本機System.Drawing.Printing命名空間建置的工程團隊,權衡因素如下:
| System.Drawing.Printing(本機) | IronPrint | |
|---|---|---|
| 每個文件的設置 | 約 15-25 行:PrintDocument,一個 PrintPage 處理器,StandardPrintController,PrinterSettings | 單一 Printer.Print() 呼叫 |
| PDF 繪製 | 未內建 - 需要單獨的PDF程式庫來將頁面提取到Graphics表面 | 內建 - 可直接處理PDF、PNG、TIFF、JPEG、GIF、HTML和BMP |
| 對話框抑制 | 手動:分配 StandardPrintController 代替預設 PrintControllerWithStatusDialog | 預設無聲即透過 Printer.Print() |
| 格式支持 | 每種格式需要手動建立一個渲染管道 | 透過單一API支持多種格式 |
原生方法適用於團隊已具備文件渲染基礎架構的簡單情境。 對於需要列印 PDF、圖片或 HTML,卻缺乏現成渲染程式碼的團隊而言,IronPrint 能省去數週的開發時間及後續維護工作。 2025年5月發佈的30%列印速度提升是那種如果自行開發會耗費工程週期的優化。
後續步驟
利用 IronPrint 進行無聲列印主要歸結於三個核心方法:Printer.Print() 用於同步無聲輸出,Printer.PrintAsync() 用於非阻塞執行,以及 PrintSettings 用於完全控制列印工作。 這些工具共同涵蓋了桌面平台上的單一文件、批次及並行列印情境。
探索IronPrint教學以獲取更深入的演示,或查看Printer類別API參考以獲取完整的方法界面。 列印設定使用說明涵蓋了其他配置選項,例如紙匣選擇和壓平。
開始免費30天試用,在真實環境中測試靜默列印 - 無需信用卡。 準備部署時,檢視授權選項,起價 $999。
與Iron Software工程師對話以獲取特定部署情境的幫助。
常見問題
C#中的無提示列印是什麼?
在C#中,靜默列印指的是直接從代碼將文件傳送到印表機,而無需顯示任何對話框或要求用戶交互。這對於自動化工作流程,例如批次發票處理和自助服務機應用程序尤其有用。
如何使用IronPrint進行靜默列印?
要使用IronPrint進行靜默列印,您需要通過NuGet安裝IronPrint程式庫,調用Printer.Print()方法並附上文件路徑,並且可以選擇性地傳遞一個PrintSettings對象進行其他配置。
IronPrint能夠處理不同格式的文件進行靜默列印嗎?
可以,IronPrint可以處理多種文件格式進行靜默列印,包括PDF、PNG、TIFF、JPEG、GIF、HTML和BMP。它會自動檢測文件格式並處理而不顯示對話框。
如何在IronPrint中控制列印作業的設置?
您可以使用PrintSettings類來控制IronPrint中的列印作業設置。這允許您配置目標印表機、紙張大小、紙張方向、DPI、份數、顏色模式和邊距。
有沒有辦法用IronPrint非同步列印文件?
有的,IronPrint提供了Printer.PrintAsync()方法,這個方法返回一個Task,支持非同步列印操作。這對於不希望列印時阻塞主線程的應用程式非常重要。
IronPrint支持多文件的批次列印嗎?
IronPrint支持通過迭代文件路徑集合並對每個路徑調用Printer.Print()方法來進行批次列印。這確保了整個批次在沒有用戶交互或提示對話的情況下完成。
我可以指定特定的印表機來使用IronPrint進行靜默列印嗎?
可以,您可以通過使用Printer.GetPrinterNames()來列出可用的印表機,並將所需的印表機指定給PrintSettings.PrinterName。
IronPrint在進行靜默列印時需要考慮哪些平台因素?
IronPrint在Windows上完全支持靜默列印,macOS有原生支持,而在iOS和Android等行動平台上,由於操作系統限制會顯示系統列印對話框。
IronPrint在易用性方面與原生.NET列印相比如何?
IronPrint簡化了列印過程,將其減少到一個Printer.Print()調用,而原生.NET列印需要大約15-25行的樣板代碼進行設置、事件處理和文檔渲染。
在C#專案中使用IronPrint需要哪些安裝步驟?
要在C#專案中使用IronPrint,請使用Install-Package IronPrint通過NuGet安裝包,在代碼中包含using IronPrint;,並使用您的文件路徑調用Printer.Print()。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。