使用 C## 在 ASP.NET Framework Web 应用程序中进行打印
IronPrint的PrintAsync方法在ASP.NET Web应用程序中启用无阻塞的文档打印,防止在处理打印请求时UI冻结。 这种异步方法可确保响应式网络应用程序能够在不阻塞线程的情况下处理打印操作。
网络应用程序通常需要将文档打印作为最终输出。 将打印功能与网络应用程序相集成是一项挑战,尤其是在处理异步操作时。 IronPrint通过PrintAsync函数解决了这个问题。 本教程演示了在ASP.NET Core中实现PrintAsync以创建一个不阻塞打印文档的Web应用程序。
在实施之前,请注意 IronPrint 提供了全面的功能,包括打印机信息检索和自定义打印设置。 这些功能使其成为需要强大打印功能的企业 ASP.NET 应用程序的理想选择。
快速入门:ASP.NET 中的异步 PDF 打印- 通过NuGet安装IronPrint:
Install-Package IronPrint - 在控制器文件中导入
IronPrint - 添加一个打印按钮以触发该方法
- 在控制器动作中调用
await Printer.PrintAsync("file.pdf") - 验证按下按钮时的文档打印功能
-
1Install IronPrint with NuGet Package Manager
-
2复制并运行这段代码。
await IronPrint.Printer.PrintAsync("Basic.pdf");Await IronPrint.Printer.PrintAsync("Basic.pdf")Await IronPrint.Printer.PrintAsync("Basic.pdf") -
3部署到您的生产环境中进行测试
通过免费试用立即在您的项目中开始使用IronPrint
开始使用 IronPrint
Start using IronPrint in your project today with a free trial.
如何在 ASP.NET Web 应用程序中打印
- 从 NuGet 安装 C# 打印库
- 将
IronPrint导入控制器 - 添加一个打印按钮以触发该操作
- 在控制器方法中调用
PrintAsync
如何在 ASP.NET 中实现异步 PDF 打印?
此示例演示使用PrintAsync方法在ASP.NET Web应用程序(.NET Framework)项目中异步打印PDF文件。 Print方法相比,保持应用程序响应。
异步方法在网络应用程序中至关重要,因为在网络应用程序中,多个用户可能会同时触发打印操作。 与同步PrintAsync确保您的应用程序在不影响性能的情况下处理并发请求。
我应该在哪里添加打印按钮?
在您的"Index.cshtml"(或主页视图)中,添加一个按钮,点击该按钮将触发一个操作。 此按钮在您的控制器中调用ActionResult方法:
@{
ViewBag.Title = "Home Page";
}
<main>
<section class="row" aria-labelledby="aspnetTitle">
<h1 id="title">ASP.NET</h1>
<p>
<!-- Button that triggers the PrintPdf ActionResult -->
<a class="btn btn-primary btn-md" onclick="location.href='@Url.Action("PrintPdf", "Home")'">Print PDF</a>
</p>
</section>
</main>

