使用 IRONPDF

如何在ASP .NET中创建报告

發佈 2024年4月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 物件發送者

  4. 調用 RenderRazorViewToPdf 方法將視圖轉換為PDF

  5. 使用 Response.Headers.Append 添加 "Content-Disposition"

  6. 使用 PDF.BinaryDataFile 方法創建報告

IronPDF 介紹

IronPDF 是一個多功能的庫,簡化了在ASP.NET和其他網絡框架中生成PDF文檔的過程。其豐富的特性集和直觀的API使其成為開發人員在網絡應用程序中直接生成動態報告、發票、收據等的理想選擇。使用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. 點擊 "Create" 以生成專案結構。

安裝 IronPDF 和 IronPDF.Extensions.Mvc.Core

接下來,讓我們使用 NuGet 套件管理器來安裝 IronPDF 及其 MVC 擴展包:

  1. 右鍵點擊方案總管,打開 NuGet 套件管理器。

  2. 搜尋 "IronPDF" 和 "IronPDF.Extensions.Mvc.Core"。

    如何在 ASP .NET 中創建報告:圖 3

  3. 將這兩個套件安裝到您的解決方案中。

在 ASP.NET 網頁應用程式中建立報表檢視器的步驟

現在,讓我們深入了解在 ASP.NET 專案中使用 IronPDF 創建 PDF 報表的步驟。在將視圖轉換為報表之前,我們需要一個模型 (Model)、視圖 (View) 和控制器 (Controller) 來創建資料來源,用於建立和下載新的 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
VB   C#

步驟 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 文件中添加「Sales」作為選單項目,以建立報表精靈檢視:

<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Sales" asp-action="Sales">Sales</a>
</li>
<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Sales" asp-action="Sales">Sales</a>
</li>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Sales" asp-action="Sales"> Sales</a> </li>
VB   C#

如何在 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)()
VB   C#

第三步:實現 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
VB   C#

在上面的代碼中,在構造函數裡,IRazorViewRenderer 服務被分配到私有字段 _viewRenderService。此外,控制器初始化了一個名為 salesData 的列表,列表中包含 SalesModel 類的實例,用於表示銷售信息以進行示範。() action 方法返回一個名為“Sales”的視圖,並將 salesData** 列表作為模型傳遞。此操作負責在相關視圖中呈現銷售數據,允許用戶以表格格式或任何其他所需的佈局來視覺化銷售信息。

如何在ASP .NET中創建報告:圖5

第4步:生成PDF報告

在控制器的 GeneratePdf 操作中,使用 IronPDF 的 ChromePdfRenderer 來渲染 Razor 視圖轉為 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
VB   C#

讓我們詳細了解上述代碼的工作原理:

  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);**

    • The RenderRazorViewToPdf()ChromePdfRenderer方法被調用來渲染指定的 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 提供 免費試用. 從下載庫文件 這裡 試試看。

< 上一頁
如何在 C# 中建立報告應用程式
下一個 >
如何解析 PDF 文件中的資料

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >