Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...