如何在 ASP.NET 中以編程方式打印 PDF 文件
ASP.NET 列印 PDF 文件任務通常會遇到開發人員經常遇到的獨特挑戰。 無論您是產生用於發票、報告還是運輸標籤的 PDF 文檔,實現可靠的列印功能都需要應對伺服器-用戶端架構的複雜性。
在本文中,我們將向您展示如何使用IronPDF強大的 .NET PDF 庫來處理PDF 列印任務。
理解挑戰
傳統桌面應用程式可以直接存取預設印表機,但 ASP.NET Core 應用程式在列印 PDF 文件時會面臨幾個障礙:
// This fails in ASP.NET - wrong approach
Process.Start(@"C:\Files\document.pdf"); // Works locally, crashes on server
// This fails in ASP.NET - wrong approach
Process.Start(@"C:\Files\document.pdf"); // Works locally, crashes on server
' This fails in ASP.NET - wrong approach
Process.Start("C:\Files\document.pdf") ' Works locally, crashes on server
上面的程式碼展示了一個常見的錯誤。 伺服器環境缺少直接印表機存取權限,並且由於 IIS 權限限制,系統會拋出錯誤。 另一點要記住的是,Web應用程式必須有效地處理伺服器端和用戶端列印場景。
開始使用 IronPDF
IronPDF提供了一個完整的 .NET core 解決方案,用於產生 PDF 文件並進行列印,無需 Adobe Reader 等外部相依性。 讓我們使用 NuGet 安裝 IronPDF 套件:
Install-Package IronPdf
這個 .NET 函式庫可以跨作業系統無縫運行,消除了困擾其他函式庫的相容性問題。 該工具在 Microsoft Windows 和其他作業系統環境下都能運作良好。
使用預設印表機在伺服器端建立和列印 PDF 文檔
以下是如何在 ASP.NET 控制器中根據 HTML 標記產生和列印 PDF 文件的方法:
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using System.Drawing;
public class PdfController : Controller
{
public IActionResult Index()
{
// Initialize the renderer
var renderer = new ChromePdfRenderer();
// Configure print-optimized settings
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Generate PDF from HTML
var pdf = renderer.RenderHtmlAsPdf("<h1>Invoice</h1><p>Total: $799</p>");
// Print to default printer
pdf.Print();
return Ok("Document sent to printer");
}
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using System.Drawing;
public class PdfController : Controller
{
public IActionResult Index()
{
// Initialize the renderer
var renderer = new ChromePdfRenderer();
// Configure print-optimized settings
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Generate PDF from HTML
var pdf = renderer.RenderHtmlAsPdf("<h1>Invoice</h1><p>Total: $799</p>");
// Print to default printer
pdf.Print();
return Ok("Document sent to printer");
}
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
Imports System.Drawing
Public Class PdfController
Inherits Controller
Public Function Index() As IActionResult
' Initialize the renderer
Dim renderer As New ChromePdfRenderer()
' Configure print-optimized settings
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.MarginBottom = 10
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
' Generate PDF from HTML
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Invoice</h1><p>Total: $799</p>")
' Print to default printer
pdf.Print()
Return Ok("Document sent to printer")
End Function
End Class
ChromePdfRenderer 負責處理轉換,同時保留 CSS 樣式和字體大小格式。 此範例示範了在無需使用者互動的情況下使用預設印表機進行基本列印。
輸出
網路印表機配置
對於需要特定印表機路由的企業環境:
public IActionResult PrintToNetworkPrinter(string filePath)
{
// Load existing PDF file
var pdfDocument = PdfDocument.FromFile(filePath);
// Get print document for advanced settings
var printDocument = pdfDocument.GetPrintDocument();
// Specify network printer
printDocument.PrinterSettings.PrinterName = @"\\server\printer";
printDocument.PrinterSettings.Copies = 2;
// Configure page settings
printDocument.DefaultPageSettings.Landscape = false;
var renderer = printDocument.PrinterSettings.PrinterResolution;
// Execute print
printDocument.Print();
return Json(new { success = true });
}
public IActionResult PrintToNetworkPrinter(string filePath)
{
// Load existing PDF file
var pdfDocument = PdfDocument.FromFile(filePath);
// Get print document for advanced settings
var printDocument = pdfDocument.GetPrintDocument();
// Specify network printer
printDocument.PrinterSettings.PrinterName = @"\\server\printer";
printDocument.PrinterSettings.Copies = 2;
// Configure page settings
printDocument.DefaultPageSettings.Landscape = false;
var renderer = printDocument.PrinterSettings.PrinterResolution;
// Execute print
printDocument.Print();
return Json(new { success = true });
}
Public Function PrintToNetworkPrinter(filePath As String) As IActionResult
' Load existing PDF file
Dim pdfDocument = PdfDocument.FromFile(filePath)
' Get print document for advanced settings
Dim printDocument = pdfDocument.GetPrintDocument()
' Specify network printer
printDocument.PrinterSettings.PrinterName = "\\server\printer"
printDocument.PrinterSettings.Copies = 2
' Configure page settings
printDocument.DefaultPageSettings.Landscape = False
Dim renderer = printDocument.PrinterSettings.PrinterResolution
' Execute print
printDocument.Print()
Return Json(New With {.success = True})
End Function
這種方法可以完全控製印表機設置,包括紙張格式和分辨率,這對於正確的繪圖和佈局至關重要。
輸出
列印確認
客戶端列印策略
由於瀏覽器限制了直接列印,因此可以透過提供 PDF 檔案供下載來實現客戶端列印:
public IActionResult GetRawPrintablePdf()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(GetInvoiceHtml());
// This header tells the browser to display the file inline.
// We use IHeaderDictionary indexer to prevent ArgumentException.
**HttpContext context**.Response.Headers["Content-Disposition"] = "inline; filename=invoice.pdf";
return File(pdf.BinaryData, "application/pdf");
}
public IActionResult PrintUsingClientWrapper()
{
var printUrl = Url.Action(nameof(GetRawPrintablePdf));
// Use a simple HTML/JavaScript wrapper to force the print dialog
var html = new StringBuilder();
html.AppendLine("<!DOCTYPE html>");
html.AppendLine("<html lang=\"en\">");
html.AppendLine("<head>");
html.AppendLine(" <title>Print Document</title>");
html.AppendLine("</head>");
html.AppendLine("<body>");
// Load the PDF from the 'GetRawPrintablePdf' action into an invisible iframe.
html.AppendLine($" <iframe src='{printUrl}' style='position:absolute; top:0; left:0; width:100%; height:100%; border:none;'></iframe>");
html.AppendLine(" <script>");
// Wait for the iframe (and thus the PDF) to load, then trigger the print dialog.
html.AppendLine(" window.onload = function() {");
html.AppendLine(" // Wait briefly to ensure the iframe content is rendered before printing.");
html.AppendLine(" setTimeout(function() {");
html.AppendLine(" window.print();");
html.AppendLine(" }, 100);");
html.AppendLine(" };");
html.AppendLine(" </script>");
html.AppendLine("</body>");
html.AppendLine("</html>");
return Content(html.ToString(), "text/html");
}
private string GetInvoiceHtml()
{
// Build HTML with proper structure
return @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.header { font-weight: bold; color: #1e40af; border-bottom: 2px solid #3b82f6; padding-bottom: 5px; }
.content { padding-top: 10px; }
</style>
</head>
<body>
<div class='header'>Invoice Summary (Client View)</div>
<div class='content'>
<p>Document content: This file is optimized for printing.</p>
<p>Total Amount: <b>$799.00</b></p>
</div>
</body>
</html>";
}
public IActionResult GetRawPrintablePdf()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(GetInvoiceHtml());
// This header tells the browser to display the file inline.
// We use IHeaderDictionary indexer to prevent ArgumentException.
**HttpContext context**.Response.Headers["Content-Disposition"] = "inline; filename=invoice.pdf";
return File(pdf.BinaryData, "application/pdf");
}
public IActionResult PrintUsingClientWrapper()
{
var printUrl = Url.Action(nameof(GetRawPrintablePdf));
// Use a simple HTML/JavaScript wrapper to force the print dialog
var html = new StringBuilder();
html.AppendLine("<!DOCTYPE html>");
html.AppendLine("<html lang=\"en\">");
html.AppendLine("<head>");
html.AppendLine(" <title>Print Document</title>");
html.AppendLine("</head>");
html.AppendLine("<body>");
// Load the PDF from the 'GetRawPrintablePdf' action into an invisible iframe.
html.AppendLine($" <iframe src='{printUrl}' style='position:absolute; top:0; left:0; width:100%; height:100%; border:none;'></iframe>");
html.AppendLine(" <script>");
// Wait for the iframe (and thus the PDF) to load, then trigger the print dialog.
html.AppendLine(" window.onload = function() {");
html.AppendLine(" // Wait briefly to ensure the iframe content is rendered before printing.");
html.AppendLine(" setTimeout(function() {");
html.AppendLine(" window.print();");
html.AppendLine(" }, 100);");
html.AppendLine(" };");
html.AppendLine(" </script>");
html.AppendLine("</body>");
html.AppendLine("</html>");
return Content(html.ToString(), "text/html");
}
private string GetInvoiceHtml()
{
// Build HTML with proper structure
return @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.header { font-weight: bold; color: #1e40af; border-bottom: 2px solid #3b82f6; padding-bottom: 5px; }
.content { padding-top: 10px; }
</style>
</head>
<body>
<div class='header'>Invoice Summary (Client View)</div>
<div class='content'>
<p>Document content: This file is optimized for printing.</p>
<p>Total Amount: <b>$799.00</b></p>
</div>
</body>
</html>";
}
Imports Microsoft.AspNetCore.Mvc
Imports System.Text
Public Class YourController
Inherits Controller
Public Function GetRawPrintablePdf() As IActionResult
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(GetInvoiceHtml())
' This header tells the browser to display the file inline.
' We use IHeaderDictionary indexer to prevent ArgumentException.
HttpContext.Response.Headers("Content-Disposition") = "inline; filename=invoice.pdf"
Return File(pdf.BinaryData, "application/pdf")
End Function
Public Function PrintUsingClientWrapper() As IActionResult
Dim printUrl = Url.Action(NameOf(GetRawPrintablePdf))
' Use a simple HTML/JavaScript wrapper to force the print dialog
Dim html = New StringBuilder()
html.AppendLine("<!DOCTYPE html>")
html.AppendLine("<html lang=""en"">")
html.AppendLine("<head>")
html.AppendLine(" <title>Print Document</title>")
html.AppendLine("</head>")
html.AppendLine("<body>")
' Load the PDF from the 'GetRawPrintablePdf' action into an invisible iframe.
html.AppendLine($" <iframe src='{printUrl}' style='position:absolute; top:0; left:0; width:100%; height:100%; border:none;'></iframe>")
html.AppendLine(" <script>")
' Wait for the iframe (and thus the PDF) to load, then trigger the print dialog.
html.AppendLine(" window.onload = function() {")
html.AppendLine(" // Wait briefly to ensure the iframe content is rendered before printing.")
html.AppendLine(" setTimeout(function() {")
html.AppendLine(" window.print();")
html.AppendLine(" }, 100);")
html.AppendLine(" };")
html.AppendLine(" </script>")
html.AppendLine("</body>")
html.AppendLine("</html>")
Return Content(html.ToString(), "text/html")
End Function
Private Function GetInvoiceHtml() As String
' Build HTML with proper structure
Return "
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.header { font-weight: bold; color: #1e40af; border-bottom: 2px solid #3b82f6; padding-bottom: 5px; }
.content { padding-top: 10px; }
</style>
</head>
<body>
<div class='header'>Invoice Summary (Client View)</div>
<div class='content'>
<p>Document content: This file is optimized for printing.</p>
<p>Total Amount: <b>$799.00</b></p>
</div>
</body>
</html>"
End Function
End Class
PDF 文件將在瀏覽器中打開,使用者可以使用標準的瀏覽器列印對話框,透過預設印表機觸發列印。 這種方法優於直接向伺服器端發出列印請求。
輸出
處理各種原始碼輸入
IronPDF 可以靈活處理各種原始碼輸入,這對於希望創建動態列印程式碼的開發人員來說非常重要:
public async Task<IActionResult> PrintFromMultipleSources()
{
var renderer = new ChromePdfRenderer();
// From URL
var pdfFromUrl = await renderer.RenderUrlAsPdfAsync("https://example.com");
// From HTML file path
var pdfFromFile = renderer.RenderHtmlFileAsPdf(@"Templates\report.html");
var pdfToStream = renderer.RenderHtmlAsPdf("<h2>PDF from Memory Stream</h2><p>This content was loaded into memory first.</p>");
// Now, write the valid PDF bytes to the stream
using (var stream = new MemoryStream(pdfToStream.BinaryData))
{
var pdfFromStream = new PdfDocument(stream);
// Example: Print the PDF loaded from the stream
// pdfFromStream.Print();
}
pdfFromUrl.Print();
// Logging the various files handled
var fileList = new List<string> { "URL", "File Path", "Memory Stream" };
return Ok("PDF documents processed and 'example.com' printed to default server printer.");
}
public async Task<IActionResult> PrintFromMultipleSources()
{
var renderer = new ChromePdfRenderer();
// From URL
var pdfFromUrl = await renderer.RenderUrlAsPdfAsync("https://example.com");
// From HTML file path
var pdfFromFile = renderer.RenderHtmlFileAsPdf(@"Templates\report.html");
var pdfToStream = renderer.RenderHtmlAsPdf("<h2>PDF from Memory Stream</h2><p>This content was loaded into memory first.</p>");
// Now, write the valid PDF bytes to the stream
using (var stream = new MemoryStream(pdfToStream.BinaryData))
{
var pdfFromStream = new PdfDocument(stream);
// Example: Print the PDF loaded from the stream
// pdfFromStream.Print();
}
pdfFromUrl.Print();
// Logging the various files handled
var fileList = new List<string> { "URL", "File Path", "Memory Stream" };
return Ok("PDF documents processed and 'example.com' printed to default server printer.");
}
Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Mvc
Imports System.IO
Public Class YourController
Inherits Controller
Public Async Function PrintFromMultipleSources() As Task(Of IActionResult)
Dim renderer = New ChromePdfRenderer()
' From URL
Dim pdfFromUrl = Await renderer.RenderUrlAsPdfAsync("https://example.com")
' From HTML file path
Dim pdfFromFile = renderer.RenderHtmlFileAsPdf("Templates\report.html")
Dim pdfToStream = renderer.RenderHtmlAsPdf("<h2>PDF from Memory Stream</h2><p>This content was loaded into memory first.</p>")
' Now, write the valid PDF bytes to the stream
Using stream = New MemoryStream(pdfToStream.BinaryData)
Dim pdfFromStream = New PdfDocument(stream)
' Example: Print the PDF loaded from the stream
' pdfFromStream.Print()
End Using
pdfFromUrl.Print()
' Logging the various files handled
Dim fileList = New List(Of String) From {"URL", "File Path", "Memory Stream"}
Return Ok("PDF documents processed and 'example.com' printed to default server printer.")
End Function
End Class
以上程式碼示範如何建立新的文件來源處理清單。 每種方法都能在保持列印品質的同時,保留文件結構和圖形。
錯誤處理和日誌記錄
在生產環境中實作健全的錯誤處理機制:
using System.Drawing.Printing; // For PrinterSettings
// ... other usings ...
public IActionResult SafePrint(string documentId)
{
try
{
var pdf = LoadPdfDocument(documentId);
// Verify printer availability
if (!PrinterSettings.InstalledPrinters.Cast<string>()
.Contains("Target Printer"))
{
// Log error and handle gracefully
return BadRequest("Printer not available");
}
pdf.Print();
// Log successful output
return Ok($"Document {documentId} printed successfully");
}
catch (Exception ex)
{
// Log error details
return StatusCode(500, "Printing failed");
}
}
using System.Drawing.Printing; // For PrinterSettings
// ... other usings ...
public IActionResult SafePrint(string documentId)
{
try
{
var pdf = LoadPdfDocument(documentId);
// Verify printer availability
if (!PrinterSettings.InstalledPrinters.Cast<string>()
.Contains("Target Printer"))
{
// Log error and handle gracefully
return BadRequest("Printer not available");
}
pdf.Print();
// Log successful output
return Ok($"Document {documentId} printed successfully");
}
catch (Exception ex)
{
// Log error details
return StatusCode(500, "Printing failed");
}
}
Imports System.Drawing.Printing ' For PrinterSettings
' ... other Imports ...
Public Function SafePrint(documentId As String) As IActionResult
Try
Dim pdf = LoadPdfDocument(documentId)
' Verify printer availability
If Not PrinterSettings.InstalledPrinters.Cast(Of String)().Contains("Target Printer") Then
' Log error and handle gracefully
Return BadRequest("Printer not available")
End If
pdf.Print()
' Log successful output
Return Ok($"Document {documentId} printed successfully")
Catch ex As Exception
' Log error details
Return StatusCode(500, "Printing failed")
End Try
End Function
即使系統資源不可用,也能確保可靠列印,這是列印服務的關鍵組成部分。
輸出情景
印表機不可用
如果程式碼中指定的印表機不可用,程式碼將顯示以下錯誤訊息:
如何在 ASP.NET 中以程式方式列印 PDF 檔案:圖 6 - 印表機不可用錯誤
PDF文件列印成功。
如果您的 PDF 文件列印成功,您應該會看到類似這樣的確認訊息:
進階配置
IronPDF的資料夾結構支援複雜的場景。 您使用的 IronPDF 庫版本可能會影響這些設定:
public IActionResult ConfigureAdvancedPrinting(object sender, EventArgs e)
{
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.RenderDelay = 500; // Wait for dynamic content
// Generate complex PDF documents
var pdf = renderer.RenderHtmlAsPdf(GetDynamicContent());
// Apply security settings
pdf.SecuritySettings.AllowUserPrinting = true;
pdf.MetaData.Author = "Your Company";
return File(pdf.BinaryData, "application/pdf");
}
public IActionResult ConfigureAdvancedPrinting(object sender, EventArgs e)
{
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.RenderDelay = 500; // Wait for dynamic content
// Generate complex PDF documents
var pdf = renderer.RenderHtmlAsPdf(GetDynamicContent());
// Apply security settings
pdf.SecuritySettings.AllowUserPrinting = true;
pdf.MetaData.Author = "Your Company";
return File(pdf.BinaryData, "application/pdf");
}
Public Function ConfigureAdvancedPrinting(sender As Object, e As EventArgs) As IActionResult
Dim renderer = New ChromePdfRenderer()
' Configure rendering options
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.EnableJavaScript = True
renderer.RenderingOptions.RenderDelay = 500 ' Wait for dynamic content
' Generate complex PDF documents
Dim pdf = renderer.RenderHtmlAsPdf(GetDynamicContent())
' Apply security settings
pdf.SecuritySettings.AllowUserPrinting = True
pdf.MetaData.Author = "Your Company"
Return File(pdf.BinaryData, "application/pdf")
End Function
文件產生後,只需使用 pdf.Print() 指令即可列印。
IronPrint 替代方案
對於特殊的列印需求,Iron Software 還提供 IronPrint,這是一個專用的 .NET 列印庫,具有增強的跨平台支援。 您可以在他們的網站上找到更多資訊的連結。主要參數就是檔案路徑。 產品詳情可在其網站上查看。
結論
IronPDF 將 ASP.NET PDF 列印從複雜的挑戰轉變為簡單的實作。 無需 Adobe Reader 或外部依賴項,只需編寫少量程式碼即可產生和列印 PDF 文件。 PDF 庫可以處理從 HTML 轉換到印表機配置的所有操作,使其成為伺服器端自動化和用戶端列印場景的理想選擇。
準備好簡化您的 PDF 列印工作流程了嗎? 立即開始免費試用,體驗 IronPDF 如何簡化 ASP.NET 應用程式中的文件處理。 憑藉全面的文件和直接的工程支援,您將在幾分鐘內即可開始生產就緒的 PDF 列印。
常見問題解答
我如何在ASP.NET中打印PDF文件?
您可以通過使用IronPDF在ASP.NET中打印PDF文件,該工具通過其全面的API簡化了流程,允許輕鬆整合和可靠的打印功能。
在ASP.NET應用程式中打印PDF的常見挑戰是什麼?
常見挑戰包括管理伺服器-客戶端架構的複雜性和生成一致的打印輸出。IronPDF通過設計用于無縫整合和可靠的結果的功能來解決這些挑戰。
IronPDF可以用來為特定目的如發票或報告生成PDF文件嗎?
是的,IronPDF可以用來生成PDF文件以滿足多種需求,包括發票、報告和運輸標籤,提供給開發者一個用於文件生成的多樣化工具。
IronPDF提供了什麼功能來支持在ASP.NET中打印PDF呢?
IronPDF提供了如HTML到PDF轉換、CSS樣式和JavaScript支持等功能,這些都促進了在ASP.NET應用程式中的有效PDF打印。
在ASP.NET中可以通過IronPDF自動化PDF打印嗎?
是的,IronPDF允許在ASP.NET應用程式中進行PDF打印的自動化,幫助開發者精簡工作流程並提高生產力。
IronPDF如何處理伺服器-客戶端架構的複雜性?
IronPDF被設計成應對伺服器-客戶端架構的複雜性,通過提供一個穩健的API簡化了直接從伺服器端生成和打印PDF的過程。
在打印之前,IronPDF支持對PDF文件進行自訂嗎?
IronPDF支持對PDF文件進行廣泛的自訂選項,允許開發者在打印之前控制佈局、內容和設計。
IronPDF支持哪些編程語言用於PDF打印?
IronPDF兼容C#和其他.NET語言,使其成為在ASP.NET框架中工作的開發者的理想選擇。
IronPDF能與其他.NET應用程式整合嗎?
是的,IronPDF可以輕鬆地與其他.NET應用程式整合,允許無縫添加到現有系統中,並增強PDF管理功能。
IronPDF如何保證在不同設備上打印輸出的穩定性?
IronPDF透過支持高保真渲染和HTML、CSS及JavaScript到PDF的準確轉換,無論使用何種設備進行打印,都能保證一致的打印輸出。
IronPDF 與 .NET 10 相容嗎?升級 IronPDF 有什麼好處?
是的,IronPDF 與 .NET 10 完全相容,包括針對 Windows、Linux、macOS 和容器化環境的 .NET 10 專案。升級至 .NET 10 可開啟各種改進,例如降低記憶體使用率、提高性能、新的 C# 語言功能,以及 ASP.NET Core 10 中可簡化 PDF 生成和整合的增強功能。



