Python Forum
Splitting PDF at Bookmark level 2
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Splitting PDF at Bookmark level 2
#1
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?
Reply


Messages In This Thread
Splitting PDF at Bookmark level 2 - by standenman - May-08-2023, 07:20 PM
RE: Splitting PDF at Bookmark level 2 - by buran - May-08-2023, 07:47 PM
RE: Splitting PDF at Bookmark level 2 - by zalito - May-09-2023, 07:21 AM
RE: Splitting PDF at Bookmark level 2 - by buran - May-09-2023, 09:04 AM
RE: Splitting PDF at Bookmark level 2 - by buran - May-09-2023, 03:20 PM
RE: Splitting PDF at Bookmark level 2 - by buran - May-09-2023, 04:45 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020