May-08-2023, 07:20 PM
I am trying to split a pdf document at the second bookmark level Here is my code:
import os import PyPDF2 # Open the PDF file input_pdf = PyPDF2.PdfFileReader(open('C:\\venv\\inputfile.pdf', 'rb')) # Loop through each bookmark in the PDF for bookmark in input_pdf.getOutlines(): # Check if the bookmark has children (i.e., second level) if isinstance(bookmark, list): # Create a new PDF writer output_pdf = PyPDF2.PdfFileWriter() # Loop through each child bookmark and add the corresponding page to the new PDF for child in bookmark: page_num = child['/Page'] output_pdf.addPage(input_pdf.getPage(page_num)) # Write the new PDF to a file output_filename = bookmark[0]['/Title'] + '.pdf' with open(output_filename, 'wb') as output_file: output_pdf.write(output_file)I get this error:
Error:PS C:\Users\stand> & C:/Users/stand/AppData/Local/Programs/Python/Python311/python.exe c:/venv/TestIt.py
Traceback (most recent call last):
File "c:\venv\TestIt.py", line 19, in <module>
output_pdf.addPage(input_pdf.getPage(page_num))
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\stand\AppData\Local\Programs\Python\Python311\Lib\site-packages\PyPDF2\pdf.py", line 1177, in getPage
return self.flattenedPages[pageNumber]
~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
TypeError: list indices must be integers or slices, not DictionaryObject
PS C:\Users\stand>
Any advice on what I am doing wrong?