使用 C## 在 ASP.NET Framework Web App 中打印

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronPrint 的 PrintAsync 方法可在 ASP.NET Web 應用程式中實現無阻塞的文件列印,防止在處理列印請求時發生 UI 凍結。 此異步方法可確保響應式 Web 應用程式能夠在不阻塞線程的情況下處理列印作業。

<! -- 引言實作示意圖 --> <!--說明:說明程式碼概念的圖表或截圖 -->

網路應用程式通常需要文件列印作為最終輸出。 將列印功能整合至網路應用程式會帶來挑戰,尤其是在處理異步作業時。 IronPrint 透過 PrintAsync 函式解決了這個問題。 本教學示範使用 ASP.NET Core 實作 PrintAsync 以建立無阻塞列印文件的 Web 應用程式。

在實施之前,請注意 IronPrint 提供全面的功能,包括印表機資訊檢索自訂列印設定。 這些功能使其非常適合需要強大列印功能的企業級 ASP.NET 應用程式。

快速入門:在 ASP.NET 中使用 IronPrint 進行非同步 PDF 列印

以下是展示 IronPrint 的 PrintAsync API 的最小示例--您控制器中的一行即可開始列印,而不會凍結您的應用程式。不需要任何模板。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronPrint

    PM > Install-Package IronPrint

  2. 複製並運行這段程式碼。

    return await IronPrint.Printer.PrintAsync("Basic.pdf");
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronPrint,免費試用!
    arrow pointer

如何在 ASP.NET 中實作異步 PDF 列印?

本範例使用 PrintAsync 方法,在 ASP.NET Web Application (.NET Framework) 專案中以非同步方式列印 PDF 檔案。 PrintAsync 以異步方式啟動列印,與阻塞線程的同步 Print 方法相比,可保持應用程式的反應速度。

<! -- 說明 PrintAsync 實作流程的圖表 --> <!--說明:說明 PrintAsync 工作流程的圖表或截圖 -->

在多位使用者可能會同時觸發列印作業的網路應用程式中,異步方式至關重要。 與同步的 Print 方法不同,PrintAsync 可確保您的應用程式在處理並發要求時不會降低效能。

我應該在哪裡加入列印按鈕?

在您的"Index.cshtml"(或首頁視圖)中,新增一個按鈕,點擊該按鈕將觸發一個操作。 這個按鈕在您的控制器中呼叫 ActionResult 方法:

@{
    ViewBag.Title = "Home Page";
}

<main>
    <section class="row" aria-labelledby="aspnetTitle">
        <h1>ASP.NET</h1>
        <p>

            <a class="btn btn-primary btn-md" onclick="location.href='@Url.Action("PrintPdf", "Home")'">Print PDF</a>
        </p>
    </section>
</main>
@{
    ViewBag.Title = "Home Page";
}

<main>
    <section class="row" aria-labelledby="aspnetTitle">
        <h1>ASP.NET</h1>
        <p>

            <a class="btn btn-primary btn-md" onclick="location.href='@Url.Action("PrintPdf", "Home")'">Print PDF</a>
        </p>
    </section>
</main>
HTML

ASP.NET應用程式介面,顯示導覽選單和藍色的Print PDF按鈕,用於產生PDF


如何在控制器中配置 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 Namespace
$vbLabelText   $csharpLabel

針對進階方案,實施適當的 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 Namespace
$vbLabelText   $csharpLabel

此增強實作展示 Print Settings 指南中的概念,包括指定印表機名稱、設定紙張大小以及適當處理錯誤。

在網頁環境中進行印表機選擇時,請利用 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
$vbLabelText   $csharpLabel

對於需要使用者互動的場景,可考慮採用 Print with Dialog 的方式,不過這種方式比起網頁環境更適合桌面應用程式。

生產部署的其他注意事項

在使用 IronPrint 部署您的 ASP.NET 應用程式時,請考慮這些因素:

1.授權組態:對於 ASP.NET 應用程式,請在 Web.config 中設定您的授權金鑰。請參閱 Setting License Key in Web.config 指南以取得正確的設定。

2.印表機存取權限:確保應用程式池身分具有存取本機或網路印表機的權限。 Print Your Documents 文件提供了印表機存取要求。

3.錯誤處理:針對離線印表機或無法存取的文件實施強大的錯誤處理。 對於技術問題,請使用 Engineering Request 流程來解決複雜的問題。

4.效能:針對大量列印,實施佇列系統以有效管理列印請求。 異步的 PrintAsync 是這類實作的理想選擇。

如需全面的列印功能,請參閱 API Reference 以取得 IronPrint 命名空間中所有方法和屬性的詳細說明文件。

常見問題解答

如何在 ASP.NET Framework 應用程式中實作異步 PDF 列印?

您可以使用 IronPrint 的 PrintAsync 方法實現異步 PDF 列印。只需在您的控制器動作中加入 `return await IronPrint.Printer.PrintAsync("yourfile.pdf");` 即可。這種非阻塞方法可確保您的 Web 應用程式在處理列印請求時保持反應迅速,避免在進行文件列印作業時發生使用者介面凍結的情況。

為什麼在 Web 應用程式中應該使用異步列印而非同步列印?

使用 IronPrint 的 PrintAsync 方法進行異步列印,對於可能有多位使用者同時觸發列印作業的 Web 應用程式而言至關重要。與阻塞線程的同步列印方法不同,PrintAsync 可確保您的應用程式在處理並發請求時不會降低性能,即使在高負載下也能保持反應速度。

在我的 ASP.NET Framework 專案中加入 PDF 列印的最基本步驟是什麼?

最基本的工作流程包括 5 個步驟:1) 下載適用於 C# 的 IronPrint 函式庫;2) 將 IronPrint 匯入您的 class 檔案;3) 在您的檢視中加入列印按鈕;4) 在您的控制器動作中實作 PrintAsync;5) 按下按鈕時確認文件列印工作正常。這個簡化的流程只需最少的程式碼變更。

如何在 ASP.NET 視圖中加入列印按鈕?

在您的 Index.cshtml 或首頁檢視中,新增一個可觸發控制器動作的按鈕。使用類似 `` 的 HTML。按一下此按鈕時,會在您的 Home 控制器中呼叫 PrintPDF ActionResult 方法。

使用非同步列印時,我可以自訂列印設定嗎?

是的,IronPrint 提供全面的功能,包括自訂列印設定和印表機資訊擷取。這些功能使其成為需要強大列印功能的企業級 ASP.NET 應用程式的理想選擇,並可設定印表機選擇、頁面方向、邊界及其他列印參數。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 37,046 | 版本: 2026.2 剛剛發布