跳過到頁腳內容
使用IRONPDF

使用 IronPDF 以程式設計方式透過 ASP.NET 列印 PDF 文件

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
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

上面的程式碼展示了一個常見的錯誤。 伺服器環境缺少直接印表機存取權限,並且由於 IIS 權限限制,系統會拋出錯誤。 另一點要記住的是,Web應用程式必須有效地處理伺服器端和用戶端列印場景。

開始使用 IronPdf

IronPDF提供了一個完整的 .NET core 解決方案,用於產生 PDF 文件並進行列印,無需 Adobe Reader 等外部相依性。 讓我們使用 NuGet 安裝 IronPDF 套件:

Install-Package IronPdf
Install-Package IronPdf
SHELL

這個 .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: $749</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: $749</p>");
        // Print to default printer
        pdf.Print();
        return Ok("Document sent to printer");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

ChromePdfRenderer負責處理轉換,同時保留 CSS 樣式和字體大小格式。 此範例示範了在無需使用者互動的情況下使用預設印表機進行基本列印。

輸出

使用 IronPDF 以程式設計方式在 ASP.NET 中列印 PDF 檔案:圖 1 - 列印 PDF(在本例中,我們將列印到磁碟)

網路印表機配置

對於需要特定印表機路由的企業環境:

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 });
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這種方法可以完全控製印表機設置,包括紙張格式和分辨率,這對於正確的繪圖和佈局至關重要。

輸出

使用 IronPDF 以程式設計方式在 ASP.NET 中列印 PDF 檔案:圖 2 - 透過網頁列印列印 PDF

列印確認

使用 IronPDF 以程式設計方式在 ASP.NET 中列印 PDF 檔案:圖 3 - PDF 列印作業成功訊息

客戶端列印策略

由於瀏覽器限制了直接列印,因此可以透過提供 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.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>$749.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.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>$749.00</b></p>
        </div>
    </body>
    </html>";
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

PDF 文件將在瀏覽器中打開,使用者可以使用標準的瀏覽器列印對話框,透過預設印表機觸發列印。 這種方法優於直接向伺服器端發出列印請求。

輸出

使用 IronPDF 以程式設計方式在 ASP.NET 中列印 PDF 檔案:圖 4 - 用戶端列印對話框

處理各種原始碼輸入

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.");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

以上程式碼示範如何建立新的文件來源處理清單。 每種方法都能在保持列印品質的同時,保留文件結構和圖形。

使用 IronPDF 以程式設計方式在 ASP.NET 中列印 PDF 檔案:圖片 5 - 與"使用 IronPDF 以程式設計方式在 ASP.NET 中列印 PDF 檔案"相關的 7 張圖片中的第 5 張

錯誤處理和日誌記錄

在生產環境中實作健全的錯誤處理機制:

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");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

即使系統資源不可用,也能確保可靠列印,這是列印服務的關鍵組成部分。

輸出情景

印表機不可用

如果程式碼中指定的印表機不可用,程式碼將顯示以下錯誤訊息:

使用 IronPDF 以程式設計方式在 ASP.NET 中列印 PDF 檔案:圖片 6 - 印表機無法使用錯誤

PDF文件列印成功。

如果您的 PDF 文件列印成功,您應該會看到類似這樣的確認訊息:

使用 IronPDF 以程式設計方式在 ASP.NET 中列印 PDF 檔案:圖 7 - 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");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

文件產生後,只需使用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 文件,方法是將 HTML 文件轉換為 PDF,然後將其傳送到印表機。 IronPDF 的內建方法簡化了此流程。

在 ASP.NET 中使用 IronPDF 列印 PDF 有哪些好處?

IronPDF 為在 ASP.NET 中列印 PDF 提供了許多優勢,包括易於整合、高品質渲染以及能夠精確地將 HTML 內容轉換為 PDF。

使用 IronPDF 是否可以在列印前自訂 PDF 文件?

是的,IronPDF 允許您在列印前自訂 PDF,例如新增頁首、頁尾和浮水印,以及設定頁面大小和邊距。

IronPDF 能否處理用於列印的大型 PDF 檔案?

IronPDF 能夠有效率地處理大型 PDF 文件,確保即使是複雜的文件也能從您的 ASP.NET 應用程式準確快速地列印出來。

IronPDF是否支援不同的PDF列印印表機設定?

IronPDF 支援多種印表機設置,您可以根據需要指定紙張尺寸、方向和列印品質。

在 ASP.NET 中,有沒有辦法在列印前預覽 PDF 檔案?

使用 IronPDF,您可以在 ASP.NET 應用程式中產生和顯示 PDF 預覽,使用戶能夠在執行列印命令之前查看文件。

IronPDF可以將哪些格式轉換為PDF以供列印?

IronPDF 可以將多種格式轉換為 PDF 進行列印,包括 HTML、ASPX 和圖像文件,使其能夠靈活滿足各種應用需求。

IronPDF 如何保證列印 PDF 文件的品質?

IronPDF 使用先進的渲染技術,確保列印的 PDF 文件與原始內容保持高度一致性,文字清晰銳利,影像清晰可辨。

IronPDF 可以用於列印加密或密碼保護的 PDF 檔案嗎?

是的,IronPDF 可以處理加密或密碼保護的 PDF 文件,您可以透過在 ASP.NET 應用程式中提供必要的憑證來安全地列印它們。

將 IronPDF 整合到現有的 ASP.NET 應用程式中有多容易?

由於 IronPDF 擁有全面的文件和對各種開發環境的支持,因此將其整合到現有的 ASP.NET 應用程式中非常簡單。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。