python - 使用 pyobjc 将元数据写入 pdf

标签 python cocoa pdf pyobjc pdfkit

我正在尝试使用以下 python 代码将元数据写入 pdf 文件:

from Foundation import *
from Quartz import *

url = NSURL.fileURLWithPath_("test.pdf")
pdfdoc = PDFDocument.alloc().initWithURL_(url)
assert pdfdoc, "failed to create document"

print "reading pdf file"

attrs = {}
attrs[PDFDocumentTitleAttribute] = "THIS IS THE TITLE"
attrs[PDFDocumentAuthorAttribute] = "A. Author and B. Author"

PDFDocumentTitleAttribute = "test"

pdfdoc.setDocumentAttributes_(attrs)
pdfdoc.writeToFile_("mynewfile.pdf")   

print "pdf made"

这似乎工作正常(控制台没有错误),但是当我检查文件的元数据时,它如下所示:

PdfID0:
242b7e252f1d3fdd89b35751b3f72d3
PdfID1:
242b7e252f1d3fdd89b35751b3f72d3
NumberOfPages: 4

并且原始文件具有以下元数据:

InfoKey: Creator
InfoValue: PScript5.dll Version 5.2.2
InfoKey: Title
InfoValue: Microsoft Word - PROGRESS  ON  THE  GABION  HOUSE Compressed.doc
InfoKey: Producer
InfoValue: GPL Ghostscript 8.15
InfoKey: Author
InfoValue: PWK
InfoKey: ModDate
InfoValue: D:20101021193627-05'00'
InfoKey: CreationDate
InfoValue: D:20101008152350Z
PdfID0: d5fd6d3960122ba72117db6c4d46cefa
PdfID1: 24bade63285c641b11a8248ada9f19
NumberOfPages: 4

所以问题是,它没有附加元数据,而是清除了以前的元数据结构。我需要做什么才能让它工作?我的目标是附加引用管理系统可以导入的元数据。

最佳答案

Mark 的方向是正确的,但有一些特殊情况需要考虑。

首先,他是正确的,pdfdoc.documentAttributes 是一个包含文档元数据的 NSDictionary。你想修改它,但请注意 documentAttributes 给你一个 NSDictionary,它是不可变的。您必须将其转换为 NSMutableDictionary,如下所示:

attrs = NSMutableDictionary.alloc().initWithDictionary_(pdfDoc.documentAttributes())

现在您可以像以前一样修改attrs。没有必要按照 Mark 的建议编写 PDFDocument.PDFDocumentTitleAttribute,那是行不通的,PDFDocumentTitleAttribute 被声明为模块级常量,所以照你做的做在您自己的代码中。

这是适合我的完整代码:

from Foundation import *
from Quartz import *

url = NSURL.fileURLWithPath_("test.pdf")
pdfdoc = PDFDocument.alloc().initWithURL_(url)

attrs = NSMutableDictionary.alloc().initWithDictionary_(pdfdoc.documentAttributes())
attrs[PDFDocumentTitleAttribute] = "THIS IS THE TITLE"
attrs[PDFDocumentAuthorAttribute] = "A. Author and B. Author"

pdfdoc.setDocumentAttributes_(attrs)
pdfdoc.writeToFile_("mynewfile.pdf")

关于python - 使用 pyobjc 将元数据写入 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4100405/

相关文章:

python - 列表中的重复元素

iphone - 捆绑 i386 和 arm6/7 的可执行文件

cocoa - 使用 NSManagedObjectContext 的 objectWithID : 的 'proper' 方法是什么

java - iTextPDF 5.5.0 BouncyCasSTLe 依赖问题

php - DOMPDF 中 float 的解决方法

python - 在 Django 中测试 url 重定向

python - 将工具提示参数与 python 破折号 slider 一起使用时出错

macos - dateFormatter 在瑞典返回 nil 的 NSDate

c# mvc pdf 下载在 android chrome 上失败

python - 将输入转换为字符串和两个 float