如何在 TypeScript 中使用 Core PDF API
本指南展示了如何使用针对 TypeScript 的 Aspose.PDF FOSS 打开、创建、编辑、拆分和保存 PDF 文档。Document 和 Page 类是库中所有操作的入口——打开和创建文件、就地编辑页面、拆分和合并文档以及保存结果。它仅需要 Node.js 22 或更高版本。
分步指南
步骤 1:安装软件包
git clone https://github.com/aspose-pdf-foss/Aspose.PDF-FOSS-for-TypeScript.git
cd Aspose.PDF-FOSS-for-TypeScript
npm install
npm run build通过在新的 TypeScript 文件中导入 Document 类来验证安装——一旦软件包安装完成,此行应能正常解析且不报错:
import { Document } from '@asposefoss/pdf';步骤 2:导入所需类
导入 Document 以加载或创建 PDF,若计划从头开始文档,则使用 PageFormat:
import { Document, PageFormat } from '@asposefoss/pdf';步骤 3:打开已有 PDF 并编辑页面
Document.OpenFile() 从文件路径打开 PDF;Document.Open() 接受内存中的 Uint8Array。页面可以就地检查和编辑,Document.WriteTo() 将结果写回。
import { Document } from '@asposefoss/pdf';
// Open from disk (or Document.Open(uint8array) for in-memory data)
const doc = Document.OpenFile('input.pdf');
// Inspect and edit pages
const pages = doc.Pages;
console.log(pages.length);
pages[0].Rotate = 90;
doc.RemovePage(2); // 1-based page number
doc.Reorder([3, 1, 2]);
// Save
doc.WriteTo('output.pdf'); // or: const bytes = doc.Save();
步骤 4:从头创建新 PDF
Document.New() 在指定的 PageFormat 上启动一个空白文档。Page.AddText() 放置定位文本,Document.AddPage() 追加更多页面。
import { Document, PageFormat } from '@asposefoss/pdf';
const doc = Document.New(PageFormat.A4); // one blank A4 page
doc.Pages[0].AddText('Hello', 72, 720, { fontSize: 14 });
doc.AddPage(PageFormat.A4.landscape()); // append more as you go
doc.WriteTo('scratch.pdf');步骤 5:拆分、提取和合并页面
Document.Split() 为每页返回一个 Document。Document.ExtractPages() 接受基于 1 的、允许重复的页码列表,并返回仅包含这些页面的新 Document。Document.Append() 和 Document.InsertPage() 在文档之间复制页面,Document.Merge() 将多个文档合并为一个。
const parts = doc.Split(); // one Document per page
const chapter = doc.ExtractPages([3, 4, 5]); // subset (1-based, repeats allowed) as a new Document
docA.Append(docB); // copy all of docB's pages onto docA
docA.InsertPage(1, docB.Pages[0]); // copy a single page across documents
常见问题及解决方案
Document.OpenFile() throws InvalidPasswordError. PDF受密码保护,但未提供密码(或提供了错误的密码)。Pass { password: '...' } to Document.OpenFile() / Document.Open().
RemovePage() or ExtractPages() 删除或提取了错误的页面。 这些方法使用基于1的页码,而 doc.Pages 是一个普通的基于0的数组——这两种索引方式很容易混淆。
WriteTo() 输出比预期的要大。 默认保存不使用xref/object-stream压缩。Pass { compressed: true } to Document.WriteTo() 以启用它。
对…所做的编辑 doc.Pages[i] 不会出现在已保存的文件中。 页面编辑必须在调用之前进行 Document.WriteTo() / Document.Save() — 没有单独的“commit”步骤,但在保存后进行的编辑将不会反映在已写入磁盘的文件中。
常见问题
如何从内存缓冲区加载 PDF,而不是从文件路径?
将 Uint8Array 传递给 Document.Open(),而不是将路径传递给 Document.OpenFile()。
我该如何旋转页面?
将 page.Rotate 设置为 90、180 或 270,然后使用 Document.WriteTo() 保存文档。
我可以将单页从一个文档复制到另一个文档吗?
是的 — Document.InsertPage(at, sourcePage) 会在给定的基于 1 的位置复制另一文档中的单页,而不会复制整个文档。
Document.ExtractPages() 允许同一页面出现两次吗?
是的。传递给 Document.ExtractPages() 的页码列表允许重复,因此相同的源页面可以在结果中出现多次。