使用 C# (.NET) 生成 PDF 报告:库概览与示例
在现代 .NET 平台开发中,创建 PDF 文档是一项常见任务。无论是生成发票、报告、运单还是分析仪表板,C# 都提供了强大的 PDF 处理工具。在本文中,我们将介绍三个流行的库:iTextSharp、QuestPDF 和 PdfSharp。您将了解如何根据具体任务选择合适的库,并看到可运行的代码示例。
1. iTextSharp(适用于 .NET 的 iText 7)
iTextSharp 是流行的 Java 库 iText 在 .NET 上的移植版本。这是最成熟且功能最丰富的解决方案,支持复杂的布局、表格、图像、注释和数字签名。然而,商业使用需要购买许可证(开源项目使用 AGPL 许可)。
安装
dotnet add package itext7示例:带表格的简单报告
using iText.Kernel.Pdf;using iText.Layout;using iText.Layout.Element;
public void CreatePdfReport(){ string filePath = "report.pdf"; using (PdfWriter writer = new PdfWriter(filePath)) using (PdfDocument pdf = new PdfDocument(writer)) using (Document document = new Document(pdf)) { document.Add(new Paragraph("三月份销售报告") .SetBold().SetFontSize(18));
Table table = new Table(3); table.AddCell("商品"); table.AddCell("数量"); table.AddCell("价格"); table.AddCell("笔记本电脑"); table.AddCell("12"); table.AddCell("75,000 ₽"); table.AddCell("显示器"); table.AddCell("5"); table.AddCell("32,000 ₽");
document.Add(table); }}优点: 最大的灵活性,支持复杂结构,数字签名。
缺点: 对初学者来说 API 复杂,商业使用需要许可。
2. QuestPDF
QuestPDF 是一个现代库,具有流畅的接口和内置渲染引擎。它允许以声明式风格描述文档,类似于 HTML/CSS。非常适合生成带有重复元素的典型报告。
安装
dotnet add package QuestPDF示例:带标题和表格的发票
using QuestPDF.Fluent;using QuestPDF.Helpers;using QuestPDF.Infrastructure;
public byte[] GenerateInvoice(){ return Document.Create(container => { container.Page(page => { page.Size(PageSizes.A4); page.Margin(20); page.Header().Text("发票号 12345") .SemiBold().FontSize(20).FontColor(Colors.Blue.Darken2);
page.Content().Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); });
table.Header(header => { header.Cell().Background(Colors.Grey.Lighten3).Text("服务"); header.Cell().Background(Colors.Grey.Lighten3).Text("费用"); header.Cell().Background(Colors.Grey.Lighten3).Text("数量"); });
table.Cell().Text("咨询"); table.Cell().Text("5,000 ₽"); table.Cell().Text("2");
table.Cell().Text("开发"); table.Cell().Text("15,000 ₽"); table.Cell().Text("1"); });
page.Footer().AlignCenter().Text("感谢您的合作!"); }); }).GeneratePdf();}优点: 代码简单易读,性能出色,商业使用免费