使用 QuestPDF 在 C# (.NET) 中生成 PDF 报告
在现代 .NET 平台开发中,经常需要创建专业的 PDF 文档:报告、发票、运单、分析摘要和其他业务文档。QuestPDF 库是一个现代、高性能且直观的 C# PDF 生成解决方案。它不需要安装第三方工具(例如 wkhtmltopdf),并且完全在 .NET 托管代码中运行。
在本文中,我们将详细介绍如何开始使用 QuestPDF、配置项目、创建包含表格、图像和文本格式的简单报告。
安装与配置
QuestPDF 通过 NuGet 分发。要安装,请在 Package Manager Console 中执行命令,或通过 Visual Studio/Rider 界面操作:
Install-Package QuestPDF或者通过 .NET CLI:
dotnet add package QuestPDF安装后,需要初始化一次许可证。商业使用需要付费许可证,但对于测试和小型项目,可以使用带有水印的免费模式。要移除水印,请在程序开头添加:
QuestPDF.Settings.License = LicenseType.Community;// 或用于商业用途:// QuestPDF.Settings.License = LicenseType.Professional;创建第一个 PDF 文档
QuestPDF 使用 Fluent API——您通过连续的方法调用来描述文档结构。让我们看一个最小示例:
using QuestPDF.Fluent;using QuestPDF.Helpers;using QuestPDF.Infrastructure;
// 配置许可证(必需)QuestPDF.Settings.License = LicenseType.Community;
// 创建文档Document.Create(container =>{ container.Page(page => { page.Size(PageSizes.A4); page.Margin(2, Unit.Centimetre); page.DefaultTextStyle(x => x.FontSize(12));
page.Header() .Text("销售报告") .SemiBold().FontSize(24).FontColor(Colors.Blue.Medium);
page.Content() .PaddingVertical(1, Unit.Centimetre) .Column(col => { col.Item().Text("日期: " + DateTime.Now.ToShortDateString()); col.Item().PaddingBottom(10).LineHorizontal(1); col.Item().Text("以下是包含数据的表格:"); });
page.Footer() .AlignCenter() .Text(x => { x.Span("第 "); x.CurrentPageNumber(); x.Span(" 页"); }); });}).GeneratePdf("report.pdf");此代码创建一个包含标题、日期、水平线和页脚页码的 PDF 文件。
使用表格
最常见的任务之一是输出表格数据。QuestPDF 提供了强大的 API 来创建具有自动列宽调整功能的表格:
container.Page(page =>{ page.Size(PageSizes.A4); page.Margin(20);
page.Content().Table(table => { // 定义列(宽度为可用空间的百分比) table.ColumnsDefinition(columns => { columns.RelativeColumn(3); // 名称 columns.RelativeColumn(1); // 数量 columns.RelativeColumn(1); // 价格 columns.RelativeColumn(1); // 金额 });
// 表格标题 table.Header(header => { header.Cell().Background(Colors.Grey.Lighten2).Padding(5).Text("商品"); header.Cell().Background(Colors.Grey.Lighten2).Padding(5).AlignCenter().Text("数量"); header.Cell().Background(Colors.Grey.Lighten2).Padding(5).AlignCenter().Text("价格"); header.Cell().Backgrou