6

我正在尝试使用 PyPDF2 向 PDF 添加书签。我运行以下没有问题。但是永远不会创建书签。关于我做错了什么的任何想法。PDF 有 2 页长。

from PyPDF2 import PdfFileWriter, PdfFileReader

output = PdfFileWriter() # open output
input = PdfFileReader(open('test.pdf', 'rb')) # open input
output.addPage(input.getPage(0)) # insert page
output.addBookmark('Hello, World Bookmark', 0, parent=None) # add bookmark
4

2 回答 2

11

我运行了您的代码(在其下方添加文本以写出 pdf)并发现实际上已创建了一个书签。

output = PdfFileWriter() # open output
input = PdfFileReader(open('test.pdf', 'rb')) # open input
output.addPage(input.getPage(0)) # insert page
output.addBookmark('Hello, World Bookmark', 0, parent=None) # add bookmark
outputStream = file('result.pdf','wb') #creating result pdf JCT
output.write(outputStream) #writing to result pdf JCT
outputStream.close() #closing result JCT

检查结果中的书签面板。拥有书签不会自动导致 PDF 打开到书签面板。

要使用 PyPDF2 打开书签面板,请添加一行:

output = PdfFileWriter() # open output
input = PdfFileReader(open('test.pdf', 'rb')) # open input
output.addPage(input.getPage(0)) # insert page
output.addBookmark('Hello, World Bookmark', 0, parent=None) # add bookmark
output.setPageMode("/UseOutlines") #This is what tells the PDF to open to bookmarks
outputStream = file('result.pdf','wb') #creating result pdf JCT
output.write(outputStream) #writing to result pdf JCT
outputStream.close() #closing result JCT
于 2017-03-02T13:20:35.453 回答
3

感谢詹姆斯的代码。但它只输出一页pdf文件,并没有显示如何添加多个书签。这是他这样做的代码的修订版。

from PyPDF2 import PdfFileWriter, PdfFileReader

output = PdfFileWriter() # open output
input = PdfFileReader(open('test.pdf', 'rb')) # open input

n = input.getNumPages()

for i in range(n):
  output.addPage(input.getPage(i)) # insert page

output.addBookmark('Hello, World Bookmark', 0, parent=None) # add a bookmark on the first page
par = output.addBookmark('Second Bookmark', 5, parent=None) # add a bookmark on the sixth page
output.addBookmark('Third Bookmark', 7, parent=par) # add a child bookmark on the eighth page

outputStream = open('result.pdf','wb') #creating result pdf JCT
output.write(outputStream) #writing to result pdf JCT
outputStream.close() #closing result JCT
于 2021-07-04T07:04:27.197 回答