使用 IRONPDF

如何在ASP .NET中创建报告

Chipego
奇佩戈·卡林达
2024年4月3日
分享:

報告對於以結構化且視覺吸引的格式呈現數據至關重要。 無論是銷售數據、分析還是財務摘要,生成報告都是網絡應用程式中的常見需求。 Microsoft 提供可透過 Web Forms Report Viewer Control 整合到網頁應用程式中的 rdlc 報表服務。 然而,該過程通常可能是複雜且耗時的。

這就是 IronPDF 派上用場的地方。 IronPDF 是一個多功能的函式庫,簡化了在 ASP.NET 和其他網頁框架中生成 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 和其他網路框架中生成 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 網頁應用程式中建立報告檢視器的步驟

現在,讓我們深入了解在 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);

    • ChromePdfRenderer 中調用 RenderRazorViewToPdf() 方法將指定的 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 提供 免費試用版。 從這裡下載庫並試用。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
如何在 C# 中建立報告應用程式
下一個 >
如何解析 PDF 文件中的資料