Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
916 views
in Technique[技术] by (71.8m points)

python - Add a bookmark to a PDF with PyPDF2

I'm trying to add a bookmark to a PDF using PyPDF2. I run the following with no problems. But a bookmark is never created. Any thoughts on what I'm doing wrong. The PDF is 2 pages long.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I ran your code (adding the text below it to write out the pdf) and found a bookmark was, in fact, created.

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

Check the bookmarks panel in your result. Having bookmarks doesn't automatically cause a PDF to open to the bookmarks panel.

To make it open to the bookmarks panel with PyPDF2, add one line:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...