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

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

IronPrint的PrintAsync方法啟用非阻塞文件列印於ASP.NET Web應用程式中,防止在處理列印請求時出現UI凍結。 這種非同步方法確保響應迅速的Web應用程式可以在不阻塞執行緒的情況下處理列印操作。

Web應用程式經常需要文件列印作為最終輸出。 將列印功能整合到Web應用程式中面臨挑戰,尤其是在處理非同步操作時。 IronPrint用PrintAsync函式解決了這個問題。 本教程演示如何使用ASP.NET Core實現PrintAsync,以建立一個不阻塞的文件列印Web應用程式。

在實施之前,請注意IronPrint提供了全面的功能,包括列印機資訊檢索自訂列印設置。 這些功能使其成為需要強大列印功能的企業ASP.NET應用程式的理想選擇。

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

  1. 通過NuGet安裝IronPrint:Install-Package IronPrint
  2. IronPrint匯入控制器檔案
  3. 新增列印按鈕以觸發該方法
  4. 在控制器操作中調用await Printer.PrintAsync("file.pdf")
  5. 確認按鈕按下時進行文件列印
  1. 使用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列印?

此範例展示了使用PrintAsync方法在ASP.NET Web應用程式(.NET Framework)專案中非同步列印PDF文件。 Print方法相比。

在多個使用者可能同時觸發列印操作的Web應用程式中,非同步方法至關重要。 與同步PrintAsync確保您的應用程式可以處理並發請求而不會降低效能。

我應該將列印按鈕放在哪裡?

在您的"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

ASP.NET應用程式介面顯示導航選單和供生成PDF的藍色列印PDF按鈕


我該如何在我的控制器中配置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 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

此增強實現展示了列印設置指南中的概念,包括指定列印機名稱、配置紙張尺寸和適當處理錯誤。

在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
$vbLabelText   $csharpLabel

對於需要使用者互動的情況,考慮實施帶對話框的列印方法,雖然這更適合桌面應用程式而非Web環境。

生產部署的其他考量

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

  1. 授權配置:對於ASP.NET應用程式,請在Web.config中配置您的授權金鑰。請參閱在Web.config中設置授權金鑰指南以進行適當設置。

  2. 列印機存取:確保應用程式池的身份具有存取本地或網路列印機的權限。 列印您的文件文件提供了列印機存取要求。

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

  4. 性能:對於高容量列印,實施隊列系統以有效管理列印請求。 非同步PrintAsync對於此類實現非常理想。

有關全面的列印功能,請查閱API引用以獲取IronPrint命名空間中所有方法和屬性的詳細說明。

常見問題

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

您可以使用IronPrint的PrintAsync方法實現非同步PDF列印。只需在您的控制器操作中新增`return await IronPrint.Printer.PrintAsync("yourfile.pdf");`。這種非阻塞的方法確保您的Web應用程式在處理列印請求時保持響應,防止UI在文件列印操作中凍結。

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

使用IronPrint的PrintAsync方法進行非同步列印,對於多個使用者可能同時觸發列印操作的Web應用程式非常重要。與阻塞執行緒的同步Print方法不同,PrintAsync確保在不降低性能的情況下處理並發請求,即使在高負載下也能保持響應性。

將PDF列印新增到我的ASP.NET Framework專案的最小步驟是什麼?

最小工作流程包括5個步驟:1)下載用於C#的IronPrint程式庫,2)將IronPrint導入類別檔案,3)在視圖中新增列印按鈕,4)在控制器操作中實現PrintAsync,5)確認在按下按鈕時文件列印正常工作。這個精簡的過程需要的程式碼改變最少。

如何在我的ASP.NET視圖中新增列印按鈕?

在您的Index.cshtml或首頁視圖中,新增一個觸發控制器操作的按鈕。使用如``的HTML。此按鈕將在點擊時調用您的Home控制器中的PrintPDF ActionResult方法。

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

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

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備好開始了嗎?
Nuget 下載 44,051 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

仍在滾動?

想要快速證明嗎? PM > Install-Package IronPrint
運行範例 看看您的文件如何到達印表機。