Skip to content

Instantly share code, notes, and snippets.

@vgmoose
Created Jan 30, 2021
Embed
What would you like to do?
Splits a given PDF file into separate PDFs made up of the odd and even pages
from PyPDF2 import PdfFileReader, PdfFileWriter
import sys
# Splits a given PDFfile into two odd and even page'd PDFs
# Also flips the even pages upside down and reverses their order
# This is to faciliate double-sided printing without having the printer support it
# If there's an odd number of pages, the last page is placed separately in a third PDF
# This helps make it easier to re-feed the paper without worrying about that remainder page
try:
target = sys.argv[1]
except:
print("Provide pdf file to split")
pdf_reader = PdfFileReader(open(target, 'rb'))
pages_count = pdf_reader.getNumPages()
odd_writer = PdfFileWriter()
even_writer = PdfFileWriter()
last_page = PdfFileWriter()
even_outs = []
hasLast = False
for page_num in range(0, pages_count, 2):
next_num = page_num + 1
if next_num >= pages_count:
# unmatched odd page!!! stands alone
last_page.addPage(pdf_reader.getPage(page_num))
hasLast = True
break
odd_writer.addPage(pdf_reader.getPage(page_num))
even_outs.append(pdf_reader.getPage(next_num))
for page in even_outs[::-1]:
page.rotateClockwise(180)
even_writer.addPage(page)
with open(f"{target}_odd.pdf",'wb') as out:
odd_writer.write(out)
with open(f"{target}_even.pdf",'wb') as out:
even_writer.write(out)
if hasLast:
with open(f"{target}_last.pdf", 'wb') as out:
last_page.write(out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment