在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
報告對於以結構化且視覺吸引的格式呈現數據至關重要。 無論是銷售數據、分析還是財務摘要,生成報告都是網絡應用程式中的常見需求。 Microsoft 提供可透過 Web Forms Report Viewer Control 整合到網頁應用程式中的 rdlc 報表服務。 然而,該過程通常可能是複雜且耗時的。
這就是 IronPDF 派上用場的地方。 IronPDF 是一個多功能的函式庫,簡化了在 ASP.NET 和其他網頁框架中生成 PDF 報告的過程,提供強大的功能和易用性。 在本文中,我們將探討如何使用IronPDF在ASP.NET中創建報告。
使用 Visual Studio 建立 ASP.NET Web 應用程式
安裝IronPDF和IronPDF.Extensions.MVC.Core
實例化ChromePdfRenderer物件寄件者
調用RenderRazorViewToPdf方法將視圖轉換為PDF
使用Response.Headers.Append添加「Content-Disposition」
IronPDF 是一個多功能的函式庫,可以簡化在 ASP.NET 和其他網路框架中生成 PDF 文件的過程。 其豐富的功能集和直觀的API使其成為尋求直接從其Web應用程式生成動態報告、發票、收據等的開發人員的理想選擇。 使用 IronPDF,開發人員可以輕鬆地將 HTML、CSS,甚至 Razor 視圖轉換成高品質的 PDF 文件,從而將報告功能無縫整合到他們的 ASP.NET 項目中。
在我們開始之前,請確保您具備以下先決條件:
打開 Visual Studio 並創建一個新的 ASP.NET Core 項目。
選擇所需的專案模板(例如,MVC 或 Razor Pages)。
配置專案設定,例如專案名稱、位置和框架版本。
接下來,讓我們使用 NuGet 套件管理器安裝 IronPDF 及其 MVC 擴展套件:
在解決方案總管上右鍵單擊,開啟 NuGet 套件管理器解決方案。
搜索「IronPDF」和「IronPDF.Extensions.Mvc.Core」。
現在,讓我們深入了解在 ASP.NET 專案中使用 IronPDF 建立 PDF 報告的步驟。 在將視圖轉換為報告之前,我們需要一個模型、視圖和控制器來創建一個數據來源,用於創建和下載新的 PDF 格式報告。
首先,創建一個模型類別(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
接下來,建立一個 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>
現在,將銷售作為菜單項目添加到位於 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>
在 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)()
實作一個控制器(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
在上面的代碼中,構造函式內將 IRazorViewRenderer 服務賦值給私有字段 _viewRenderService。 此外,控制器初始化了一個名為salesData的列表,其中包含SalesModel類的實例,這些實例表示銷售資訊以供演示之用。
Sales() 行為方法返回一個名為 "Sales" 的視圖,並將 salesData 清單作為模型傳遞。 此操作負責在相關視圖中渲染銷售數據,使用戶能夠以表格格式或其他所需的佈局查看銷售信息。
在控制器的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
讓我們詳細了解上述程式碼的運作原理:
許可證密鑰設置:
License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
渲染器初始化:
ChromePdfRenderer renderer = new ChromePdfRenderer();
渲染視圖到 PDF:
PdfDocument PDF = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData);
Content-Disposition Header:
Response.Headers.Append("Content-Disposition", "inline");
返回 PDF 檔案:
return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf");
總體而言,這個方法有效地協調了從 Razor 視圖生成 PDF 報告的過程,適合在 ASP.NET 應用程序中進行整合,以增強報告功能。
如需有關 IronPDF 如何簡化 PDF 報告生成過程及其他 PDF 相關任務的詳細信息,請訪問文檔頁面。
在本文中,我們探討了IronPDF如何簡化在ASP.NET應用程式中生成PDF報告的過程。 通過遵循上述的分步指南,您可以快速將 IronPDF 集成到您的 ASP.NET 項目中,並輕鬆生成動態 PDF 報告。
IronPDF 具備豐富的功能集和無縫的整合能力,使開發人員能夠創建滿足用戶和企業需求的專業品質報告。