如何在控制器中配置 PrintAsync?
在您的PrintAsync方法。 这种方法可以异步执行打印操作,提高应用程序的响应速度。 在实施之前,请确保许可证密钥配置正确,以便在生产中使用。
using IronPrint;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace WebApplication4.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
return View();
}
// Action method to handle the printing operation
// This makes use of the PrintAsync method to avoid blocking the main thread
public ActionResult PrintPdf()
{
// Wait for the asynchronous print operation to complete
Printer.PrintAsync("Basic.pdf").Wait();
// Return some view, for example, a confirmation page or the index page
return View(); // Replace with an appropriate view
}
}
}using IronPrint;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace WebApplication4.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
return View();
}
// Action method to handle the printing operation
// This makes use of the PrintAsync method to avoid blocking the main thread
public ActionResult PrintPdf()
{
// Wait for the asynchronous print operation to complete
Printer.PrintAsync("Basic.pdf").Wait();
// Return some view, for example, a confirmation page or the index page
return View(); // Replace with an appropriate view
}
}
}Imports IronPrint
Imports System.Threading.Tasks
Imports System.Web.Mvc
Namespace WebApplication4.Controllers
Public Class HomeController
Inherits Controller
Public Function Index() As ActionResult
Return View()
End Function
Public Function About() As ActionResult
ViewBag.Message = "Your application description page."
Return View()
End Function
Public Function Contact() As ActionResult
Return View()
End Function
' Action method to handle the printing operation
' This makes use of the PrintAsync method to avoid blocking the main thread
Public Function PrintPdf() As ActionResult
' Wait for the asynchronous print operation to complete
Printer.PrintAsync("Basic.pdf").Wait()
' Return some view, for example, a confirmation page or the index page
Return View() ' Replace with an appropriate view
End Function
End Class
End NamespaceImports IronPrint
Imports System.Threading.Tasks
Imports System.Web.Mvc
Namespace WebApplication4.Controllers
Public Class HomeController
Inherits Controller
Public Function Index() As ActionResult
Return View()
End Function
Public Function About() As ActionResult
ViewBag.Message = "Your application description page."
Return View()
End Function
Public Function Contact() As ActionResult
Return View()
End Function
' Action method to handle the printing operation
' This makes use of the PrintAsync method to avoid blocking the main thread
Public Function PrintPdf() As ActionResult
' Wait for the asynchronous print operation to complete
Printer.PrintAsync("Basic.pdf").Wait()
' Return some view, for example, a confirmation page or the index page
Return View() ' Replace with an appropriate view
End Function
End Class
End Namespace对于高级场景,应实施适当的Async/Await模式并自定义打印操作。 下面是一个增强示例,演示了错误处理和自定义打印设置:
using IronPrint;
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace WebApplication4.Controllers
{
public class HomeController : Controller
{
// Async action method with proper error handling
public async Task<ActionResult> PrintPdfAdvanced()
{
try
{
// Create custom print settings
var printSettings = new PrintSettings
{
// Select specific printer
PrinterName = "Microsoft Print to PDF",
// Set paper size
PaperSize = PaperSize.A4,
// Configure orientation
PaperOrientation = PaperOrientation.Portrait,
// Set number of copies
NumberOfCopies = 1,
// Configure DPI for high-quality output
Dpi = 300
};
// Print asynchronously with custom settings
await Printer.PrintAsync("Basic.pdf", printSettings);
// Log successful print operation (optional)
System.Diagnostics.Debug.WriteLine("Document printed successfully");
// Return success view or redirect
TempData["PrintMessage"] = "Document sent to printer successfully!";
return RedirectToAction("Index");
}
catch (Exception ex)
{
// Handle printing errors gracefully
System.Diagnostics.Debug.WriteLine($"Printing error: {ex.Message}");
TempData["ErrorMessage"] = "Unable to print document. Please try again.";
return RedirectToAction("Index");
}
}
}
}using IronPrint;
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace WebApplication4.Controllers
{
public class HomeController : Controller
{
// Async action method with proper error handling
public async Task<ActionResult> PrintPdfAdvanced()
{
try
{
// Create custom print settings
var printSettings = new PrintSettings
{
// Select specific printer
PrinterName = "Microsoft Print to PDF",
// Set paper size
PaperSize = PaperSize.A4,
// Configure orientation
PaperOrientation = PaperOrientation.Portrait,
// Set number of copies
NumberOfCopies = 1,
// Configure DPI for high-quality output
Dpi = 300
};
// Print asynchronously with custom settings
await Printer.PrintAsync("Basic.pdf", printSettings);
// Log successful print operation (optional)
System.Diagnostics.Debug.WriteLine("Document printed successfully");
// Return success view or redirect
TempData["PrintMessage"] = "Document sent to printer successfully!";
return RedirectToAction("Index");
}
catch (Exception ex)
{
// Handle printing errors gracefully
System.Diagnostics.Debug.WriteLine($"Printing error: {ex.Message}");
TempData["ErrorMessage"] = "Unable to print document. Please try again.";
return RedirectToAction("Index");
}
}
}
}Imports IronPrint
Imports System
Imports System.Threading.Tasks
Imports System.Web.Mvc
Namespace WebApplication4.Controllers
Public Class HomeController
Inherits Controller
' Async action method with proper error handling
Public Async Function PrintPdfAdvanced() As Task(Of ActionResult)
Try
' Create custom print settings
Dim printSettings As New PrintSettings With {
' Select specific printer
.PrinterName = "Microsoft Print to PDF",
' Set paper size
.PaperSize = PaperSize.A4,
' Configure orientation
.PaperOrientation = PaperOrientation.Portrait,
' Set number of copies
.NumberOfCopies = 1,
' Configure DPI for high-quality output
.Dpi = 300
}
' Print asynchronously with custom settings
Await Printer.PrintAsync("Basic.pdf", printSettings)
' Log successful print operation (optional)
System.Diagnostics.Debug.WriteLine("Document printed successfully")
' Return success view or redirect
TempData("PrintMessage") = "Document sent to printer successfully!"
Return RedirectToAction("Index")
Catch ex As Exception
' Handle printing errors gracefully
System.Diagnostics.Debug.WriteLine($"Printing error: {ex.Message}")
TempData("ErrorMessage") = "Unable to print document. Please try again."
Return RedirectToAction("Index")
End Try
End Function
End Class
End NamespaceImports IronPrint
Imports System
Imports System.Threading.Tasks
Imports System.Web.Mvc
Namespace WebApplication4.Controllers
Public Class HomeController
Inherits Controller
' Async action method with proper error handling
Public Async Function PrintPdfAdvanced() As Task(Of ActionResult)
Try
' Create custom print settings
Dim printSettings As New PrintSettings With {
' Select specific printer
.PrinterName = "Microsoft Print to PDF",
' Set paper size
.PaperSize = PaperSize.A4,
' Configure orientation
.PaperOrientation = PaperOrientation.Portrait,
' Set number of copies
.NumberOfCopies = 1,
' Configure DPI for high-quality output
.Dpi = 300
}
' Print asynchronously with custom settings
Await Printer.PrintAsync("Basic.pdf", printSettings)
' Log successful print operation (optional)
System.Diagnostics.Debug.WriteLine("Document printed successfully")
' Return success view or redirect
TempData("PrintMessage") = "Document sent to printer successfully!"
Return RedirectToAction("Index")
Catch ex As Exception
' Handle printing errors gracefully
System.Diagnostics.Debug.WriteLine($"Printing error: {ex.Message}")
TempData("ErrorMessage") = "Unable to print document. Please try again."
Return RedirectToAction("Index")
End Try
End Function
End Class
End Namespace该增强实施展示了打印设置指南中的概念,包括指定打印机名称、配置纸张大小和适当处理错误。
在网络环境中选择打印机时,可利用 Get Printer Names 功能动态填充可用打印机列表:
// Get list of available printers
public ActionResult GetAvailablePrinters()
{
var printers = Printer.GetPrinterNames();
ViewBag.PrinterList = new SelectList(printers);
return View();
}// Get list of available printers
public ActionResult GetAvailablePrinters()
{
var printers = Printer.GetPrinterNames();
ViewBag.PrinterList = new SelectList(printers);
return View();
}' Get list of available printers
Public Function GetAvailablePrinters() As ActionResult
Dim printers = Printer.GetPrinterNames()
ViewBag.PrinterList = New SelectList(printers)
Return View()
End Function' Get list of available printers
Public Function GetAvailablePrinters() As ActionResult
Dim printers = Printer.GetPrinterNames()
ViewBag.PrinterList = New SelectList(printers)
Return View()
End Function对于需要用户交互的场景,可以考虑采用 Print with Dialog 方法,不过这种方法更适合桌面应用程序而非网络环境。
生产部署的其他注意事项
在使用 IronPrint 部署 ASP.NET 应用程序时,请考虑以下因素:
1.许可配置:对于 ASP.NET 应用程序,请在 Web.config 中配置许可证密钥。有关正确设置,请参阅 Setting License Key in Web.config 指南。
2.打印机访问:确保应用程序池身份具有访问本地或网络打印机的权限。 Print Your Documents 文档提供了打印机访问要求。
3.错误处理:针对脱机打印机或无法访问的文档实施强大的错误处理功能。 对于技术问题,请使用工程请求流程来解决复杂问题。
4.性能:对于大批量打印,实施队列系统以高效管理打印请求。 异步PrintAsync是此类实现的理想选择。
有关全面的打印功能,请查阅API参考,获取IronPrint命名空间中的所有方法和属性的详细文档。
常见问题解答
如何在 ASP.NET Framework 应用程序中实现异步 PDF 打印?
您可以使用 IronPrint 的 PrintAsync 方法实现异步 PDF 打印。只需在控制器操作中添加 return await IronPrint.Printer.PrintAsync("yourfile.pdf"); 即可。这种非阻塞方法可确保您的网络应用程序在处理打印请求时保持响应,防止在文档打印操作过程中出现 UI 冻结。
为什么要在网络应用程序中使用异步打印而不是同步打印?
using IronPrint 的 PrintAsync 方法进行异步打印对于网络应用程序至关重要,因为在网络应用程序中,多个用户可能会同时触发打印操作。与阻塞线程的同步打印方法不同,PrintAsync 可确保您的应用程序在处理并发请求时不会降低性能,即使在高负载情况下也能保持响应速度。
在我的 ASP.NET Framework 项目中添加 PDF 打印的最基本步骤是什么?
最基本的工作流程包括 5 个步骤:1) 下载 C# 的 IronPrint 库;2) 将 IronPrint 导入类文件;3) 在视图中添加打印按钮;4) 在控制器动作中实施 PrintAsync;5) 按下按钮时验证文档打印是否正常。这一简化流程只需修改极少的代码。
如何在 ASP.NET 视图中添加打印按钮?
在 Index.cshtml 或主页视图中,添加一个触发控制器动作的按钮。使用类似于 <button onclick="location.href="@Url.Action("PrintPDF", "Home")"" class="btn btn-primary">打印 PDF</button> 这样的 HTML。点击该按钮后,将调用 "主页 "控制器中的 PrintPDF ActionResult 方法。
使用异步打印时,能否自定义打印设置?
是的,IronPrint 提供了全面的功能,包括自定义打印设置和打印机信息检索。这些功能使其成为需要强大打印功能的企业级 ASP.NET 应用程序的理想选择,这些功能可配置打印机选择、页面方向、页边距和其他打印参数。
How can I handle errors during the printing process?
Use try-catch blocks around your PrintAsync calls to catch exceptions and handle them gracefully, providing user feedback or logging as necessary.
What should I consider for deploying an ASP.NET application using IronPrint?
Ensure your application's license configuration, printer access permissions, and error handling mechanisms are properly set up in production.
How can I dynamically populate available printer lists in my application?
Use the GetPrinterNames method from IronPrint to retrieve and dynamically display a list of available printers to users.
What is the role of the PrintAsync method in managing high-volume printing?
PrintAsync supports high-volume printing by enabling a queue system that efficiently manages print requests without blocking the application.
Is it possible to use IronPrint for printing with a dialog in a web environment?
While it's possible to integrate a print dialog in desktop applications, this approach is less suitable for web environments, where asynchronous methods are preferred for best performance.
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。