在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
C# 的 IEnumerable介面是 .NET 框架中最具多功能性的工具之一,讓開發人員能夠以高度彈性的方式處理集合。 結合時IronPDFIEnumerable 允許動態數據操作和高效 PDF 生成,這使其非常適合於創建報告、導出數據或從數據庫查詢生成文檔等情境。
使用 IEnumerable 確保您的應用程式保持可擴展性和記憶體效能,因為它以惰性方式處理資料,並避免一次將整個資料集加載到記憶體中。 這對於處理大量數據集的大型應用程式尤其有用,例如一個巨大的資料庫表。
IronPDF 是一個強大的 .NET 函式庫,旨在簡化以程式方式創建、編輯和管理 PDF 檔案的過程。 它提供了廣泛的功能,包括 HTML 轉換為 PDF、文字提取、PDF 合併等。 通過將 IronPDF 集成到您的 C# 項目中,您可以有效處理複雜的 PDF 任務,而不需要深入了解 PDF 的內部結構。
IronPDF 也支持多種格式,允許您從原始 HTML、Razor Views、ASP.NET 網頁,甚至直接從數據結構生成 PDF。 這種靈活性使其成為開發人員構建現代數據驅動應用程式的基本工具。
要在您的專案中使用IronPDF,請按以下步驟操作:
在 Visual Studio 中打開您的 .NET 專案。
Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
在您的 Visual Studio 專案中,前往 工具 > NuGet 套件管理員 > 管理解決方案的 NuGet 套件
IEnumerable 介面表示可以列舉的元素序列。 常見的例子包括陣列、清單和 LINQ 查詢結果。 透過使用 LINQ,您可以在使用 IronPDF 生成 PDF 之前,將資料篩選、排序及投影至所需的格式。
IEnumerable 的其中一個主要優勢是其延遲執行模型,讓查詢僅在訪問結果時才被執行。 這可實現高效的數據操作並減少複雜工作流程中的計算開銷。
此外,該列表實現了 IEnumerable,這意味著任何像 List
想像一下,您有一個實作 IEnumerable 的員工清單,您需要將其匯出為 PDF 表格。 使用 IEnumerable 和 IronPDF,您可以使用迭代器方法遍歷數據並將其轉換成結構良好的 PDF。
為了增強展示效果,您可以使用帶有內嵌 CSS 的 HTML 表格,根據數據動態地設計行和列。 這確保了 PDF 的輸出既具功能性又具有視覺吸引力。
使用 LINQ,您可以在將數據傳遞給 IronPDF 之前過濾和轉換它。 例如,您可以過濾僅顯示現任員工,並將他們的姓名格式化為大寫以用於 PDF 輸出。
var activeEmployees = employees.Where(e => e.IsActive).Select(e => new {
Name = e.Name.ToUpper(),
Position = e.Position,
Age = e.Age
});
var activeEmployees = employees.Where(e => e.IsActive).Select(e => new {
Name = e.Name.ToUpper(),
Position = e.Position,
Age = e.Age
});
Dim activeEmployees = employees.Where(Function(e) e.IsActive).Select(Function(e) New With {
Key .Name = e.Name.ToUpper(),
Key .Position = e.Position,
Key .Age = e.Age
})
然後,這個轉換後的數據可以被轉換成適合 PDF 的 HTML 格式以便渲染。
如果您需要為集合類中的每個記錄生成單獨的 PDF,您可以使用 foreach 迴圈來遍歷可枚舉項,並動態生成單獨的 PDF。 這在製作發票、證書或個性化報告時特別有用。
foreach (var employee in employees)
{
string html = $"<h1>{employee.Name}</h1><p>Position: {employee.Position}</p><p>Age: {employee.Age}</p>";
var pdf = Renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"{employee.Name}_Report.pdf");
}
foreach (var employee in employees)
{
string html = $"<h1>{employee.Name}</h1><p>Position: {employee.Position}</p><p>Age: {employee.Age}</p>";
var pdf = Renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"{employee.Name}_Report.pdf");
}
For Each employee In employees
Dim html As String = $"<h1>{employee.Name}</h1><p>Position: {employee.Position}</p><p>Age: {employee.Age}</p>"
Dim pdf = Renderer.RenderHtmlAsPdf(html)
pdf.SaveAs($"{employee.Name}_Report.pdf")
Next employee
在 C# 中,擴展方法是一種強大的方式,可以在不修改其源代碼的情況下向現有類型添加功能。 您可以創建擴展方法來簡化對 IEnumerable 或 List 的操作。
例如,我們來創建一個擴充方法,以從可列舉的集合中獲取第一個元素。
public static class EnumerableExtensions
{
public static T FirstOrDefaultElement<T>(this IEnumerable<T> collection)
{
return collection?.FirstOrDefault();
}
}
public static class EnumerableExtensions
{
public static T FirstOrDefaultElement<T>(this IEnumerable<T> collection)
{
return collection?.FirstOrDefault();
}
}
Public Module EnumerableExtensions
<System.Runtime.CompilerServices.Extension> _
Public Function FirstOrDefaultElement(Of T)(ByVal collection As IEnumerable(Of T)) As T
Return collection?.FirstOrDefault()
End Function
End Module
首先,設定您的專案並初始化 IronPDF 和 ChromePdfRenderer 類別:
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
Imports IronPdf
Private renderer As New ChromePdfRenderer()
將您的可枚舉數據準備為 HTML 字串:
var employees = new List<Employee>
{
new Employee { Name = "John Doe", Position = "Developer", Age = 30 },
new Employee { Name = "Jane Smith", Position = "Designer", Age = 25 }
};
string html = "<table style='width:100%; border: 1px solid black;'>" +
"<tr><th>Name</th><th>Position</th><th>Age</th></tr>";
foreach (var employee in employees)
{
html += $"<tr><td>{employee.Name}</td><td>{employee.Position}</td><td>{employee.Age}</td></tr>";
}
html += "</table>";
var employees = new List<Employee>
{
new Employee { Name = "John Doe", Position = "Developer", Age = 30 },
new Employee { Name = "Jane Smith", Position = "Designer", Age = 25 }
};
string html = "<table style='width:100%; border: 1px solid black;'>" +
"<tr><th>Name</th><th>Position</th><th>Age</th></tr>";
foreach (var employee in employees)
{
html += $"<tr><td>{employee.Name}</td><td>{employee.Position}</td><td>{employee.Age}</td></tr>";
}
html += "</table>";
Dim employees = New List(Of Employee) From {
New Employee With {
.Name = "John Doe",
.Position = "Developer",
.Age = 30
},
New Employee With {
.Name = "Jane Smith",
.Position = "Designer",
.Age = 25
}
}
Dim html As String = "<table style='width:100%; border: 1px solid black;'>" & "<tr><th>Name</th><th>Position</th><th>Age</th></tr>"
For Each employee In employees
html &= $"<tr><td>{employee.Name}</td><td>{employee.Position}</td><td>{employee.Age}</td></tr>"
Next employee
html &= "</table>"
將 HTML 轉換為 PDF:
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Employees.pdf");
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Employees.pdf");
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("Employees.pdf")
現在我們已經仔細看看如何使用 C# 的 Enumerable 類和 IronPDF 來生成 PDF 文件,現在讓我們看看一個完整的範例代碼,其中我們使用這些工具生成了一個新的動態 PDF 文檔。
using System;
using System.Collections.Generic;
using System.Linq;
using IronPdf;
public class Employee
{
public string Name { get; set; }
public string Position { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
// Sample employee data
var employees = new List<Employee>
{
new Employee { Name = "John Doe", Position = "Developer", Age = 30 },
new Employee { Name = "Jane Smith", Position = "Designer", Age = 25 },
new Employee { Name = "Sam Wilson", Position = "Manager", Age = 35 }
};
// Filter and sort data using LINQ
var filteredEmployees = employees
.Where(e => e.Age >= 25)
.OrderBy(e => e.Name)
.ToList();
// Generate HTML for the PDF
string html = "<h1 style='text-align:center;'>Employee Report</h1>" +
"<table style='width:100%; border-collapse: collapse;'>" +
"<tr style='background-color: #f2f2f2;'>" +
"<th style='border: 1px solid black; padding: 8px;'>Name</th>" +
"<th style='border: 1px solid black; padding: 8px;'>Position</th>" +
"<th style='border: 1px solid black; padding: 8px;'>Age</th></tr>";
foreach (var employee in filteredEmployees)
{
html += $"<tr>" +
$"<td style='border: 1px solid black; padding: 8px;'>{employee.Name}</td>" +
$"<td style='border: 1px solid black; padding: 8px;'>{employee.Position}</td>" +
$"<td style='border: 1px solid black; padding: 8px;'>{employee.Age}</td>" +
$"</tr>";
}
html += "</table>";
// Initialize ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the HTML to PDF
try
{
var pdf = renderer.RenderHtmlAsPdf(html);
string outputPath = "EmployeeReport.pdf";
pdf.SaveAs(outputPath);
Console.WriteLine($"PDF generated successfully at: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"Error generating PDF: {ex.Message}");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using IronPdf;
public class Employee
{
public string Name { get; set; }
public string Position { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
// Sample employee data
var employees = new List<Employee>
{
new Employee { Name = "John Doe", Position = "Developer", Age = 30 },
new Employee { Name = "Jane Smith", Position = "Designer", Age = 25 },
new Employee { Name = "Sam Wilson", Position = "Manager", Age = 35 }
};
// Filter and sort data using LINQ
var filteredEmployees = employees
.Where(e => e.Age >= 25)
.OrderBy(e => e.Name)
.ToList();
// Generate HTML for the PDF
string html = "<h1 style='text-align:center;'>Employee Report</h1>" +
"<table style='width:100%; border-collapse: collapse;'>" +
"<tr style='background-color: #f2f2f2;'>" +
"<th style='border: 1px solid black; padding: 8px;'>Name</th>" +
"<th style='border: 1px solid black; padding: 8px;'>Position</th>" +
"<th style='border: 1px solid black; padding: 8px;'>Age</th></tr>";
foreach (var employee in filteredEmployees)
{
html += $"<tr>" +
$"<td style='border: 1px solid black; padding: 8px;'>{employee.Name}</td>" +
$"<td style='border: 1px solid black; padding: 8px;'>{employee.Position}</td>" +
$"<td style='border: 1px solid black; padding: 8px;'>{employee.Age}</td>" +
$"</tr>";
}
html += "</table>";
// Initialize ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the HTML to PDF
try
{
var pdf = renderer.RenderHtmlAsPdf(html);
string outputPath = "EmployeeReport.pdf";
pdf.SaveAs(outputPath);
Console.WriteLine($"PDF generated successfully at: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"Error generating PDF: {ex.Message}");
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports IronPdf
Public Class Employee
Public Property Name() As String
Public Property Position() As String
Public Property Age() As Integer
End Class
Public Class Program
Public Shared Sub Main(ByVal args() As String)
' Sample employee data
Dim employees = New List(Of Employee) From {
New Employee With {
.Name = "John Doe",
.Position = "Developer",
.Age = 30
},
New Employee With {
.Name = "Jane Smith",
.Position = "Designer",
.Age = 25
},
New Employee With {
.Name = "Sam Wilson",
.Position = "Manager",
.Age = 35
}
}
' Filter and sort data using LINQ
Dim filteredEmployees = employees.Where(Function(e) e.Age >= 25).OrderBy(Function(e) e.Name).ToList()
' Generate HTML for the PDF
Dim html As String = "<h1 style='text-align:center;'>Employee Report</h1>" & "<table style='width:100%; border-collapse: collapse;'>" & "<tr style='background-color: #f2f2f2;'>" & "<th style='border: 1px solid black; padding: 8px;'>Name</th>" & "<th style='border: 1px solid black; padding: 8px;'>Position</th>" & "<th style='border: 1px solid black; padding: 8px;'>Age</th></tr>"
For Each employee In filteredEmployees
html &= $"<tr>" & $"<td style='border: 1px solid black; padding: 8px;'>{employee.Name}</td>" & $"<td style='border: 1px solid black; padding: 8px;'>{employee.Position}</td>" & $"<td style='border: 1px solid black; padding: 8px;'>{employee.Age}</td>" & $"</tr>"
Next employee
html &= "</table>"
' Initialize ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()
' Render the HTML to PDF
Try
Dim pdf = renderer.RenderHtmlAsPdf(html)
Dim outputPath As String = "EmployeeReport.pdf"
pdf.SaveAs(outputPath)
Console.WriteLine($"PDF generated successfully at: {outputPath}")
Catch ex As Exception
Console.WriteLine($"Error generating PDF: {ex.Message}")
End Try
End Sub
End Class
此C#程式旨在使用IronPDF庫生成過濾後的員工數據PDF報告。 上述程式碼首先定義了一個 Employee 類別,包含 Name、Position 和 Age 屬性,代表單個員工記錄。
建立了一個樣本員工數據列表,包括三個具有不同名稱、職位和年齡的員工對象。 接著,程序使用 LINQ 篩選此清單,選擇年齡在 25 歲或以上的員工,並按名字的字母順序排序。 這個過濾和排序後的列表存儲在 filteredEmployees 變數中。
接下來,程序構建一個將用於生成 PDF 的 HTML 字串。 它以標題和表格結構開始,定義了姓名、職位和年齡的欄目標題。 然後,它遍歷篩選後的員工列表,動態生成每個員工信息的表格行。 生成的 HTML 用於通過 IronPDF 創建 PDFChromePdfRenderer.
上述範例有效地展示了如何使用IronPDF從動態生成的 HTML 生成 PDF,展示了 LINQ 過濾和排序數據的強大功能,並在 PDF 生成過程中優雅地處理異常。
使用 LINQ 來優化對資料的篩選和轉換。 例如:
var filteredEmployees = employees.Where(e => e.Age > 25).OrderBy(e => e.Name);
var filteredEmployees = employees.Where(e => e.Age > 25).OrderBy(e => e.Name);
Dim filteredEmployees = employees.Where(Function(e) e.Age > 25).OrderBy(Function(e) e.Name)
通過有效鏈接 LINQ 方法來最小化冗餘操作。 這改善了效能,特別是在處理大型數據集時。
對於大型資料集,請考慮將數據以較小的區塊進行流式傳輸,以避免記憶體負擔。 使用 yield return 延遲生成非泛型集合數據,確保高效的內存使用。
IEnumerable<Employee> GetEmployees() {
foreach (var employee in database.GetAllEmployees()) {
yield return employee;
}
}
IEnumerable<Employee> GetEmployees() {
foreach (var employee in database.GetAllEmployees()) {
yield return employee;
}
}
Private Iterator Function GetEmployees() As IEnumerable(Of Employee)
For Each employee In database.GetAllEmployees()
Yield employee
Next employee
End Function
將您的 PDF 生成邏輯包裝在 try-catch 區塊中,以優雅地處理錯誤:
try
{
var pdf = Renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("output.pdf");
}
catch (IronPdf.Exceptions.PdfException ex)
{
Console.WriteLine($"PDF Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Error: {ex.Message}");
}
try
{
var pdf = Renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("output.pdf");
}
catch (IronPdf.Exceptions.PdfException ex)
{
Console.WriteLine($"PDF Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Error: {ex.Message}");
}
Try
Dim pdf = Renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("output.pdf")
Catch ex As IronPdf.Exceptions.PdfException
Console.WriteLine($"PDF Error: {ex.Message}")
Catch ex As Exception
Console.WriteLine($"General Error: {ex.Message}")
End Try
記錄錯誤並提供用戶友好的反饋可以顯著提高應用程式的穩健性。
C# 的 IEnumerable 與... 的整合IronPDF解鎖一種以程式方式生成專業 PDF 的高效且靈活的方法。 通過利用 IEnumerable,您可以簡化數據的轉換和格式化,並利用 IronPDF 的豐富功能集生產高品質的文檔。 無論您是匯出數據報告、製作發票,還是生成個性化內容,這個組合都能確保其可擴展性、性能和易用性。
我們鼓勵開發人員探索 IronPDF 的更多進階功能,例如嵌入多媒體或保護 PDF,以進一步提升他們的文件自動化工作流程。 如需更多見解、教程和支持,請參閱IronPDF 文件檔案.