跳過到頁腳內容
使用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
  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

在 Visual Studio 中建立ASP.NET專案的步驟

  1. 開啟 Visual Studio 並建立一個新的ASP.NET Core專案。
  2. 選擇所需的項目範本(例如,MVC 或Razor Pages)。

    如何在.NET中建立報表:圖 1

  3. 配置項目設置,例如項目名稱、位置和框架版本。

    如何在.NET中建立報表:圖 2

  4. 點選"建立"生成專案結構。

安裝IronPDF和IronPDF

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

  1. 右鍵點選解決方案資源管理器,開啟NuGet解決方案套件管理員。
  2. 搜尋" IronPDF "和" IronPDF "。

    如何在.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;
    }
}
$vbLabelText   $csharpLabel

步驟 2:建立新的 Web 表單視圖

接下來,建立一個Razor視圖( Sales.cshtml ),以表格格式顯示銷售數據,並提供一個按鈕來產生 PDF 報告。


@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>

@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

如何在.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>();
$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);
        }
    }
}
$vbLabelText   $csharpLabel

在上面的程式碼中,建構函式內部將IRazorViewRenderer服務指派給了私有欄位_viewRenderService 。 此外,控制器初始化了一個名為salesData 的列表,其中包含SalesModel類別的實例,用於表示銷售訊息,以作演示之用。

Sales()操作方法傳回一個名為"Sales"的視圖,並將salesData清單作為模型傳遞。 此操作負責在關聯的視圖中呈現銷售數據,使用戶能夠以表格格式或任何其他所需的佈局來視覺化銷售資訊。

如何在.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");
}
$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應用程式中,以增強報告功能。

如何在.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 網路應用程式,然後安裝 IronPDF 及其 MVC 擴展。使用 ChromePdfRenderer 類將 Razor 視圖轉換為 PDF,並利用 File 方法創建報表。

使用 ASP.NET 的 PDF 庫有何優勢?

使用像 IronPDF 這樣的 ASP.NET PDF 庫可以簡化生成和管理 PDF 報表的過程。它支持 HTML 到 PDF 轉換、PDF 編輯、表單填寫、條碼生成和文檔安全,適用於各種網路應用需求。

我如何將 Razor 視圖轉換為 ASP.NET 中的 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完全支援.NET 10,適用於Web、桌面和控制台專案類型。它利用.NET 10的運行時性能改進(如減少堆分配和更快的JIT)、C#語言增強和現代API。開發人員可以在.NET 10應用中無縫使用RenderHtmlAsPdfRenderHtmlAsPdfAsync等方法,受益於輸出速度、跨平台部署和更簡潔的代碼。

Curtis Chau
技術作家

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

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

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me