Skip to content
Demo示例FAQ

PDF 生成模板编辑器

开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。

查看 GitHub
Android Guides Attachments

附件管理 ​

文档附件是嵌入 PDF 的文件,可通过 CPDFDocument 添加、枚举和删除,并通过 CPDFAttachment 读取或导出。以下示例中的 document 均为已打开的文档。

添加附件 ​

sourcePath 为可读取的本地文件路径,name 为附件名称:

java
import com.compdfkit.core.attachment.CPDFAttachment;

CPDFAttachment attachment = document.addAttachment(sourcePath, "specification.txt");
if (attachment != null) {
    try {
        boolean updated = attachment.setDescription("项目规格说明");
        // 根据 updated 检查描述是否写入成功。
    } finally {
        attachment.close();
    }
} else {
    // 添加失败,检查文档及源文件。
}

添加、删除、修改描述或写入数据后,需要 保存文档 才会持久化。释放附件句柄不会删除文档中的附件。

枚举附件 ​

java
import com.compdfkit.core.attachment.CPDFAttachmentInfo;

int count = document.getAttachmentCount();
for (CPDFAttachmentInfo info : document.getAttachmentList()) {
    int attachmentIndex = info.getIndex();
    String name = info.getName();
    String description = info.getDescription();
    String mimeType = info.getMimeType();
    long sizeBytes = info.getSizeBytes();
    // 展示元数据,并保留 attachmentIndex 供后续操作使用。
}

附件位于 PDF 名称树中,枚举顺序不保证与添加顺序一致。应使用 info.getIndex() 获取附件,不能将列表位置直接作为附件索引。添加或删除后重新读取列表,不继续使用旧列表中的索引。

读取和导出 ​

attachmentIndex 来自当前列表中的 CPDFAttachmentInfo.getIndex();outputPath 为可写的输出文件路径,先创建父目录:

java
CPDFAttachment attachment = document.getAttachment(attachmentIndex);
if (attachment != null) {
    try {
        boolean exported = attachment.saveTo(outputPath);
        // 根据 exported 检查导出结果。
    } finally {
        attachment.close();
    }
}
接口用途
read()将附件内容读取为 byte[],大文件需注意内存占用
saveTo(String)、saveTo(File)导出到本地文件
writeTo(OutputStream)写入应用提供的输出流,调用方管理流的关闭并处理 IOException
write(byte[])替换附件数据,检查返回值并保存文档
setDescription(String)修改附件描述,检查返回值并保存文档

附件操作应在后台线程执行。读取失败时检查返回值,不将失败结果直接作为有效附件内容使用。

删除附件 ​

使用当前有效索引删除:

java
boolean removed = document.removeAttachment(attachmentIndex);
if (removed) {
    // 重新读取附件列表,再保存文档。
}

也可在有效的附件对象上调用 remove()。附件删除或文档关闭后,不继续使用原附件句柄。所有取得的 CPDFAttachment 都应及时调用 close(),并在文档关闭前结束相关操作。