如何在 .NET 中加载和管理 PDF 文档
如何在 .NET 中加载和管理 PDF 文档
本指南介绍如何使用核心 Document 类打开、创建和保存 PDF 文档。
先决条件
| 需求 | 细节 |
|---|---|
| 运行时 | .NET 8.0 或更高版本 |
| 包 | dotnet add package Aspose.Pdf.Foss |
从字节打开 PDF
通过将字节数组传递给 Document.Open,将现有 PDF 加载到 Document 实例中。此方法避免文件锁定,并且非常适用于内存中的工作流,例如 Web 请求处理程序。
using var doc = Document.Open(File.ReadAllBytes("input.pdf"));
Console.WriteLine($"Pages: {doc.Pages.Count}");创建新文档
实例化一个空的 Document,添加至少一页,然后调用 Save 在磁盘上生成有效的 PDF 文件。
using var doc = new Document();
doc.Pages.Add();
doc.Save("new.pdf");修改页面几何
通过其基于 1 的索引访问页面并设置媒体框、裁剪框或旋转。Rectangle 构造函数接受坐标,顺序为左、下、右、上。
var page = doc.Pages[1];
page.SetMediaBox(new Rectangle(0, 0, 612, 792));
page.SetRotation(90);添加文件附件
使用 FileSpecification 将文件嵌入 PDF。嵌入的文件会出现在查看器的附件面板中,收件人可以提取它。
var spec = new FileSpecification("data.csv", "Embedded data");
doc.EmbeddedFiles.Add(spec);
doc.Save("with-attachment.pdf");关键类
| Class | Purpose |
|---|---|
Document | 根 PDF 对象 |
Document.Open | 从字节数组打开 |
Page | 包含内容和几何的单页 |
PageCollection | 管理文档页面 |
FileSpecification | 文件附件描述符 |