How to split each page of a pdf in separe pdf files

I had to do this task for my own use, so I thought to share it with you folks. Remember to visit my site often, so that I can do more post in a more enthusiastic way.

This is the code.

You gotta give the name of the file to be splitted, that is in the same dir of the script and the name of the folder where you want the splitted files ot the output to go.

pdf splitted in all his pages
import os
from PyPDF2 import PdfReader, PdfWriter

''' pdfsplit

As the name suggests, give the name of a pdf in a folder,
and it will be splitted in all his

'''


def split_pdf_pages(input_file_path, output_folder_path):
    # Open the PDF file
    input_pdf = PdfReader(open(input_file_path, "rb"))

    # Loop through each page of the PDF and extract it as a separate PDF file
    for page_number in range(len(input_pdf.pages)):
        # Create a new PDF writer object
        output_pdf = PdfWriter()

        # Add the current page to the writer
        output_pdf.add_page(input_pdf.pages[page_number])

        # Construct the output file path
        output_file_path = os.path.join(output_folder_path, f"page{page_number+1}.pdf")

        # Write the output PDF file
        with open(output_file_path, "wb") as output_file:
            output_pdf.write(output_file)

    print(f"Split {input_file_path} into {len(input_pdf.pages)} separate pages")

# Example usage
split_pdf_pages("All.pdf", "ALL")

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.