我正在尝试使用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
答案 0 :(得分:4)
我运行了你的代码(添加下面的文字来写出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
答案 1 :(得分:0)
感谢 James 的代码。但它只输出一页 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