使用案例
本指南展示了 Aspose.PDF FOSS 在 TypeScript 场景下的真实用例,涵盖文档生成、审阅工作流、脱敏、 安全分发、基于表单的数据收集以及带标签的网页发布。运行本指南需要 Node.js 22 或更高版本。
文档生成与页面组装
通过在指定的 PageFormat 上启动一个空白的 Document,使用 Page.AddText() 放置文本,并追加后续页面,从头构建 PDF。此模式是发票生成、证书打印和报告生产流水线的基础:
import { Document, PageFormat } from '@asposefoss/pdf';
const doc = Document.New(PageFormat.A4); // one blank A4 page
doc.Pages[0].AddText('Monthly Report', 72, 720, { fontSize: 14 });
doc.AddPage(PageFormat.A4.landscape()); // append more as you go
doc.WriteTo('report.pdf');使用批注进行审阅和标记
对共享草稿进行高亮、便签和自由文本批注标记,获批后将审阅结果合并为最终的、不可编辑页面:
const draft = Document.OpenFile('draft.pdf');
const page = draft.Pages[0];
page.AddHighlight({ quads: [72, 700, 300, 700, 72, 685, 300, 685], color: [1, 1, 0] });
const note = page.AddFreeText({
rect: [320, 685, 500, 715],
contents: 'Please confirm this figure before publishing.',
fontSize: 10,
});
// Once the review is resolved, bake the comment into static content:
note.Flatten();
draft.WriteTo('reviewed.pdf');在分发前对敏感数据进行脱敏
在文档离开组织之前,标记并随后彻底删除敏感字段——员工编号、银行账号——:
const memo = Document.OpenFile('internal-memo.pdf');
const page2 = memo.Pages[0];
page2.AddRedact({
rect: [220, 548, 460, 566],
fill: [0, 0, 0],
overlayText: '[REDACTED]',
align: 'center',
fontSize: 9,
textColor: [1, 1, 1],
});
page2.ApplyRedactions(); // destructive — the covered content is gone
memo.WriteTo('memo-for-distribution.pdf');为分发而安全加密和签署文档
对完成的文档进行认证,然后使用特定收件人的证书加密,使只有该收件人能够打开:
async function secureAndDistribute(sourcePath: string): Promise<void> {
const doc = Document.OpenFile(sourcePath);
await doc.Certify(
{ certificate: authorCert, privateKey: authorKey },
{ permissions: 'form-fill', reason: 'Certifying the final report' },
);
const encryptedBytes = doc.Save({
encrypt: {
recipients: [{ certificate: recipientCertPem }],
algorithm: 'aes256',
permissions: { copying: false },
},
});
writeFileSync('report-secure.pdf', encryptedBytes);
}使用可填写表单收集结构化数据
构建一个可填写的 intake 表单,然后从返回的副本中读取提交的数值——这对于在没有单独表单提交服务器的情况下处理已填写的申请表非常有用:
const template = Document.New(PageFormat.A4);
const form = template.Form;
const pageNum = template.Pages[0].Number;
form.AddTextField({ page: pageNum, rect: [200, 670, 450, 690], name: 'FullName' });
form.AddCheckbox({ page: pageNum, rect: [200, 630, 218, 648], name: 'Subscribe' });
template.WriteTo('intake-form.pdf');
// Later, after the form comes back filled in:
const submitted = Document.OpenFile('intake-form-filled.pdf');
for (const field of submitted.Form.Fields) {
console.log(field.FullName, '=', field.Value);
}发布已标记的、适合网络的文档
标记文档的逻辑结构,然后导出为语义 HTML,使其在网页阅读器中能够正确重新排版——导出过程遍历标记阶段构建的相同结构树:
const source = Document.OpenFile('report.pdf');
const report = source.AutoTag({ title: true });
console.log(`tagged: ${report.headings} heading(s), ${report.paragraphs} paragraph(s)`);
const html = source.ToHtml(); // reflowable markup, built from the structure tree
writeFileSync('report.html', html, 'utf8');