Skip to content

Instantly share code, notes, and snippets.

@breedx2
Created January 3, 2024 20:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save breedx2/60409d2179508dba28c4159b81f26fc2 to your computer and use it in GitHub Desktop.
Save breedx2/60409d2179508dba28c4159b81f26fc2 to your computer and use it in GitHub Desktop.
Split a PDF vertically, used for scanned double sided PDF pages
# Source http://stackoverflow.com/a/15741856/1301753
# Source https://gist.github.com/breedx2/60409d2179508dba28c4159b81f26fc2
import copy
import sys
import math
import pypdf
def split_pages(src, dst):
src_f = open(src, 'r+b')
dst_f = open(dst, 'w+b')
input = pypdf.PdfReader(src_f)
output = pypdf.PdfWriter()
for i in range(len(input.pages)):
p = input.pages[i]
q = copy.copy(p)
q.mediabox = copy.copy(p.mediabox)
x1, x2 = p.mediabox.lower_left
x3, x4 = p.mediabox.upper_right
x1, x2 = math.floor(x1), math.floor(x2)
x3, x4 = math.floor(x3), math.floor(x4)
x5, x6 = math.floor(x3/2), math.floor(x4/2)
if x3 > x4:
# horizontal
p.mediabox.upper_right = (x5, x4)
p.mediabox.lower_left = (x1, x2)
q.mediabox.upper_right = (x3, x4)
q.mediabox.lower_left = (x5, x2)
else:
# vertical
p.mediabox.upper_right = (x3, x4)
p.mediabox.lower_left = (x1, x6)
q.mediabox.upper_right = (x3, x6)
q.mediabox.lower_left = (x1, x2)
output.add_page(p)
output.add_page(q)
output.write(dst_f)
src_f.close()
dst_f.close()
input_file=input("Enter the original PDF file name :")
output_file=input("Enter the splitted PDF file name :")
split_pages(input_file,output_file)
@breedx2
Copy link
Author

breedx2 commented Jan 3, 2024

This is a quick and dirty python3 update in 2024 for the original at https://gist.github.com/tshrinivasan/23d8e4986cbae49b8a8c

@tshrinivasan
Copy link

Thanks for improving .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment