Adding Bookmarks Using PyPDF2

The documentation for PyPDF2 states that you can add sub-bookmarks to PDF files, and the code appears (after reading) to support this.

Adding a bookmark to the root tree is easy (see the code below), but I cannot figure out what I need to pass as a 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 it possible?

Sample code for adding bookmarks to the root of a 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 

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

+7
python pdf
source share
1 answer

The addBookmark method returns a link to the created bookmark, which can be used as the parent for another bookmark. eg.

 #!/usr/bin/env python from PyPDF2 import PdfFileWriter, PdfFileReader output = PdfFileWriter() input1 = PdfFileReader(open('introduction.pdf', 'rb')) output.addPage(input1.getPage(0)) input2 = PdfFileReader(open('hello.pdf', 'rb')) output.addPage(input2.getPage(0)) parent = output.addBookmark('Introduction', 0) # add parent bookmark output.addBookmark('Hello, World', 0, parent) # add child bookmark 
+8
source share

All Articles