跳過到頁腳內容
使用IRONPDF

如何在ASP .NET中創建報告

報告在以結構化且具有視覺吸引力的格式呈現資料時是必不可少的。 無論是銷售數據、分析還是財務摘要,生成報告都是網絡應用程序中的常見要求。 Microsoft 提供 RDLC 報告服務,可以通過 Web Forms 報告查看器控件集成到網絡應用程序中。 然而,這個過程經常是複雜且耗時的。

這就是 IronPDF 發揮作用的地方。 IronPDF 是一個多功能的庫,它簡化了在 ASP.NET 和其他網絡框架中生成 PDF 報告的過程,提供強大的功能和易用性。 在本文中,我們將探討如何使用 IronPDF 在 ASP.NET 中創建報告。

如何在 ASP.NET 中創建報告

  1. 使用 Visual Studio 創建 ASP.NET 網絡應用程序
  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 轉換:輕鬆將包含 CSS 樣式的 HTML 內容轉換為高質量的 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 頁面)。

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

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

在 ASP.NET 網絡應用程序中創建報告查看器的步驟

現在,我們深入了解如何在 ASP.NET 項目中使用 IronPDF 創建 PDF報告的步驟。 在將視圖轉換為報告之前,我們需要一個模型(View)、視圖(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
$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 = "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. 內容處置標頭:
    • 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 for ASP.NET 等 PDF 函式庫可以簡化 PDF 報告的產生和管理流程。它支援 HTML 轉 PDF、PDF 編輯、表單填寫、條碼產生和文件安全性等功能,使其能夠靈活滿足各種 Web 應用程式的需求。

如何在 ASP.NET 中將 Razor 視圖轉換為 PDF?

若要在 ASP.NET 中將 Razor 視圖轉換為 PDF,可以使用 IronPDF 的ChromePdfRenderer.RenderRazorViewToPdf方法。這樣,您就可以將 PDF 生成功能無縫整合到 ASP.NET 應用程式中。

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 完全支援 .NET 10,涵蓋 Web、桌面和控制台專案類型。它充分利用了 .NET 10 運行時效能改進(例如減少堆分配和加快 JIT 編譯速度)、C# 語言增強功能以及現代 API。開發人員可以在 .NET 10 應用程式中無縫使用RenderHtmlAsPdfRenderHtmlAsPdfAsync等方法,從而受益於更快的輸出速度、跨平台部署和更簡潔的程式碼。

Curtis Chau
技術作家

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

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