跳過到頁腳內容
使用IRONPDF

如何在ASP .NET中創建報告

報告對於以結構化和視覺吸引人的方式呈現數據至關重要。 無論是銷售資料、分析或財務摘要,產生報告都是 Web 應用程式中的常見需求。 微軟提供 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. 使用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 文件中產生條碼和二維碼,用於產品標籤或庫存追蹤。 浮水印**:在 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 報告。

<!-- 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類別的實例,用於表示銷售訊息,以作演示之用。

Sales()操作方法傳回一個名為"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 = "您的授權金鑰在此處";
  • 此行設定 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.內容處置標頭:
  • Response.Headers.Append("Content-Disposition", "inline");
  • HTTP 回應標頭Content-Disposition設定為"inline" 。 這將指示瀏覽器在開啟時直接顯示 PDF 內容,以便在瀏覽器視窗或標籤頁中查看報告。 5.返回 PDF 檔: *傳回 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 for .NET 在 ASP.NET 中生成 PDF 報告。首先在 Visual Studio 中建立 ASP.NET Web 應用程式,然後安裝 IronPDF for .NET 及其 MVC 延伸。使用 ChromePdfRenderer 類將 Razor 視圖轉換為 PDF,並利用 File 方法建立報表。

使用 ASP.NET 的 PDF 函式庫有什麼好處?

使用 IronPDF for ASP.NET 之類的 PDF 函式庫可簡化 PDF 報表的產生與管理過程。它支援 HTML 到 PDF 的轉換、PDF 編輯、表單填寫、Barcode 生成以及文件安全性,使其成為滿足各種 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 加入水印。該函式庫提供了在 PDF 文件上覆蓋水印的 API,讓您可以有效地保護敏感資訊或建立文件品牌。

在 ASP.NET 專案中使用 IronPDF 有哪些先決條件?

在使用 IronPDF 之前,請確保您對 ASP.NET 開發有基本的瞭解,並已安裝 Visual Studio。此外,您需要在專案中安裝 IronPDF 及其 MVC 延伸功能,才能使用其功能。

在哪裡可以找到有關 IronPDF 的更多資訊?

有關 IronPDF 及其功能的詳細資訊,您可以造訪 IronPDF 網站的說明文件頁面。該文件提供了對設置、功能和示例代碼的深入瞭解。

IronPDF 是否與 .NET 10 相容,它有哪些優點?

是的,IronPDF 在 Web、桌面和控制台專案類型中完全支援 .NET 10。它充分利用了 .NET 10 運行時的性能改進(如減少堆分配和更快的 JIT)、C# 語言增強和現代 API。開發人員可在 .NET 10 應用程式中無縫使用 RenderHtmlAsPdfRenderHtmlAsPdfAsync 等方法,從輸出速度、跨平台部署和更乾淨的程式碼中獲益。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。