pythonpypdf

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 PdfFileReader, PdfFileWriter

reader = PdfFileReader("test.pdf")  # open input
writer = PdfFileWriter()  # open output
writer.addPage(reader.getPage(0))  # insert page
writer.addBookmark("Hello, World Bookmark", 0, parent=None)  # add bookmark

Solution

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

    from PyPDF2 import PdfFileReader, PdfFileWriter
    
    writer = PdfFileWriter()  # open output
    reader = PdfFileReader("test.pdf")  # open input
    writer.addPage(reader.getPage(0))  # insert page
    writer.addBookmark("Hello, World Bookmark", 0, parent=None)  # add bookmark
    with open("result.pdf", "wb") as fp:  # creating result pdf JCT
        writer.write(fp)  # writing to result pdf 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:

    writer = PdfFileWriter()  # open output
    reader = PdfFileReader("test.pdf")  # open input
    writer.addPage(reader.getPage(0))  # insert page
    writer.addBookmark("Hello, World Bookmark", 0, parent=None)  # add bookmark
    writer.setPageMode("/UseOutlines")  # This is what tells the PDF to open to bookmarks
    with open("result.pdf", "wb") as fp:  # creating result pdf JCT
        writer.write(fp)  # writing to result pdf JCT