在ASP.NET Framework Web應用程式中使用C#列印
IronPrint 的 PrintAsync 方法可在 ASP.NET 網頁應用程式中實現非阻塞式文件列印,避免在處理列印請求時造成介面凍結。 此異步方法可確保響應式 Web 應用程式能夠在不阻塞線程的情況下處理列印作業。
網路應用程式通常需要文件列印作為最終輸出。 將列印功能整合至網路應用程式會帶來挑戰,尤其是在處理異步作業時。 IronPrint 通過 PrintAsync 函數解決了這個問題。 本教程演示了如何在 ASP.NET Core 中實現 PrintAsync,以創建一個不阻塞的文件列印網頁應用程式。
在實施之前,請注意 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 網頁應用程式中進行列印
- 從 NuGet 安裝 C# 列印函式庫
- 將
IronPrint導入控制器 - 新增一個列印按鈕以觸發該動作
- 在控制器方法中呼叫
PrintAsync
如何在 ASP.NET 中實現非同步 PDF 列印?
此示例演示瞭如何在ASP.NET 網頁應用程式 (.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此增強的實施展示來自列印設定指南的概念,包括指定打印機名稱、配置紙張大小以及適當地處理錯誤。
當在網絡環境中進行打印機選擇時,利用獲取打印機名稱功能來動態填充可用的打印機列表:
// 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對於需要用戶交互的場景,考慮實施對話框列印方法,雖然這種方法更適合桌面應用程式而非網絡環境。
生產部署的其他考慮事項
在使用 IronPrint 部署您的 ASP.NET 應用程式時,請考慮這些因素:
- 授權配置:對於 ASP.NET 應用程式,請在 Web.config 中配置您的授權金鑰。查閱在 Web.config 中設置授權金鑰指南以正確設置。
- 打印機存取:確保應用程式池身份具有存取本地或網絡打印機的許可。 列印您的文件文檔提供了打印機存取要求。
- 錯誤處理:對於離線打印機或無法存取的文件,實施可靠的錯誤處理。 若有技術問題,請使用工程請求流程來解決複雜問題。
- 性能:對於高容量列印,實施佇列系統以有效管理列印請求。 非同步的
PrintAsync適用於此類實施。
要獲得全面的列印功能,請查閱 API 參考以獲取專案 IronPrint 命名空間中所有方法和屬性的詳細文檔。
常見問題
使用IronPrint的PrintAsync方法於ASP.NET網頁應用程式中的主要優勢是什麼?
IronPrint的PrintAsync方法允許非阻塞的文件列印,確保您的ASP.NET網頁應用程式在處理列印請求時保持回應。
如何將IronPrint整合到我的ASP.NET網頁應用程式中?
要整合IronPrint,通過NuGet安裝該程式庫,將其匯入到您的控制器檔案中,添加一個列印按鈕以觸發列印動作,並使用PrintAsync方法進行非同步列印。
為什麼我應該在我的網頁應用程式中選擇非同步列印?
使用IronPrint的PrintAsync進行非同步列印可防止介面卡住,並允許同時處理多個列印請求,這提高了您的網頁應用程式的回應性。
如何使用IronPrint配置自訂列印設定?
您可以透過建立PrintSettings的實例來配置自訂列印設定,指定參數如打印機名稱、紙張大小、方向、份數和DPI,然後將其傳遞給PrintAsync方法。
在我的ASP.NET網頁應用程式中應該在哪裡添加列印按鈕?
在'Index.cshtml'或您的首頁視圖中添加列印按鈕。此按鈕應該調用控制器中的ActionResult方法以觸發列印。
如何在列印過程中處理錯誤?
在您的PrintAsync調用周圍使用try-catch塊來捕捉異常並平穩地處理它們,提供用戶反饋或必要時進行記錄。
使用IronPrint部署ASP.NET應用程式時應考慮什麼?
確保您的應用程式的授權配置、打印機存取權限和錯誤處理機制在生產環境中正確設置。
如何在我的應用程式中動態顯示可用打印機清單?
使用IronPrint的GetPrinterNames方法來檢索並動態顯示可用打印機清單給用戶。
PrintAsync方法在管理大批量列印中的作用是什麼?
PrintAsync通過啟用隊列系統支援大批量列印,能有效管理列印請求而不阻塞應用程式。
是否可以在網頁環境中使用IronPrint進行帶對話框的列印?
雖然可以在桌面應用程式中整合列印對話框,但這種方法不太適合網頁環境,在這裡,非同步方法因最佳效能而被偏好使用。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。