C# (.NET) 中的 PDF 生成:库概述与实践示例
PDF 文档生成是 C# 企业开发中最常见的任务之一。报告、发票、货运单、合同——所有这些都可以通过编程方式方便地生成。在 .NET 生态系统中,有几个成熟的库,每个都有其优势。在本文中,我们将分析四个主要工具,展示代码示例,并帮助您为项目选择合适的工具。
1. iTextSharp / iText 7 for .NET
iText 可以说是最著名的 PDF 处理库。iTextSharp 版本是 Java 库到 .NET Framework 的移植版本。目前最新的是 iText 7 for .NET(开源项目使用 AGPL 许可证,或商业许可证)。
功能:
- 从头创建 PDF
- 使用模板 (PdfTemplate)
- 添加图像、表格、列表
- 支持 Unicode、西里尔字母
- 数字签名、加密
示例:带表格的简单文档
using iText.Kernel.Pdf;using iText.Layout;using iText.Layout.Element;
public void CreateSimplePdf(string filePath){ using (PdfWriter writer = new PdfWriter(filePath)) using (PdfDocument pdf = new PdfDocument(writer)) using (Document doc = new Document(pdf)) { doc.Add(new Paragraph("你好,世界!")); Table table = new Table(3); table.AddCell("姓名"); table.AddCell("年龄"); table.AddCell("城市"); table.AddCell("安娜"); table.AddCell("28"); table.AddCell("莫斯科"); doc.Add(table); }}2. PDFsharp / MigraDoc
PDFsharp 是一个轻量级的开源库 (MIT 许可证)。与 MigraDoc 配合使用时,可以像“文字处理器”一样描述文档:段落、样式、页眉页脚。非常适合生成没有复杂图形的简单报告。
优点:
- 入门门槛低
- 良好的西里尔字母支持
- 无需许可证
- 支持 .NET Framework 和 .NET Core
示例:通过 MigraDoc 创建文档
using MigraDoc.DocumentObjectModel;using MigraDoc.Rendering;
public void CreateWithMigraDoc(string filePath){ Document doc = new Document(); Section section = doc.AddSection(); Paragraph para = section.AddParagraph("报告标题"); para.Format.Font.Size = 18; para.Format.Font.Bold = true; section.AddParagraph("这是报告文本。使用 PDFsharp 和 MigraDoc 生成。"); PdfDocumentRenderer renderer = new PdfDocumentRenderer(true); renderer.Document = doc; renderer.RenderDocument(); renderer.PdfDocument.Save(filePath);}3. QuestPDF
QuestPDF 是一个现代的库,具有流畅的接口(类似于 LINQ 的语法)。采用 MIT 许可证(免费用于商业用途)。积极开发中,支持 .NET 6/7/8。
关键特性:
- 声明式布局构建
- 自动分页
- 支持图像、SVG、二维码
- 高性能
示例:生成发票
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(2, Unit.Centimetre); page.DefaultTextStyle(x => x.FontSize(12)); page.Header().Element(ComposeHeader); page.Content().Element(ComposeContent); page.Footer().AlignCenter().Text(x => {