使用pyobj写入元数据

2024-09-24 08:29:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用以下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"

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

^{pr2}$

原始文件包含以下元数据:

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

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


Tags: 文件the数据fromtestimporturlpdf
2条回答

免责声明:我对Python完全陌生,但对PDF是个老手。在

为了避免破坏所有现有属性,您需要从pdfDoc.documentAttributes开始attrs,而不是{}。setDocumentAttributes几乎可以肯定是一个覆盖而不是合并(在这里给出您的输出)。在

其次,所有的PDFDocument*Attribute常量都是PDFDocument的一部分。毫无疑问,我对Python的无知是显而易见的,但是您不应该将它们作为属性而不是纯粹的变量来引用吗?像这样:

attrs[PDFDocument.PDFDocumentTitleAttribute] = "THIS IS THE TITLE"

你可以分配给PDFDocumentTitleAttribute让我相信它不是一个常量。在

如果我是对的,你的属性将试图为一个空键分配大量的值。我的Python很弱,所以我不知道你该怎么检查它。在调用pdfDoc.setDocumentAttributes_()之前检查attrs应该很有启发性。在

马克是在正确的轨道上,但有几个特点,应该加以说明。在

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

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

现在您可以像以前那样修改attrs。不需要像Mark建议的那样编写PDFDocument.PDFDocumentTitleAttribute,因为它不起作用,PDFDocumentTitleAttribute被声明为模块级常量,所以只需像您在自己的代码中那样做。在

以下是对我有用的完整代码:

^{pr2}$

相关问题 更多 >