使用 C# 在 ASP.NET Framework Web 应用程序中进行打印

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

IronPrint 的 PrintAsync 方法可在 ASP.NET Web 应用程序中实现非阻塞文档打印,从而避免在处理打印请求时导致用户界面卡死。 这种异步方法可确保响应式网络应用程序能够在不阻塞线程的情况下处理打印操作。

网络应用程序通常需要将文档打印作为最终输出。 将打印功能与网络应用程序相集成是一项挑战,尤其是在处理异步操作时。 IronPrint 通过 PrintAsync 函数解决了这一问题。 本教程演示了如何使用 .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 打印?

此示例演示了如何在 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>

            <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 方法。 这种方法可以异步执行打印操作,提高应用程序的响应速度。 在实施之前,请确保许可证密钥配置正确,以便在生产中使用。

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

对于高级场景,应实施适当的异步/等待模式并自定义打印操作。 下面是一个增强示例,演示了错误处理和自定义打印设置:

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");
            }
        }
    }
}
$vbLabelText   $csharpLabel

该增强实施展示了打印设置指南中的概念,包括指定打印机名称、配置纸张大小和适当处理错误。

在网络环境中选择打印机时,可利用 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();
}
$vbLabelText   $csharpLabel

对于需要用户交互的场景,可以考虑采用 Print with Dialog 方法,不过这种方法更适合桌面应用程序而非网络环境。

生产部署的其他注意事项

在使用 IronPrint 部署 ASP.NET 应用程序时,请考虑以下因素:

1.许可配置:对于 ASP.NET 应用程序,请在 Web.config 中配置许可证密钥。有关正确设置,请参阅 Setting License Key in Web.config 指南。

2.打印机访问:确保应用程序池身份具有访问本地或网络打印机的权限。 Print Your Documents 文档提供了打印机访问要求。

3.错误处理:针对脱机打印机或无法访问的文档实施强大的错误处理功能。 对于技术问题,请使用工程请求流程来解决复杂问题。

4.性能:对于大批量打印,实施队列系统以高效管理打印请求。 异步 PrintAsync 非常适合此类实现。

有关全面的打印功能,请查阅 API 参考,了解 IronPrint 名称空间中所有方法和属性的详细文档。

常见问题解答

如何在 ASP.NET Framework 应用程序中实现异步 PDF 打印?

您可以使用 IronPrint 的 PrintAsync 方法实现异步 PDF 打印。只需在控制器操作中添加 `return await IronPrint.Printer.PrintAsync("yourfile.pdf");` 即可。这种非阻塞方法可确保您的网络应用程序在处理打印请求时保持响应,防止在文档打印操作过程中出现 UI 冻结。

为什么要在网络应用程序中使用异步打印而不是同步打印?

使用 IronPrint 的 PrintAsync 方法进行异步打印对于网络应用程序至关重要,因为在网络应用程序中,多个用户可能会同时触发打印操作。与阻塞线程的同步打印方法不同,PrintAsync 可确保您的应用程序在处理并发请求时不会降低性能,即使在高负载情况下也能保持响应速度。

在我的 ASP.NET Framework 项目中添加 PDF 打印的最基本步骤是什么?

最基本的工作流程包括 5 个步骤:1) 下载 C# 的 IronPrint 库;2) 将 IronPrint 导入类文件;3) 在视图中添加打印按钮;4) 在控制器动作中实施 PrintAsync;5) 按下按钮时验证文档打印是否正常。这一简化流程只需修改极少的代码。

如何在 ASP.NET 视图中添加打印按钮?

在 Index.cshtml 或主页视图中,添加一个触发控制器动作的按钮。使用类似于 `` 这样的 HTML。点击该按钮后,将调用 "主页 "控制器中的 PrintPDF ActionResult 方法。

使用异步打印时,能否自定义打印设置?

是的,IronPrint 提供了全面的功能,包括自定义打印设置和打印机信息检索。这些功能使其成为需要强大打印功能的企业级 ASP.NET 应用程序的理想选择,这些功能可配置打印机选择、页面方向、页边距和其他打印参数。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 38,454 | 版本: 2026.3 刚刚发布
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package IronPrint
运行示例 观看您的文档打到打印机上。