使用IRONPDF

如何在ASP .NET中创建报告

Chipego
奇佩戈-卡琳达
2024年四月3日
分享:

报告对于以结构化和视觉吸引力的格式呈现数据至关重要。 无论是销售数据、分析还是财务摘要,生成报告都是网页应用中的常见需求。 Microsoft 提供 rdlc 报告服务,可以使用 Web Forms 报表查看器控件集成到 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对象 sender

  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 表单填写:使用来自您的网络应用程序的数据动态填写 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

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

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

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

安装 IronPDF 和 IronPDF.Extensions.Mvc.Core

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

  1. 通过右键单击解决方案资源管理器,打开NuGet包管理器。

  2. 搜索“IronPDF”和“IronPDF.Extensions.Mvc.Core”。

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

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

在 ASP.NET Web 应用程序中创建报告查看器的步骤

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

步骤 1:定义一个模型类

首先,创建一个模型类(SalesModel.cs)来表示销售数据。 此示例 SalesModel 类将包含 Date、ProductName、Quantity、UnitPrice 和 TotalAmount 等属性。 这在从数据源(如 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 报告。

<!-- Index.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>
<!-- Index.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 文件中添加销售作为菜单项,以创建报告向导视图:

<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Sales" asp-action="Sales">Sales</a>
</li>
XML

如何在 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

步骤 3:实现 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 data in Sales view
            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 data in Sales view
            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 data in Sales view
			Return View(salesData)
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

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

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

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

步骤 4:生成 PDF 报告

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

public FileContentResult GeneratePdf()
{
    License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
    ChromePdfRenderer renderer = new ChromePdfRenderer();
    // Render View to PDF document
    PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData);
    Response.Headers.Append("Content-Disposition", "inline");
    // Output PDF document
    return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf");
}
public FileContentResult GeneratePdf()
{
    License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
    ChromePdfRenderer renderer = new ChromePdfRenderer();
    // Render View to PDF document
    PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData);
    Response.Headers.Append("Content-Disposition", "inline");
    // Output PDF document
    return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf");
}
Public Function GeneratePdf() As FileContentResult
	License.LicenseKey = "YOUR-LICENSE-KEY-HERE"
	Dim renderer As New ChromePdfRenderer()
	' Render View to PDF document
	Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData)
	Response.Headers.Append("Content-Disposition", "inline")
	' Output PDF document
	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 标头:

    • 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 提供免费试用。 从这里下载库并试用。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
如何在C#中创建报表应用程序
下一步 >
如何从PDF文档解析数据