核心文档管理

核心文档管理

核心文档管理

Document 类是 Aspose.PDF FOSS for .NET 的主要入口点。它实现了 IDisposable,并且应在 using 块中使用,以确保所有资源及时释放。


创建新的 PDF 文档

使用 Document.Create() 实例化一个空的 PDF 文档:

using Aspose.Pdf;
using var doc = Document.Create();
doc.Pages.Add();
doc.Save("new-document.pdf");

或者,直接使用 new Document() 构造 Document 实例:

using Aspose.Pdf;
using var doc = new Document();
doc.Pages.Add();
doc.Save("new-document.pdf");

打开现有 PDF 文档

Document.Open 接受一个 byte[]、一个文件路径 string,或一个 Stream

从字节数组打开:

using Aspose.Pdf;
byte[] data = File.ReadAllBytes("input.pdf");
using var doc = Document.Open(data);
Console.WriteLine($"Pages: {doc.Pages.Count}");

从文件路径打开:

using Aspose.Pdf;
using var doc = Document.Open("input.pdf");
Console.WriteLine($"Pages: {doc.Pages.Count}");

Stream 打开:

using Aspose.Pdf;
using var stream = File.OpenRead("input.pdf");
using var doc = Document.Open(stream);
Console.WriteLine($"Pages: {doc.Pages.Count}");

打开受密码保护的 PDF

将密码作为第二个参数传递给任何 Document.Open 重载:

using Aspose.Pdf;
using var doc = Document.Open("protected.pdf", "mypassword");

保存文档

Document.Save 将当前文档写入文件路径或流。
Document.ToArray 直接返回序列化的字节。

保存到文件:

using Aspose.Pdf;
using var doc = Document.Open(File.ReadAllBytes("input.pdf"));
doc.Pages.Add();
doc.Save("output.pdf");

将往返保存到 MemoryStream(来自 snippet_014.cs):

using Aspose.Pdf;
var data = File.ReadAllBytes("input.pdf");
using var doc = Document.Open(data);
var page = doc.Pages[1];
var action = PdfAction.CreateJavaScript("app.alert('Round trip');");
page.Annotations.AddLinkAnnotation(new Rectangle(50, 600, 200, 620), action);
using var ms = new MemoryStream();
doc.Save(ms);
ms.Position = 0;
using var doc2 = Document.Open(ms.ToArray());

序列化为字节数组:

using Aspose.Pdf;
using var doc = Document.Open(File.ReadAllBytes("input.pdf"));
var bytes = doc.ToArray();
File.WriteAllBytes("output.pdf", bytes);

访问页面

页面通过 Document.Pages 访问,它是一个基于 1 的 PageCollection。使用整数索引获取特定的 Page

using Aspose.Pdf;
using var doc = Document.Open(File.ReadAllBytes("input.pdf"));
var page = doc.Pages[1];
Console.WriteLine($"Width: {page.Width}, Height: {page.Height}");
Console.WriteLine($"Rotation: {page.RotateDegrees}");
Console.WriteLine($"Annotations: {page.Annotations.Count}");

访问表单

交互式 AcroForm 字段可通过 Document.Form 获取。在文档可能不包含表单时,访问前请检查 null

using Aspose.Pdf;
using var doc = Document.Open(File.ReadAllBytes("form.pdf"));
if (doc.Form is not null)
{
    foreach (var field in doc.Form.Fields)
    {
        Console.WriteLine($"{field.Name}: {field.Value}");
    }
}

释放文档

Document 实现 IDisposable。始终使用 using 或显式调用 Dispose()

using Aspose.Pdf;
using var doc = Document.Open("input.pdf");
// doc is disposed automatically at the end of the using block.

另请参阅

 中文