Add a bookmark to a PDF with PyPDF2

前端 未结 1 739
野趣味
野趣味 2020-12-18 17:30

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

1条回答
  •  时光说笑
    2020-12-18 17:46

    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
    

    0 讨论(0)
提交回复
热议问题