2017-03-02 88 views
0

我正在嘗試使用PyPDF2爲PDF添加書籤。我運行以下沒有問題。但書籤永遠不會創建。任何想法我做錯了。該PDF爲2頁長。用PyPDF2添加PDF書籤

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

[使用PyPDF2添加書籤]的可能的複製(http://stackoverflow.com/questions/18855907/adding-bookmarks -using-pypdf2) –

+0

@ShubhamNamdeo那個問題,沒有幫助;在答案中有錯誤 – rmp2150

回答

1

我跑你的代碼(將它下面的文字寫出來的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