Skip to content

Instantly share code, notes, and snippets.

@marcorichetta
Created June 24, 2019 13:20
Show Gist options
  • Save marcorichetta/1b8ffc46954bc55bdb10f0b06bfebc6c to your computer and use it in GitHub Desktop.
Save marcorichetta/1b8ffc46954bc55bdb10f0b06bfebc6c to your computer and use it in GitHub Desktop.
Split a pdf file between provided pages.
from PyPDF2 import PdfFileReader, PdfFileWriter
def split(path, split_name, start_page, end_page):
# Create a FileReader instance
pdf = PdfFileReader(path)
# Create a FileWriter instance
pdf_writer = PdfFileWriter()
"""
Add every page between start to end,
inclusively, to the FileWriter instance
"""
for page in range(start_page, end_page):
pdf_writer.addPage(pdf.getPage(page))
# Write the contents of the
# FileWriter instance to a file
output = f'{split_name}.pdf'
with open(output, 'wb') as output_pdf:
pdf_writer.write(output_pdf)
if __name__ == "__main__":
path = 'test.pdf' # Same folder
split(path, 'split_file', 343, 385)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment