跳至页脚内容
使用IRONPDF

如何在 ASP.NET 中以编程方式打印 PDF 文件

ASP .NET 打印 PDF 文件任务通常涉及开发人员经常遇到的独特挑战。 无论您是为发票、报告或运输标签生成 PDF 文档,实现可靠的打印功能都需要导航服务器-客户端架构的复杂性。

In this article, we'll show you how to handle PDF printing tasks using IronPDF's powerful PDF library for .NET.

理解挑战

传统的桌面应用程序可以直接访问默认打印机,但 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 核心解决方案来生成 PDF 文档并打印它们,而无需像 Adobe Reader 这样的外部依赖。 让我们使用 NuGet 安装 IronPDF 包:

Install-Package IronPdf

这个 .NET 库可以跨操作系统无缝运行,消除了其他库困扰的兼容性问题。 这款工具在微软 Windows 和其他操作系统环境中效果良好。

使用默认打印机在服务器端创建和打印 PDF 文档

以下是如何从 HTML 标记在您的 ASP.NET 控制器中生成和打印 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 样式和字体大小格式。 此示例显示了如何在没有用户交互的情况下基本打印到默认打印机。

输出

网络打印机配置

对于需要特定打印机路由的企业环境:

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

这种方法提供了对打印机设置的完全控制,包括纸张格式和分辨率,这对于正确的绘图和布局至关重要。

输出

!如何在 ASP.NET 中以编程方式打印 PDF 文件:图 2 - 使用网络打印打印 PDF

打印确认

!如何在 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 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>$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 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>$749.00</b></p>
            </div>
        </body>
        </html>";
    }
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

PDF 文档在浏览器中打开,用户可以通过使用标准的浏览器打印对话框触发他们的默认打印机进行打印。 这种方法优于直接发起服务器端打印请求。

输出

!如何在 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

以上几行展示了如何创建一个新的处理文件源列表。 每个方法在维护打印质量的同时保留了文档结构和图形。

!如何在 ASP.NET 中以编程方式打印 PDF 文件:图 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

这可确保即使在系统资源不可用时也能可靠打印,并且是打印服务的重要组成部分。

输出 Scenarios

打印机不可用

如果代码中指定的打印机不可用,代码将提供此错误消息:

!如何在 ASP.NET 中以编程方式打印 PDF 文件:图 6 - 打印机不可用错误

PDF 成功打印

如果您的 PDF 打印成功,您将看到类似于以下的确认消息:

!如何在 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文件,该工具通过其综合的API简化了过程,允许轻松集成和可靠的打印功能。

在ASP.NET应用程序中打印PDF时的常见挑战是什么?

常见挑战包括管理服务器-客户端架构的复杂性和生成一致的打印输出。IronPDF通过为无缝集成和可靠的结果设计的功能解决了这些挑战。

IronPDF是否可以用于生成特定用途的PDF文档,如发票或报告?

是的,IronPDF可以用于生成多种用途的PDF,例如发票、报告和运单标签,为开发人员提供多功能的文档生成工具。

IronPDF提供了哪些功能来支持ASP.NET中的PDF打印?

IronPDF提供了HTML到PDF转换、CSS样式和JavaScript支持等功能,这些都促进了ASP.NET应用程序中有效的PDF打印。

使用IronPDF在ASP.NET中是否可以自动化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?升级到 .NET 10 能带来哪些好处?

是的,IronPDF 完全兼容 .NET 10,包括面向 Windows、Linux、macOS 和容器化环境的 .NET 10 项目。升级到 .NET 10 可解锁诸多改进,例如降低内存占用、提升性能、使用新的 C# 语言特性,以及 ASP.NET Core 10 中可简化 PDF 生成和集成的增强功能。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。