在 Python 中创建符合 PDF/3-A 标准的 PDF 并附加 ZUGFeRD 发票

将 ZUGFeRD 附加到 PDF

我们建议遵循以下步骤将 ZUGFeRD 附加到 PDF:

  1. 导入 Aspose.PDF 库,并为方便起见给它一个别名 ap。
  2. 定义输入和输出 PDF 文件所在目录的路径。
  3. 定义将要处理的 PDF 文件的路径。
  4. 从 path 变量加载 PDF 文件并创建一个 Document 对象。
  5. 为包含发票元数据的 XML 文件创建一个 FileSpecification 对象。使用 path 变量和描述字符串来创建该 FileSpecification 对象。
  6. 设置 mime_typeaf_relationship FileSpecification 对象的属性 text/xmlALTERNATIVE,分别。
  7. 将 fileSpecification 对象添加到 document 对象的嵌入文件集合中。这会将 XML 文件作为发票元数据文件附加到 PDF 文档。
  8. 将 PDF 文档转换为 PDF/A-3A 格式。使用日志文件的路径, PdfFormat.PDF_A_3A 枚举,以及 ConvertErrorAction.DELETE 用于转换文档对象的枚举。
  9. 将带有附加 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)