使用 C# 在 ASP.NET Framework 網頁應用程式中進行列印

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

IronPrint 的 PrintAsync 方法可在 ASP.NET 網頁應用程式中實現非阻塞式文件列印,避免在處理列印請求時導致使用者介面凍結。 這種非同步方法確保響應式網頁應用程式能夠在不阻塞執行緒的情況下處理PRINT操作。

網頁應用程式通常需要將文件列印作為最終輸出。 將PRINT功能整合至網頁應用程式會面臨諸多挑戰,特別是在處理非同步操作時。 IronPrint 透過 PrintAsync 函式來解決此問題。 本教學將示範如何使用 .NET Core 實作 PrintAsync,以建立一個在不阻塞的情況下列印文件的網頁應用程式。

在實作前,請注意 IronPrint 提供全面的功能,包括印表機資訊擷取自訂列印設定。 這些功能使其成為需要強大列印功能之 Enterprise 級 ASP.NET 應用程式的理想選擇。

快速入門:ASP.NET 中的非同步 PDF 列印

  1. 透過 NuGet 安裝 IronPrint:Install-Package IronPrint
  2. IronPrint 匯入控制器檔案
  3. 新增一個PRINT按鈕以觸發該方法
  4. 在控制器動作中呼叫 await Printer.PrintAsync("file.pdf")
  5. 驗證按下按鈕時的文件列印功能
  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronPrint

    PM > Install-Package IronPrint
  2. 請複製並執行此程式碼片段。

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

    立即透過免費試用,在您的專案中開始使用 IronPrint

    arrow pointer

開始使用 IronPrint

立即透過免費試用,在您的專案中開始使用 IronPrint。

第一步:
green arrow pointer


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

此範例展示如何在 ASP.NET Web Application (.NET Framework) 專案中,使用 PrintAsync 方法以非同步方式印製 PDF 檔案。 PrintAsync 會以非同步方式啟動列印,相較於會阻塞執行緒的同步 Print 方法,能讓應用程式保持響應性。

在可能有多名使用者同時觸發PRINT操作的網頁應用程式中,異步處理方式至關重要。 與同步的 Print 方法不同,PrintAsync 可確保您的應用程式在不影響效能的情況下處理並發請求。

我應該在哪裡添加PRINT按鈕?

在您的"Index.cshtml"(或首頁檢視)中,新增一個按鈕,點擊時會觸發特定動作。 此按鈕會呼叫您控制器中的 ActionResult 方法:

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

<main>
    <section class="row" aria-labelledby="aspnetTitle">
        <h1 id="title">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 id="title">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

顯示導覽選單及藍色


如何在控制器中設定 PrintAsync?

在您的 HomeController 中,實作 PrintAsync 方法。 此方法以非同步方式執行PRINT操作,從而提升應用程式的反應速度。 在實作前,請確保已正確設定授權金鑰以供生產環境使用。

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 模式,並自訂 PRINT 操作。 以下是一個經過優化的範例,展示錯誤處理與自訂PRINT設定:

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設定》指南中的概念,包括指定印表機名稱、設定紙張尺寸,以及妥善處理錯誤。

在網頁環境中處理印表機選取時,請利用"取得印表機名稱"功能,以動態方式填入可用的印表機清單:

// 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"的方式,不過此方法較適合桌面應用程式,而非網頁環境。

生產環境部署的額外考量

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

  1. 授權設定:對於 ASP.NET 應用程式,請在 Web.config 中設定您的授權金鑰。請參閱《在 Web.config 中設定授權金鑰》指南以進行正確設定。

  2. 印表機存取權限:請確保應用程式池的識別身分具備存取本地或網路印表機的權限。 《Print Your Documents》文件中提供了印表機存取需求。

  3. 錯誤處理:針對離線印表機或無法存取的文件,實作穩健的錯誤處理機制。 若遇技術問題,請透過工程請求流程解決複雜問題。

  4. 效能:針對大量列印需求,應實作佇列系統以有效率地管理列印請求。 異步的 PrintAsync 非常適合此類實作。

如需全面的 PRINT 功能,請參閱 API 參考文件,其中詳載 IronPrint 命名空間內所有方法與屬性的詳細說明。

常見問題

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

您可以透過 IronPrint 的 PrintAsync 方法實作非同步 PDF 列印。只需在控制器動作中加入 `return await IronPrint.Printer.PrintAsync("yourfile.pdf");`。這種非阻塞式方法可確保您的網頁應用程式在處理列印請求時仍能保持響應,避免在文件列印操作期間發生使用者介面凍結的情況。

為何在網頁應用程式中應使用非同步列印而非同步列印?

對於可能有多名使用者同時觸發列印操作的網頁應用程式而言,IronPrint 的 PrintAsync 方法所提供的非同步列印功能至關重要。與會阻塞執行緒的同步 PRINT 方法不同,PrintAsync 可確保您的應用程式在不影響效能的情況下處理並發請求,即使在高負載下也能維持系統的回應能力。

要在我的 ASP.NET Framework 專案中新增 PDF 列印功能,最少需要哪些步驟?

最簡化的工作流程包含 5 個步驟:1) 下載適用於 C# 的 IronPrint程式庫,2) 將 IronPrint 匯入您的類別檔案,3) 在檢視中新增一個列印按鈕,4) 在控制器動作中實作 PrintAsync 方法,以及 5) 確認按下按鈕時文件列印功能正常運作。此簡化流程僅需最少的程式碼變更。

如何在我的 ASP.NET 檢視中新增 PRINT 按鈕?

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

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

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

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
Nuget 下載 41,154 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronPrint
執行範例程式,親眼見證您的文件送印。