在 Java 中向 PDF 添加附件
Contents
[
Hide
]
要将文件附加到 PDF,加载源文档,创建一个 FileSpecification,将其添加到嵌入式文件集合中,然后保存结果。
将附件添加到 PDF 文档
当需要将外部文件嵌入到现有 PDF 时使用此示例。
- 打开源 PDF Document。
- 创建一个 FileSpecification 对于您想要嵌入的文件。
- 将文件规范添加到
EmbeddedFiles收集并保存更新后的文档。
public static void addAttachments(Path inputFile, Path attachmentPath, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
FileSpecification fileSpecification = new FileSpecification(attachmentPath.toString(), "Sample text file");
document.getEmbeddedFiles().add(attachmentPath.getFileName().toString(), fileSpecification);
document.save(outputFile.toString());
}
}