Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding nested bookmarks to a PDF using PyPDF2

Tags:

python

pdf

pypdf2

The documentation for PyPDF2 states that it's possible to add nested bookmarks to PDF files, and the code appears (upon reading) to support this.

Adding a bookmark to the root tree is easy (see code below), but I can't figure out what I need to pass as the parent argument to create a nested bookmark. I want to create a structure something like this:

Group A
    Page 1
    Page 2
Group A
    Page 3
    Page 4 

Is this possible?

Sample code to add a bookmark to the root of the tree:

#!/usr/bin/env python
from PyPDF2 import PdfFileWriter, PdfFileReader
output = PdfFileWriter() # open output
input = PdfFileReader(open('input.pdf', 'rb')) # open input
output.addPage(input.getPage(0)) # insert page
output.addBookmark('Hello, World', 0, parent=None) # add bookmark

PyPDF2 addBookmark function: https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/pdf.py#L517

like image 948
Snorfalorpagus Avatar asked Sep 17 '13 17:09

Snorfalorpagus


People also ask

How do you create PDF Bookmarks?

Select the bookmark under which you want to place the new bookmark. If you don't select a bookmark, the new bookmark is automatically added at the end of the list. Choose Tools > Edit PDF > More > Add Bookmark. In the Bookmarks panel, type or edit the name of the new bookmark.

What is the use of PyPDF2?

PyPDF2: It is a python library used for performing major tasks on PDF files such as extracting the document-specific information, merging the PDF files, splitting the pages of a PDF file, adding watermarks to a file, encrypting and decrypting the PDF files, etc.


1 Answers

The addBookmark method returns a reference to the bookmark it created, which can be used as the parent to another bookmark. e.g.

from PyPDF2 import PdfReader, PdfWriter

writer = PdfWriter()
reader = PdfReader("introduction.pdf")
writer.add_page(reader.pages[0])

reader2 = PdfReader("hello.pdf")
writer.add_page(reader2.pages[0])

parent = writer.add_bookmark("Introduction", 0)  # add parent bookmark
writer.add_bookmark("Hello, World", 0, parent)  # add child bookmark
like image 115
Snorfalorpagus Avatar answered Oct 04 '22 21:10

Snorfalorpagus