附件
福昕 PDF SDK 安卓版通过 Core SDK 提供了文档附件(Embedded Files)的嵌入、提取、遍历和删除能力。文档附件允许将任意文件以"类似邮件附件"的方式封装进 PDF 文档中。
文档附件 vs 文件附件注释
本文档介绍的是文档级附件(Embedded Files),存储在文档名称树中。文件附件注释(File Attachment Annotation)是页面级的注释类型,将在注释文档中单独介绍。
UI Extensions 内置附件面板
如果您使用的是完整阅读器(UI Extensions),文档附件功能已内置在侧边面板中,用户可直接通过面板查看、添加和导出附件,无需额外编码。
核心类
| 类 | 说明 |
|---|---|
Attachments | 文档附件集合,管理嵌入文件的增删查改,支持便捷方法 addFromFilePath() 和 extractEmbeddedFileTo() |
FileSpec | 文件规范对象,描述嵌入文件的属性(文件名、大小、时间等),支持通过文件路径或流嵌入/导出 |
PDFNameTree | PDF 名称树,Attachments 基于 e_EmbeddedFiles 类型的名称树构建 |
示例:嵌入文件到 PDF 文档
java
import com.foxit.sdk.pdf.PDFDoc;
import com.foxit.sdk.pdf.Attachments;
import com.foxit.sdk.pdf.FileSpec;
import com.foxit.sdk.pdf.objects.PDFNameTree;
PDFDoc doc = new PDFDoc("path/to/Sample.pdf");
doc.load(null);
PDFNameTree nameTree = new PDFNameTree(doc, PDFNameTree.e_EmbeddedFiles);
Attachments attachments = new Attachments(doc, nameTree);
// 方式一:通过 FileSpec 嵌入
FileSpec fileSpec = new FileSpec(doc);
fileSpec.setFileName("report.xlsx");
fileSpec.embed("/sdcard/report.xlsx");
attachments.addEmbeddedFile("report.xlsx", fileSpec);
// 方式二:直接从文件路径嵌入(便捷方法)
attachments.addFromFilePath("image.png", "/sdcard/image.png");
doc.saveAs("path/to/output.pdf", PDFDoc.e_SaveFlagNormal);
1
示例:遍历并导出所有附件
java
PDFNameTree nameTree = new PDFNameTree(doc, PDFNameTree.e_EmbeddedFiles);
Attachments attachments = new Attachments(doc, nameTree);
int count = attachments.getCount();
for (int i = 0; i < count; i++) {
String key = attachments.getKey(i);
FileSpec fileSpec = attachments.getEmbeddedFile(key);
if (fileSpec != null && !fileSpec.isEmpty()) {
String fileName = fileSpec.getFileName();
// 导出附件
fileSpec.exportToFile("/sdcard/exports/" + fileName);
}
}
1
示例:删除附件
java
// 按键名删除单个附件
attachments.removeEmbeddedFile("report.xlsx");
// 删除所有附件
attachments.removeAllEmbeddedFiles();
1
API 参考
Attachments、FileSpec 的完整接口说明请参阅 API 手册。