PDF 外观
本指南展示了如何使用 org.aspose.pdf.facades 包中的面向任务的外观类。每个外观遵循相同的生命周期:bindPdf() → 操作 → save()。您将学习如何扁平化注释、管理书签、替换文本、加密文档、提取文本以及添加页码。
外观模式
所有位于 org.aspose.pdf.facades 中的外观类都遵循相同的生命周期:bindPdf() → 操作 → save()。它们接受文件路径、流或 Document 对象。
PdfAnnotationEditor
对整个文档的注释进行扁平化、删除或计数。flattenAnnotations() 将所有注释合并到页面内容流中,使其永久且不可编辑:
try (PdfAnnotationEditor editor = new PdfAnnotationEditor()) {
editor.bindPdf("input.pdf");
editor.flattenAnnotations();
editor.save("output.pdf");
}deleteAnnotations(annotationType) 按名称移除特定的注释类型。
PdfBookmarkEditor
创建和删除 PDF 大纲条目(书签)。deleteBookmarks() 在保存之前会从已绑定的文档中删除所有大纲条目:
try (PdfBookmarkEditor editor = new PdfBookmarkEditor()) {
editor.bindPdf("input.pdf");
editor.deleteBookmarks();
editor.save("output.pdf");
}PdfContentEditor
在整个文档或特定页面的 PDF 内容流中替换文本。replaceText(searchString, replacement) 查找并替换所有匹配的文本字符串:
try (PdfContentEditor editor = new PdfContentEditor()) {
editor.bindPdf("template.pdf");
editor.replaceText("{{Name}}", "John Smith");
editor.save("output.pdf");
}PdfFileSecurity
使用 AES-256 加密文档,并通过 DocumentPrivilege 设置访问权限。encryptFile(userPass, ownerPass, privilege, keySize) 应用加密并将结果写入配置的输出文件:
try (PdfFileSecurity security = new PdfFileSecurity("input.pdf", "out.pdf")) {
DocumentPrivilege priv = DocumentPrivilege.getForbidAll();
priv.setAllowPrint(true);
security.encryptFile("user", "owner", priv, KeySize.x256);
}PdfExtractor
逐页从 PDF 文档中提取文本。调用 extractText() 后,使用 hasNextPageText() 和 getNextPageText() 迭代每页的提取内容:
try (PdfExtractor extractor = new PdfExtractor()) {
extractor.bindPdf("document.pdf");
extractor.extractText();
while (extractor.hasNextPageText()) {
String text = extractor.getNextPageText();
System.out.println(text);
}
}PdfFileStamp
使用 addPageNumber(FormattedText) 为 PDF 页面添加页码戳。传入包含页码标签的 FormattedText 实例:
try (PdfFileStamp stamp = new PdfFileStamp("in.pdf", "out.pdf")) {
stamp.addPageNumber(new FormattedText("Page #"));
stamp.close();
}使用 addHeader(FormattedText, float) 或 addFooter(FormattedText, float) 在每页距离顶部或底部的指定边距处添加循环文本。