Last active
June 11, 2023 02:29
-
-
Save thamognya/e24b140f2f9e02f2db4d7c083cff63a2 to your computer and use it in GitHub Desktop.
Split an pdf into N parts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from PyPDF2 import PdfReader, PdfWriter | |
def split_pdf(input_file, output_folder, num_files): | |
os.makedirs(output_folder, exist_ok=True) | |
with open(input_file, 'rb') as file: | |
pdf = PdfReader(file) | |
total_pages = len(pdf.pages) | |
pages_per_file = total_pages // num_files | |
for i in range(num_files): | |
output_file = os.path.join(output_folder, f'output_{i+1}.pdf') | |
start_page = i * pages_per_file | |
end_page = start_page + pages_per_file if i < num_files - 1 else total_pages | |
writer = PdfWriter() | |
for page in range(start_page, end_page): | |
writer.add_page(pdf.pages[page]) | |
with open(output_file, 'wb') as output: | |
writer.write(output) | |
print(f'Successfully created {output_file}') | |
input_file = 'path/to/your/input.pdf' | |
output_folder = 'path/to/output/folder' | |
num_files = 7 | |
split_pdf(input_file, output_folder, num_files) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment