跳至页脚内容
使用IRONPDF

如何在ASP.NET中创建报告

报告对于以结构化和视觉吸引力的格式呈现数据至关重要。 无论是销售数据、分析还是财务摘要,生成报告都是Web应用程序中的常见需求。 Microsoft 提供 RDLC 报告服务,可以使用 Web Forms Report Viewer 控件集成到 Web 应用程序中。 然而,这个过程通常很复杂且耗时。

这就是 IronPDF 的用武之地。 IronPDF 是一个多功能库,通过提供强大的功能和易用性简化了在 ASP.NET 和其他 Web 框架中生成 PDF 报告的过程。 在本文中,我们将探讨如何使用 IronPDF 在 ASP.NET 中创建报告。

如何在 ASP.NET 中创建报告

  1. 使用 Visual Studio 创建一个 ASP.NET Web 应用程序
  2. 安装 IronPDFIronPDF.Extensions.MVC.Core
  3. 实例化 ChromePdfRenderer 对象发送方
  4. 调用 RenderRazorViewToPdf 方法将视图转换为 PDF
  5. 使用 Response.Headers.Append 添加 "Content-Disposition"
  6. 使用 File 方法和 PDF.BinaryData 创建报告

IronPDF简介

IronPDF 是一个多功能库,通过简化在 ASP.NET 和其他 Web 框架中生成 PDF 文档的过程。 其丰富的功能集和直观的 API 使其成为希望从 Web 应用程序直接生成动态报告、发票、收据等的开发人员的理想选择。 借助 IronPDF,开发人员可以轻松地将 HTML、CSS 甚至 Razor 视图转换为高质量的 PDF 文档,从而使报告功能无缝集成到他们的 ASP.NET 项目中。

IronPDF的功能

  • HTML 到 PDF 转换:轻松将 HTML 内容(包括 CSS 样式)转换为高质量的 PDF 文档。
  • PDF 编辑:通过添加或删除文本、图像和注释来修改现有的 PDF 文档。
  • PDF 表单填写:使用来自 Web 应用程序的数据动态填充 PDF 表单。
  • 条形码生成:在 PDF 文档中生成条形码和 QR 码,用于产品标签或库存跟踪。
  • 水印:向 PDF 页面添加水印以保护敏感信息或品牌文档。
  • 加密与安全:使用加密、密码和权限设置来保护 PDF 文档。

前提条件

在开始之前,请确保您具备以下先决条件:

  • ASP.NET 开发的基本知识。
  • 计算机上已安装 Visual Studio
  • IronPDF 和 IronPDF.Extensions.Mvc.Core

在 Visual Studio 中创建 ASP.NET 项目的步骤

  1. 打开 Visual Studio 并创建一个新的 ASP.NET Core 项目。
  2. 选择所需的项目模板(例如,MVC 或 Razor Pages)。

如何在 ASP.NET 中创建报告:图 1

  1. 配置项目设置,例如项目名称、位置和框架版本。

如何在 ASP.NET 中创建报告:图 2

  1. 单击“创建”以生成项目结构。

安装 IronPDF 和 IronPDF.Extensions.Mvc.Core

接下来,让我们使用 NuGet 包管理器安装 IronPDF 及其 MVC 扩展包:

  1. 通过右键单击解决方案资源管理器打开解决方案的 NuGet 包管理器。
  2. 搜索“IronPDF”和“IronPDF.Extensions.Mvc.Core”。

如何在 ASP.NET 中创建报告:图 3

  1. 将这两个包安装到您的解决方案中。

在 ASP.NET Web 应用程序中创建 Report Viewer 的步骤

现在,让我们深入探讨使用 IronPDF 在我们的 ASP.NET 项目中创建 PDF 报告的步骤。 在将视图转换为报告之前,我们需要一个模型、视图和控制器来创建数据源以创建和下载新的 PDF 格式报告。

第 1 步:定义模型类

首先,创建一个模型类(SalesModel.cs)来表示销售数据。 此示例 SalesModel 类将包括日期、产品名称、数量、单价和总金额等属性。 当从 Microsoft SQL Server 或 MySQL Server 等数据源检索信息时,这非常有用。

namespace ReportGenerator.Models
{
    public class SalesModel
    {
        public DateTime Date { get; set; }
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal TotalAmount => Quantity * UnitPrice;
    }
}
namespace ReportGenerator.Models
{
    public class SalesModel
    {
        public DateTime Date { get; set; }
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal TotalAmount => Quantity * UnitPrice;
    }
}
Namespace ReportGenerator.Models
	Public Class SalesModel
		Public Property [Date]() As DateTime
		Public Property ProductName() As String
		Public Property Quantity() As Integer
		Public Property UnitPrice() As Decimal
		Public ReadOnly Property TotalAmount() As Decimal
			Get
				Return Quantity * UnitPrice
			End Get
		End Property
	End Class
