如何在C#開發人員中使用ChatGPT與IronPDF
報告在以結構化和視覺吸引人的格式展示資料方面至關重要。 無論是銷售資料、分析還是財務摘要,生成報告都是網路應用中的常見需求。 Microsoft 提供RDLC報告服務,可以使用Web Forms報告檢視器控制項整合到網路應用中。 然而,這個過程往往既複雜又耗時。
這就是IronPDF 的用武之地。 IronPDF是一個多功能的程式庫,可以簡化在ASP.NET和其他網路框架中生成PDF報告的過程,提供強大的功能和易於使用的特性。 在本文中,我們將探討如何在ASP.NET中使用IronPDF建立報告。
如何在ASP.NET中建立報告
- 使用Visual Studio建立ASP.NET網路應用
- Install IronPDF and IronPdf.Extensions.MVC.Core
- 實例化 ChromePdfRenderer 物件發送者
- 調用 RenderRazorViewToPdf 方法將視圖轉換為PDF
- 使用 Response.Headers.Append 新增 "Content-Disposition"
- 使用 PDF.BinaryData 和 File 方法建立報告
IronPDF簡介
IronPDF 是一個多功能的程式庫,可以簡化在ASP.NET和其他網路框架中生成PDF文件的過程。 它的豐富功能集和直觀的API使其成為開發者的理想選擇,直接從他們的網路應用中生成動態報告、發票、收據等。 使用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 and IronPdf.Extensions.Mvc.Core
在Visual Studio中建立ASP.NET項目的步驟
- 打開Visual Studio並建立一個新的ASP.NET Core項目。
-
選擇所需的項目模板(例如,MVC或Razor Pages)。

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

- 點擊 "Create" 以生成項目結構。
安裝 IronPDF 和 IronPdf.Extensions.Mvc.Core
接下來,讓我們使用NuGet套件管理器安裝IronPDF及其MVC擴展包:
- 右鍵單擊解決方案資源管理器,打開NuGet套件管理器以解決方案。
-
Search for "IronPDF" and "IronPdf.Extensions.Mvc.Core".

- 將兩個包都安裝到您的解決方案中。
在ASP.NET網路應用中建立報告檢視器的步驟
現在,我們來深入了解如何在ASP.NET項目中使用IronPDF建立PDF報告的步驟。 在將視圖轉換為報告之前,我們需要Model、View和Controller來建立資料源,以建立和下載新的PDF格式報告。
步驟1:定義Model類
首先,建立一個表示銷售資料的模型類(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
步驟2:建立新的網路表單視圖
接下來,建立一個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>
現在,將Sales新增為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>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Sales" asp-action="Sales">Sales</a>
</li>

步驟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)()
步驟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
在上面的程式碼中,在構造函式內,IRazorViewRenderer 服務被賦值給私有字段 _viewRenderService。 此外,控制器初始化一個名為 salesData 的列表,其中包含 SalesModel 類的實例,表示銷售資訊以供演示。
Sales() 操作方法返回一個名為 "Sales" 的視圖,將 salesData 列表作為模型傳遞。 此操作負責在關聯的視圖中呈現銷售資料,使使用者可以以表格格式或其他任何所需的布局可視化銷售資訊。

步驟5:生成PDF報告
在控制器的 GeneratePdf 操作中,使用IronPDF的 ChromePdfRenderer 將Razor視圖轉換為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
讓我們深入了解上述程式碼的工作原理:
- 授權金鑰設置:
- License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
- 該行設置使用IronPDF所需的授權金鑰。 這對於在應用中使用IronPDF功能至關重要。
- 渲染器初始化:
- ChromePdfRenderer renderer = new ChromePdfRenderer();
- 建立一個 ChromePdfRenderer 實例。 這個渲染器負責使用Chromium瀏覽器引擎將Razor視圖轉換為PDF格式。
- 渲染視圖至PDF:
- PdfDocument PDF = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData);
- 調用 ChromePdfRenderer 的
RenderRazorViewToPdf()方法將指定的Razor視圖(Views/Sales/Sales.cshtml)渲染為PDF文件。 變數 salesData 作為視圖的模型。
- 內容配置標頭:
Response.Headers.Append("Content-Disposition", "inline");- 設置HTTP響應頭 Content-Disposition 為 "inline"。 這會指示瀏覽器直接將PDF內容顯示在瀏覽器視窗或標籤中,以便在打開時預覽報告。
- 返回PDF文件:
- return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf");
- 返回PDF文件內容為 FileContentResult。 它包含PDF的二進制資料(pdf.BinaryData),指定MIME型別為 "application/pdf",並建議文件名為 "SalesReport.pdf"。
總而言之,這個方法高效地組織從Razor視圖生成PDF報告的過程,使其適合在ASP.NET應用中整合,以增強報告能力。

如需有關IronPDF如何簡化PDF報告生成過程及其他PDF相關任務的詳細資訊,請存取文件頁面。
結論
在本文中,我們探討了IronPDF如何簡化在ASP.NET應用中生成PDF報告的過程。 通過遵循上面提供的分步指南,您可以快速將IronPDF整合到您的ASP.NET項目中,並輕鬆生成動態PDF報告。
憑藉豐富的功能集和無縫整合,IronPDF讓開發者能夠建立滿足其使用者和業務需求的專業品質報告。
常見問題
如何在ASP.NET中生成PDF報告?
您可以通過使用IronPDF在ASP.NET中生成PDF報告。首先,在Visual Studio中設置ASP.NET Web應用程式,然後安裝IronPDF及其MVC擴展。使用ChromePdfRenderer類將Razor視圖轉換為PDF,並使用File方法建立報告。
使用PDF程式庫對ASP.NET有什麼好處?
使用像IronPDF這樣的PDF程式庫簡化了在ASP.NET中生成和管理PDF報告的過程。它支持HTML轉PDF、PDF編輯、表單填寫、條碼生成和文件安全,為各種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新增水印?
您可以在ASP.NET應用程式中使用IronPDF為PDF新增水印。該程式庫提供用於在PDF文件上疊加水印的API,允許您有效地保護敏感資訊或在您的文件上新增品牌標識。
使用IronPDF在我的ASP.NET專案中有哪些先決條件?
在使用IronPDF之前,請確保您對ASP.NET開發有基本理解並已安裝Visual Studio。此外,您需要在專案中安裝IronPDF及其MVC擴展以利用其功能。
我在哪裡可以找到更多關於IronPDF的資訊?
如需更多關於IronPDF及其功能的詳細資訊,您可以存取IronPDF網站上的文件頁面。該文件提供有關設置、功能和範例程式碼的見解。
IronPDF是否與.NET 10相容,並帶來哪些優勢?
是的,IronPDF完全支持.NET 10跨Web、桌面和控制台專案型別。它利用.NET 10運行時性能改進(如減少堆分配和更快的JIT)、C#語言增強和現代API。開發者可以在.NET 10應用程式中無縫使用RenderHtmlAsPdf和RenderHtmlAsPdfAsync等方法,從中受益於輸出速度、跨平台部署和更清晰的程式碼。




