Skip to content

Instantly share code, notes, and snippets.

@rvegajr
Last active July 26, 2022 21:18
Show Gist options
  • Save rvegajr/c7a0867287a09f99ed0223841c438caa to your computer and use it in GitHub Desktop.
Save rvegajr/c7a0867287a09f99ed0223841c438caa to your computer and use it in GitHub Desktop.
Python PDF Splitter
from PyPDF2 import PdfFileWriter, PdfFileReader
import os
import shutil
def splitpdf(pdf_name_to_split, form_page_count=1):
print(f'Splitting {pdf_name_to_split}')
dir_path = os.path.dirname(os.path.realpath(__file__)) + '/'
input_file_name = pdf_name_to_split
input_pdf = PdfFileReader(input_file_name)
new_path = dir_path + input_file_name.replace('.pdf', '')
if os.path.exists(new_path):
shutil.rmtree(new_path)
os.mkdir(new_path)
print(f' Creating {new_path}.. will split into {input_pdf.numPages} pages')
sub_page_group = 0
current_file_no = 1;
output = PdfFileWriter()
for i in range(0, input_pdf.numPages):
output.addPage(input_pdf.getPage(i))
sub_page_group += 1
if sub_page_group == form_page_count:
new_file_name = new_path + '/' + input_file_name.replace('.pdf', f"_{current_file_no}.pdf")
sub_page_group = 0
current_file_no += 1
with open(new_file_name, "wb") as output_stream:
output.write(output_stream)
output = PdfFileWriter()
print(f' Splitting of {pdf_name_to_split} completed')
splitpdf("elite gear.pdf", 2)
splitpdf("perf gear.pdf", 2)
splitpdf("soldier cards.pdf")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment