文档管理

文档管理

Document 是 Aspose.PDF FOSS for .NET 中的根对象。
它表示一个
完整的 PDF 文件,并提供对页面、元数据、表单字段以及所有
其他 PDF 结构的访问。
使用 Document.Open 打开现有文件并创建新的
文件使用 Document 构造函数。


打开和创建文档

// Open from a byte array
using var doc = Document.Open(File.ReadAllBytes("input.pdf"));

// Open from a file path
using var doc2 = new Document("input.pdf");

// Create a new empty document
using var newDoc = new Document();
newDoc.Pages.Add();
newDoc.Save("new.pdf");

页面操作

PageCollection 管理文档的页面。通过基于 1 的索引访问页面,添加新页面或删除现有页面。

using var doc = Document.Open(pdfBytes);

// Access first page
var page = doc.Pages[1];

// Add a blank page
var newPage = doc.Pages.Add();

// Get page count
int count = doc.Pages.Count;

页面几何

每页定义了多个边界框。使用 Page 上的 setter 方法来调整它们。

var page = doc.Pages[1];
page.SetMediaBox(new Rectangle(0, 0, 612, 792));
page.SetCropBox(new Rectangle(36, 36, 576, 756));
page.SetRotation(90);

保存文档

保存到文件路径、流或字节数组。

// Save to file
doc.Save("output.pdf");

// Save to stream
using var ms = new MemoryStream();
doc.Save(ms);

文件附件

FileSpecification 表示 PDF 中的嵌入文件附件。

var spec = new FileSpecification("data.csv", "Embedded data file");
doc.EmbeddedFiles.Add(spec);

图像印章

ImageStamp 在页面的指定位置覆盖栅格图像。

var stamp = new ImageStamp("logo.png");
stamp.Put(doc.Pages[1]);
doc.Save("stamped.pdf");

运算符集合

OperatorCollection 在每页上保存原始内容流操作符。将其用于低级内容检查或操作。

var ops = doc.Pages[1].Contents;
foreach (var op in ops)
{
    // Inspect each operator
}

技巧与最佳实践

  • Document 包装在 using 语句中,以及时释放文件句柄。
  • 使用 Document.Open(byte[]) 进行内存工作流,以避免文件锁定问题。
  • 在添加内容之前修改页面框(MediaBox、CropBox),以确保坐标空间正确。
  • 在所有修改完成后仅调用一次 Save —— 多次保存虽然更安全,但速度更慢。
  • 使用 PageCollection.Accept(AnnotationSelector) 对所有页面的批注进行批量处理。

常见问题

IssueCauseFix
Document.Open 在有效 PDF 上抛出异常文件已使用密码加密在构造函数中提供 password 参数
构造后页数为 0新的 Document() 初始为空调用 doc.Pages.Add() 添加空白页
保存的文件大于预期图像或字体被多次嵌入使用优化(参见 Conversion and Optimization guide)
Pages[0] 抛出索引错误页面是基于 1 的,而不是基于 0 的对第一页使用 Pages[1]

常见问题

如何合并两个 PDF 文档?

使用 Facades API 中的 PdfFileEditor.Concatenate,或使用 PageCollection 手动将页面从一个文档复制到另一个文档。

我可以从 URL 或流中打开 PDF 吗?

是的。先将 URL 内容读取到 byte[],然后将其传递给 Document.Open(byte[])

我该如何删除页面?

调用 doc.Pages.Delete(pageNumber),其中 pageNumber 为基于 1 的。

Document 是线程安全的吗?

不。每个线程应该使用各自的 Document 实例。


API 参考摘要

Class / MethodDescription
Document根 PDF 对象;包含页面、元数据和表单字段
Document.Open用于从字节数组打开 PDF 的静态工厂
Document.Save将文档序列化为文件或流
Page单个 PDF 页面,包含内容、注释和几何信息
Page.SetMediaBox定义页面媒体框
Page.SetCropBox定义可见裁剪区域
Page.SetRotation将页面旋转 0、90、180 或 270 度
PageCollection文档中页面的有序集合
PageCollection.Add追加空白页
OperatorCollection页面的原始内容流操作符
FileSpecification嵌入式文件附件描述符
ImageStamp页面的图像覆盖印章
XFormCollection文档中可重用的表单 XObject

另请参阅

 中文