使用IRONPDF ASP .NET 使用 IronPDF 以编程方式打印 PDF 文件 Curtis Chau 已发布:十二月 18, 2025 下载 IronPDF NuGet 下载 DLL 下载 Windows 安装程序 免费试用 法学硕士副本 法学硕士副本 将页面复制为 Markdown 格式,用于 LLMs 在 ChatGPT 中打开 向 ChatGPT 咨询此页面 在双子座打开 向 Gemini 询问此页面 在双子座打开 向 Gemini 询问此页面 打开困惑 向 Perplexity 询问有关此页面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 复制链接 电子邮件文章 ASP.NET 打印 PDF 文件任务 ASP .NET 打印 PDF 文件任务通常涉及开发人员经常遇到的独特挑战。 无论您是为发票、报告或运输标签生成 PDF 文档,实现可靠的打印功能都需要导航服务器-客户端架构的复杂性。 在本文中,我们将向您展示如何使用 PDF 打印任务 使用 IronPDF 的 强大 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 核心解决方案来生成 PDF 文档并打印它们,而无需像 Adobe Reader 这样的外部依赖。 让我们使用 NuGet 安装 IronPDF 包: Install-Package IronPdf Install-Package IronPdf SHELL 这个 .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 样式和字体大小格式。 此示例显示了如何在没有用户交互的情况下基本打印到默认打印机。 输出 使用 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 for .NET 为在 ASP.NET 中打印 PDF 提供了多种优势,包括易于集成、高质量渲染以及能够将 HTML 内容精确转换为 PDF。 是否可以使用 IronPDF 在打印前自定义 PDF? 是的,IronPdf 允许您在打印前通过添加页眉、页脚和水印以及设置页面大小和页边距自定义 PDF。 IronPDF 能否处理打印用的大型 PDF 文件? IronPDF for .NET 能够高效处理大型 PDF 文件,确保从您的 ASP.NET 应用程序中准确、快速地打印出复杂的文档。 IronPDF 是否支持不同的 PDF 打印机设置? IronPDF 支持各种打印机设置,您可以根据需要指定纸张大小、方向和打印质量。 是否有办法在 ASP.NET 中打印前预览 PDF? 通过 IronPDF for .NET,您可以在 ASP.NET 应用程序中生成并显示 PDF 预览,让用户在启动打印命令前查看文档。 IronPDF 可将哪些格式转换为 PDF 用于打印? IronPDF 可将多种格式转换为 PDF 格式进行打印,包括 HTML、ASPX 和图像文件,因此可满足各种应用需求。 IronPDF 如何确保打印 PDF 文档的质量? IronPDF 采用先进的渲染技术,确保打印出的 PDF 文档与原始内容保持高保真,文字清晰,图像清晰。 IronPDF 可用于打印加密或密码保护的 PDF 吗? 是的,IronPDF for .NET 可以处理加密或密码保护的 PDF 文件,您只需在 ASP.NET 应用程序中提供必要的凭证即可安全地打印 PDF 文件。 将 IronPDF 集成到现有 ASP.NET 应用程序中有多容易? 由于 IronPDF 提供了全面的文档并支持各种开发环境,因此将 IronPDF 集成到现有的 ASP.NET 应用程序中非常简单。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已发布十二月 18, 2025 .NET PDF API 是 .NET 开发人员的指南。 如何使用 IronPDF for .NET 创建 .NET PDF API 阅读更多 已发布十二月 18, 2025 如何使用 Aspose C# 和 IronPDF 创建 PDF 通过这本专为开发人员设计的分步指南,了解如何使用 Aspose C# 和 IronPDF 创建 PDF。 阅读更多 已发布十二月 18, 2025 使用 IronPDF 创建 .NET Core PDF 生成器 使用 IronPDF 在 .NET Core 中构建强大的 PDF 生成器。将 HTML 转换为 PDF,创建发票,并通过像素完美的渲染生成报告。 阅读更多 .NET Core 使用 IronPDF 创建 PDF 文件探索使用 IronPDF 在 C# 中动...
已发布十二月 18, 2025 如何使用 Aspose C# 和 IronPDF 创建 PDF 通过这本专为开发人员设计的分步指南,了解如何使用 Aspose C# 和 IronPDF 创建 PDF。 阅读更多
已发布十二月 18, 2025 使用 IronPDF 创建 .NET Core PDF 生成器 使用 IronPDF 在 .NET Core 中构建强大的 PDF 生成器。将 HTML 转换为 PDF,创建发票,并通过像素完美的渲染生成报告。 阅读更多