End Namespace
$vbLabelText   $csharpLabel

第 2 步:创建新的 Web 窗体视图

接下来,创建一个 Razor 视图(Sales.cshtml)以表格格式显示销售数据,并提供一个按钮以生成 PDF 报告。

<!-- Sales.cshtml -->
@model List<SalesModel>
<!DOCTYPE html>
<html>
<head>
    <title>Sales Report</title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }
        th {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>
    <h2>Sales Report</h2>
    <table>
        <tr>
            <th>Date</th>
            <th>Product Name</th>
            <th>Quantity</th>
            <th>Unit Price</th>
            <th>Total Amount</th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Date.ToShortDateString()</td>
                <td>@item.ProductName</td>
                <td>@item.Quantity</td>
                <td>@item.UnitPrice.ToString("C")</td>
                <td>@item.TotalAmount.ToString("C")</td>
            </tr>
        }
    </table>
    <br />
    @using (Html.BeginForm("GeneratePdf", "Sales", FormMethod.Post))
    {
        <button type="submit">Generate PDF Report</button>
    }
</body>
</html>
<!-- Sales.cshtml -->
@model List<SalesModel>
<!DOCTYPE html>
<html>
<head>
    <title>Sales Report</title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }
        th {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>
    <h2>Sales Report</h2>
    <table>
        <tr>
            <th>Date</th>
            <th>Product Name</th>
            <th>Quantity</th>
            <th>Unit Price</th>
            <th>Total Amount</th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Date.ToShortDateString()</td>
                <td>@item.ProductName</td>
                <td>@item.Quantity</td>
                <td>@item.UnitPrice.ToString("C")</td>
                <td>@item.TotalAmount.ToString("C")</td>
            </tr>
        }
    </table>
    <br />
    @using (Html.BeginForm("GeneratePdf", "Sales", FormMethod.Post))
    {
        <button type="submit">Generate PDF Report</button>
    }
</body>
</html>
HTML

现在,在 Views->Shared 文件夹中的 _Layout.cshtml 文件中将销售项作为菜单项添加,以创建报告向导视图:

<!— Layout.cshtml —>
<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Sales" asp-action="Sales">Sales</a>
</li>
<!— Layout.cshtml —>
<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Sales" asp-action="Sales">Sales</a>
</li>
HTML

如何在 ASP.NET 中创建报告:图 4

第 3 步:注册视图渲染服务

Program.cs 文件中包括视图渲染服务的注册对于依赖项注入正常工作至关重要。 将以下代码添加到 Program.cs 文件以注册 IRazorViewRenderer 服务:

// Register the IRazorViewRenderer service
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
// Register the IRazorViewRenderer service
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
' Register the IRazorViewRenderer service
builder.Services.AddSingleton(Of IRazorViewRenderer, RazorViewRenderer)()
$vbLabelText   $csharpLabel

第 4 步:实施 Web API 控制器类

实现一个控制器(SalesController.cs),带有渲染销售视图和生成 PDF 报告的操作。 在控制器构造函数中注入 IronPDF 提供的 IRazorViewRenderer 服务。

using ReportGenerator.Models;
namespace ReportGenerator.Controllers
{
    public class SalesController : Controller
    {
        private readonly IRazorViewRenderer _viewRenderService;
        private readonly List<SalesModel> salesData;

        public SalesController(IRazorViewRenderer viewRenderService)
        {
            _viewRenderService = viewRenderService;
            // Example data with sales information
            salesData = new List<SalesModel>
            {
                new SalesModel { Date = DateTime.Parse("2024-03-01"), ProductName = "Product A", Quantity = 10, UnitPrice = 50.00m },
                new SalesModel { Date = DateTime.Parse("2024-03-02"), ProductName = "Product B", Quantity = 15, UnitPrice = 40.00m },
                new SalesModel { Date = DateTime.Parse("2024-03-03"), ProductName = "Product C", Quantity = 20, UnitPrice = 30.00m }
                // Add more data as needed
            };
        }

        public IActionResult Sales()
        {
            // Renders the sales view with the sales data
            return View(salesData);
        }
    }
}
using ReportGenerator.Models;
namespace ReportGenerator.Controllers
{
    public class SalesController : Controller
    {
        private readonly IRazorViewRenderer _viewRenderService;
        private readonly List<SalesModel> salesData;

