英文:
Python / Add custom document properties in a pdf?
问题
有没有办法使用现有的Python模块(如pypdf2、reportlab等)在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:
答案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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论