我正在使用PyPDF2修改一个PDF文档(添加书签)。所以我需要读入整个源PDF文件,并把它写出来,尽可能保持数据的完整性。仅仅将每个页面写入一个新的PDF对象可能不足以保存文档元数据。
PdfFileWriter()
确实有许多复制整个文件的方法:cloneDocumentFromReader
、appendPagesFromReader
和{
如果我使用cloneDocumentFromReader
或appendPagesFromReader
,我会得到一个有效的PDF文件,并且有正确的页数,但是所有页面都是空白的。
如果我使用cloneReaderDocumentRoot
,我将得到一个最小的有效PDF文件,但是没有页面或数据。
This has been asked before,但没有成功的答案。 其他问题也问过Blank pages in PyPDF2,但我不能应用给出的答案。
我的代码是:
def bookmark(incomingFile):
fileObj = open(incomingFile, 'rb')
output = PdfFileWriter()
input = PdfFileReader(fileObj)
output.appendPagesFromReader(input)
#output.cloneDocumentFromReader(input)
myTableOfContents = [
('Page 1', 0),
('Page 2', 1),
('Page 3', 2)
]
# output.addBookmark(title, pagenum, parent=None, color=None, bold=False, italic=False, fit='/Fit')
for title, pagenum in myTableOfContents:
output.addBookmark(title, pagenum, parent=None)
output.setPageMode("/UseOutlines")
outputStream = open(incomingFile, "wb")
output.write(outputStream)
outputStream.close()
fileObj.close()
当PyPDF2不能向PdfFileWriter对象添加书签时,我往往会出错,因为它没有任何页面或类似的页面。
我也为此绞尽脑汁,最后发现PyPDF2有这个issue。 基本上,我将this answer's代码复制到
C:\ProgramData\Anaconda3\lib\site-packages\PyPDF2\pdf.py
(这将取决于您的发行版)中cloneDocumentFromReader
函数的第382行。在之后,我可以用
writer.cloneDocumentFromReader(pdf)
将reader
页附加到writer
中,并且在我的例子中,可以更新PDF元数据(主题、关键字等)。在希望这对你有帮助
相关问题 更多 >
编程相关推荐