        public SalesController(IRazorViewRenderer viewRenderService)
        {
            _viewRenderService = viewRenderService;
            // Example data with sales information
            salesData = new List<SalesModel>
            {
                new SalesModel { Date = DateTime.Parse("2024-03-01"), ProductName = "Product A", Quantity = 10, UnitPrice = 50.00m },
                new SalesModel { Date = DateTime.Parse("2024-03-02"), ProductName = "Product B", Quantity = 15, UnitPrice = 40.00m },
                new SalesModel { Date = DateTime.Parse("2024-03-03"), ProductName = "Product C", Quantity = 20, UnitPrice = 30.00m }
                // Add more data as needed
            };
        }

        public IActionResult Sales()
        {
            // Renders the sales view with the sales data
            return View(salesData);
        }
    }
}
Imports ReportGenerator.Models
Namespace ReportGenerator.Controllers
	Public Class SalesController
		Inherits Controller

		Private ReadOnly _viewRenderService As IRazorViewRenderer
		Private ReadOnly salesData As List(Of SalesModel)

		Public Sub New(ByVal viewRenderService As IRazorViewRenderer)
			_viewRenderService = viewRenderService
			' Example data with sales information
			salesData = New List(Of SalesModel) From {
				New SalesModel With {
					.Date = DateTime.Parse("2024-03-01"),
					.ProductName = "Product A",
					.Quantity = 10,
					.UnitPrice = 50.00D
				},
				New SalesModel With {
					.Date = DateTime.Parse("2024-03-02"),
					.ProductName = "Product B",
					.Quantity = 15,
					.UnitPrice = 40.00D
				},
				New SalesModel With {
					.Date = DateTime.Parse("2024-03-03"),
					.ProductName = "Product C",
					.Quantity = 20,
					.UnitPrice = 30.00D
				}
			}
		End Sub

		Public Function Sales() As IActionResult
			' Renders the sales view with the sales data
			Return View(salesData)
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

在上述代码中,在构造函数内,IRazorViewRenderer 服务被分配给私有字段 _viewRenderService。 此外,控制器还会初始化名为 salesData 的列表,其中包含 SalesModel 类的实例,用于演示销售信息。

The Sales() action 方法返回一个名为“Sales”的视图,并将 salesData 列表作为模型传递。 此动作负责将销售数据显示在关联视图中,允许用户以表格格式或任何其他所需布局来可视化销售信息。

如何在 ASP.NET 中创建报告:图 5

第 5 步:生成 PDF 报告

在控制器的 GeneratePdf 动作中,使用 IronPDF 的 ChromePdfRendererRazor 视图渲染为 PDF 报告文档。 设置适当的响应头并将 PDF 文件返回给客户端。

public FileContentResult GeneratePdf()
{
    // Set license key for IronPDF
    License.LicenseKey = "YOUR-LICENSE-KEY-HERE";

    // Initialize the ChromePdfRenderer
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the Sales Razor view to a PDF document
    PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData);

    // Set HTTP response header to display the PDF inline
    Response.Headers.Append("Content-Disposition", "inline");

    // Return the PDF document as a FileContentResult
    return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf");
}
public FileContentResult GeneratePdf()
{
    // Set license key for IronPDF
    License.LicenseKey = "YOUR-LICENSE-KEY-HERE";

    // Initialize the ChromePdfRenderer
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the Sales Razor view to a PDF document
    PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData);

    // Set HTTP response header to display the PDF inline
    Response.Headers.Append("Content-Disposition", "inline");

    // Return the PDF document as a FileContentResult
    return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf");
}
Public Function GeneratePdf() As FileContentResult
	' Set license key for IronPDF
	License.LicenseKey = "YOUR-LICENSE-KEY-HERE"

	' Initialize the ChromePdfRenderer
	Dim renderer As New ChromePdfRenderer()

	' Render the Sales Razor view to a PDF document
	Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData)

	' Set HTTP response header to display the PDF inline
	Response.Headers.Append("Content-Disposition", "inline")

	' Return the PDF document as a FileContentResult
	Return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf")
End Function
$vbLabelText   $csharpLabel

让我们详细了解上述代码的工作原理:

  1. 许可证密钥设置:
    • License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
    • 这行代码设置了 IronPDF 所需的许可证密钥。 它对于在应用程序中使用 IronPDF 功能至关重要。
  2. 渲染器初始化:
    • ChromePdfRenderer renderer = new ChromePdfRenderer();
    • 创建了一个 ChromePdfRenderer 实例。 此渲染器负责使用 Chromium 浏览器引擎将 Razor 视图转换为 PDF 格式。
  3. 将视图渲染为 PDF:
    • PdfDocument PDF = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData);
    • ChromePdfRendererRenderRazorViewToPdf() 方法被调用以将指定的 Razor 视图(Views/Sales/Sales.cshtml)渲染为 PDF 文档。 变量 salesData 作为视图的模型。
  4. Content-Disposition Header:
    • Response.Headers.Append("Content-Disposition", "inline");
    • HTTP 响应头 Content-Disposition 设置为 "inline"。 这会指示浏览器直接显示 PDF 内容,以便在打开时可以在浏览器窗口或选项卡中查看报告。
  5. 返回 PDF 文件:
    • return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf");
    • PDF 文档内容以 FileContentResult 的形式返回。 它包括 PDF 的二进制数据(pdf.BinaryData),指定 MIME 类型为 "application/pdf",并建议文件名为 "SalesReport.pdf"

