Python / 在PDF中添加自定义文档属性?

huangapple go评论78阅读模式
英文:

Python / Add custom document properties in a pdf?

问题

有没有办法使用现有的Python模块(如pypdf2、reportlab等)在PDF文件中添加/创建自定义文档属性?

我想在这里添加一个类似于您在此处看到的名称和值:

Python / 在PDF中添加自定义文档属性?

英文:

is there any way to add / create custom document properties in a pdf-file using some of the existing python-modules like pypdf2, reportlab, etc.?

I would like to add here a Name and Value like you can see it here:

Python / 在PDF中添加自定义文档属性?

答案1

得分: 1

你可以使用 PyPDF2 来完成这个任务:

import PyPDF2


def add_custom_property(pdf_path, property_name, property_value):
    with open(pdf_path, "rb") as file:
        pdf_reader = PyPDF2.PdfReader(file)
        pdf_writer = PyPDF2.PdfWriter()

        [pdf_writer.add_page(page) for page in pdf_reader.pages]
        pdf_writer.add_metadata(
            {
                f"/{property_name}": property_value,
                **pdf_reader.metadata,
            }
        )

        output_path = "modified_" + pdf_path
        with open(output_path, "wb") as output_file:
            pdf_writer.write(output_file)


add_custom_property("test.pdf", "institution", "stack overflow")
英文:

You can use PyPdf2 to do that:

import PyPDF2


def add_custom_property(pdf_path, property_name, property_value):
    with open(pdf_path, "rb") as file:
        pdf_reader = PyPDF2.PdfReader(file)
        pdf_writer = PyPDF2.PdfWriter()

        [pdf_writer.add_page(page) for page in pdf_reader.pages]
        pdf_writer.add_metadata(
            {
                f"/{property_name}": property_value,
                **pdf_reader.metadata,
            }
        )

        output_path = "modified_" + pdf_path
        with open(output_path, "wb") as output_file:
            pdf_writer.write(output_file)


add_custom_property("test.pdf", "institution", "stack overflow")

huangapple
  • 本文由 发表于 2023年6月15日 21:16:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76482899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定