在 Python 中向 PDF 添加附件
Contents
[
Hide
]
附件可以包含各种信息,且可以是多种文件类型。本文解释了如何向 PDF 文件添加附件。
当需要将支持的源文件、电子表格、图像或相关文档与主 PDF 一起打包时,使用嵌入式 PDF 附件。
- 创建一个新的 Python 项目。
- 导入 Aspose.PDF 包
- 创建一个 文档 对象。
- 创建一个 FileSpecification 包含您正在添加的文件及文件描述的对象。
- 添加 FileSpecification 对象到 文档 对象的 EmbeddedFileCollection 集合,带有集合的 添加 方法。
这 EmbeddedFileCollection 集合包含 PDF 文件中的所有附件。以下代码片段向您展示如何在 PDF 文档中添加附件。
from os import path
import aspose.pdf as ap
def add_attachments(infile, attachment_path, outfile):
with ap.Document(infile) as document:
file_spec = ap.FileSpecification(attachment_path, "Sample text file")
document.embedded_files.add(path.basename(attachment_path), file_spec)
document.save(outfile)