总之,这种方法有效地协调了从 Razor 视图生成 PDF 报告的过程,使其适合在 ASP.NET 应用程序中集成,以增强报告能力。

如何在 ASP.NET 中创建报告:图 6

有关 IronPDF 如何简化 PDF 报告生成过程和其他 PDF 相关任务的详细信息,请访问文档页面。

结论

在本文中,我们探讨了 IronPDF 如何简化在 ASP.NET 应用程序中生成 PDF 报告的过程。 通过遵循上面提供的分步指南,你可以快速将 IronPDF 集成到你的 ASP.NET 项目中,并轻松生成动态 PDF 报告。

凭借其丰富的功能集和无缝集成,IronPDF 使开发人员能够创建符合用户和企业需求的专业质量报告。

IronPDF 提供免费试用。 从这里下载库并试用。

常见问题解答

我如何在 ASP.NET 中生成 PDF 报告?

您可以使用 IronPDF 在 ASP.NET 中生成 PDF 报告。首先在 Visual Studio 中设置一个 ASP.NET Web 应用程序,然后安装 IronPDF 及其 MVC 扩展。使用ChromePdfRenderer类将 Razor 视图转换为 PDF,并利用File方法创建报告。

使用 PDF 库对 ASP.NET 有什么好处?

使用像 IronPDF 这样的 PDF 库来简化 ASP.NET 中生成和管理 PDF 报告的过程。它支持 HTML 转为 PDF、PDF 编辑、表单填充、条码生成和文档安全,使其在各种 Web 应用程序需求中非常通用。

我如何在 ASP.NET 中将 Razor 视图转换为 PDF?

要在 ASP.NET 中将 Razor 视图转换为 PDF,您可以使用 IronPDF 的ChromePdfRenderer.RenderRazorViewToPdf方法。这使您能够在 ASP.NET 应用程序中无缝集成 PDF 生成功能。

IronPDF 在 PDF 报告生成方面提供了哪些功能?

IronPDF 提供了诸如 HTML 转为 PDF、PDF 编辑、表单填充、条码生成、加水印和文档加密和安全等功能。这些特性可促进创建动态和安全的 PDF 报告。

我如何在 ASP.NET 中保护 PDF 文档?

IronPDF 提供加密和安全功能,让开发人员能够通过加密、密码和权限设置来保护 PDF 文档。这可确保您的 ASP.NET 应用程序中的敏感信息保持安全。

IronPDF有免费试用版吗?

是的,IronPDF 提供免费试用。您可以从 IronPDF 网站下载该库,并探索其在您的应用程序中生成专业质量 PDF 报告的功能。

我如何在 ASP.NET 应用程序中向 PDF 添加水印?

您可以使用 IronPDF 在 ASP.NET 应用程序中向 PDF 添加水印。该库提供 API 用于在 PDF 文档上覆盖水印,允许您有效地保护敏感信息或标记您的文档。

在我的 ASP.NET 项目中使用 IronPDF 有哪些先决条件?

在使用 IronPDF 之前,请确保您对 ASP.NET 开发有基本了解并已安装 Visual Studio。此外,您需要在项目中安装 IronPDF 及其 MVC 扩展,以便利用其功能。

我在哪里可以找到有关 IronPDF 的更多信息?

有关 IronPDF 及其能力的更多详细信息,您可以访问 IronPDF 网站上的文档页面。文档提供了设置信息、功能和示例代码。

IronPDF 是否兼容 .NET 10?如果兼容,它能带来哪些优势?

是的,IronPDF 完全支持 .NET 10,涵盖 Web、桌面和控制台项目类型。它充分利用了 .NET 10 运行时性能改进(例如减少堆分配和加快 JIT 编译速度)、C# 语言增强功能以及现代 API。开发人员可以在 .NET 10 应用程序中无缝使用RenderHtmlAsPdfRenderHtmlAsPdfAsync等方法,从而受益于更快的输出速度、跨平台部署和更简洁的代码。

Curtis Chau
技术作家

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

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