在 Python 中创建符合 PDF/3-A 标准的 PDF 并附加 ZUGFeRD 发票
Contents
[
Hide
]
将 ZUGFeRD 附加到 PDF
我们建议遵循以下步骤将 ZUGFeRD 附加到 PDF:
- 导入 Aspose.PDF 库,并为方便起见给它一个别名 ap。
- 定义输入和输出 PDF 文件所在目录的路径。
- 定义将要处理的 PDF 文件的路径。
- 从 path 变量加载 PDF 文件并创建一个 Document 对象。
- 为包含发票元数据的 XML 文件创建一个 FileSpecification 对象。使用 path 变量和描述字符串来创建该 FileSpecification 对象。
- 设置
mime_type和af_relationshipFileSpecification 对象的属性text/xml和ALTERNATIVE,分别。 - 将 fileSpecification 对象添加到 document 对象的嵌入文件集合中。这会将 XML 文件作为发票元数据文件附加到 PDF 文档。
- 将 PDF 文档转换为 PDF/A-3A 格式。使用日志文件的路径,
PdfFormat.PDF_A_3A枚举,以及ConvertErrorAction.DELETE用于转换文档对象的枚举。 - 将带有附加 ZUGFeRD 的 PDF 文档保存。
import sys
import os
import aspose.pdf as ap
def attach_invoice_zugferd_format(infile, invoice, outfile):
document = ap.Document(infile)
# Create a FileSpecification object for the XML file that contains the invoice metadata
description = "Invoice metadata conforming to ZUGFeRD standard"
file_specification = ap.FileSpecification(invoice, description)
# Set the MIME type and the AFRelationship properties of the embedded file
file_specification.mime_type = "text/xml"
file_specification.af_relationship = ap.AFRelationship.ALTERNATIVE
# Add the embedded file to the PDF document's embedded files collection
document.embedded_files.add("factur", file_specification)
# Convert the PDF document to the PDF/A-3A format
log_path = outfile.replace(".pdf", "_log.xml")
document.convert(log_path, ap.PdfFormat.PDF_A_3A, ap.ConvertErrorAction.DELETE)
document.save(outfile)