在ASP.NET Framework Web应用程序中使用C#打印
IronPrint的PrintAsync方法在ASP.NET web应用程序中实现非阻塞文档打印,防止在处理打印请求时界面冻结。 这种异步方法可确保响应式网络应用程序能够在不阻塞线程的情况下处理打印操作。
网络应用程序通常需要将文档打印作为最终输出。 将打印功能与网络应用程序相集成是一项挑战,尤其是在处理异步操作时。 IronPrint通过PrintAsync功能解决了这个问题。 本教程演示了如何通过ASP.NET Core实现PrintAsync,以创建一个无需阻塞可打印文档的web应用程序。
在实现之前,请注意IronPrint提供了包括功能,如打印机信息检索和自定义打印设置。 这些功能使其成为需要可靠打印功能的企业ASP.NET应用程序的理想选择。
快速入门:ASP.NET 中的异步 PDF 打印- 通过NuGet安装IronPrint:
Install-Package IronPrint - 将
IronPrint导入到控制器文件中 - 添加一个打印按钮以触发该方法
- 在控制器操作中调用
await Printer.PrintAsync("file.pdf") - 验证按下按钮时的文档打印功能
-
1使用 IronPrint 安装 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
从今天开始在您的项目中使用 IronPrint 免费试用。
如何在 ASP.NET Web 应用程序中打印
- 从 NuGet 安装 C# 打印库
- 将
IronPrint导入控制器 - 添加一个打印按钮以触发该操作
- 在控制器方法中调用
PrintAsync
如何在ASP.NET中实现异步PDF打印?
此示例演示在ASP.NET Web应用程序(.NET Framework)项目中使用PrintAsync方法异步打印PDF文件。 PrintAsync 异步启动打印,与阻塞线程的同步 Print 方法相比,保持应用程序的响应性。
异步方法在网络应用程序中至关重要,因为在网络应用程序中,多个用户可能会同时触发打印操作。 与同步的 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?
在您的 HomeController 中,实施 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此增强的实施展示了来自打印设置指南的概念,包括指定打印机名称、配置纸张尺寸以及适当处理错误。
在web环境中进行打印机选择时,利用获取打印机名称功能来动态填充可用打印机列表:
// 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对于需要用户交互的场景,考虑实现带对话框的打印方法,尽管这更适合桌面应用程序而非web环境。
生产部署的其他考虑事项
在使用 IronPrint 部署 ASP.NET 应用程序时,请考虑以下因素:
- 许可证配置:对于ASP.NET应用程序,请在Web.config中配置您的许可证密钥。有关正确设置方法,请参阅在Web.config中设置许可证密钥指南。
- 打印机访问:确保应用程序池标识有权访问本地或网络打印机。 打印您的文档文档提供打印机访问要求。
- 错误处理:为离线打印机或无法访问的文档实施可靠的错误处理。 对于技术问题,请使用工程请求流程来解决复杂问题。
- 性能:对于大量打印,实施队列系统以有效管理打印请求。 异步
PrintAsync是这种实现的理想选择。
为了获得全面的打印功能,请查阅 API参考文档,其中详细记录了 IronPrint 命名空间中的所有方法和属性。
常见问题
在ASP.NET Web应用程序中使用IronPrint的PrintAsync方法的主要优势是什么?
IronPrint的PrintAsync方法支持非阻塞文档打印,确保您的ASP.NET Web应用程序在处理打印请求时保持响应。
如何将IronPrint集成到我的ASP.NET Web应用程序中?
要集成IronPrint,通过NuGet安装库,将其导入到您的控制器文件中,添加一个用于触发打印操作的打印按钮,并使用PrintAsync方法进行异步打印。
为什么在我的Web应用程序中选择异步打印?
使用IronPrint的PrintAsync进行异步打印可以防止UI冻结,并允许同时处理多个打印请求,从而提高您的Web应用程序的响应速度。
如何使用IronPrint配置自定义打印设置?
可以通过创建PrintSettings实例,指定参数如打印机名称、纸张尺寸、方向、份数和DPI,并将其传递给PrintAsync方法来配置自定义打印设置。
在我的ASP.NET Web应用程序中应该在哪里添加打印按钮?
将打印按钮添加到'Index.cshtml'或您的主页视图中。此按钮应调用您控制器中的ActionResult方法以触发打印。
如何处理打印过程中出现的错误?
在您的PrintAsync调用中使用try-catch块来捕获异常并优雅地处理它们,提供用户反馈或进行必要的日志记录。
部署一个使用IronPrint的ASP.NET应用程序时应该考虑什么?
确保您的应用程序许可证配置、打印机访问权限和错误处理机制在生产环境中得到正确设置。
如何在我的应用程序中动态填充可用的打印机列表?
使用IronPrint的GetPrinterNames方法来检索并动态显示可供用户使用的打印机列表。
PrintAsync方法在管理大批量打印中扮演什么角色?
PrintAsync通过支持一个队列系统来高效管理打印请求,从而支持大批量打印而不阻塞应用程序。
IronPrint是否可以用于在Web环境中显示打印对话框?
虽然可以在桌面应用程序中集成打印对话框,但这种方法不太适合Web环境,在Web环境中异步方法是最佳性能的首选。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。