Skip to content

Instantly share code, notes, and snippets.

@pajachiet
Created March 1, 2019 17:05
Show Gist options
  • Save pajachiet/99c1291d0410384748c5750cbdf46827 to your computer and use it in GitHub Desktop.
Save pajachiet/99c1291d0410384748c5750cbdf46827 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# coding: utf8
import copy
import PyPDF2
import sys
def split_page(src, dst, row=1, col=1, margin=0):
src_f = file(src, 'r+b')
dst_f = file(dst, 'w+b')
input = PyPDF2.PdfFileReader(src_f)
output = PyPDF2.PdfFileWriter()
p = input.getPage(0)
x0, y0 = p.mediaBox.lowerLeft
x1, y1 = p.mediaBox.upperRight
x_delta = float(x1-x0) / col
y_delta = float(y1-y0) / row
for j in range(col):
for i in reversed(range(row)):
q = copy.copy(p)
q.mediaBox = copy.copy(p.mediaBox)
q.mediaBox.lowerLeft = x0 + j * x_delta - margin, y0 + i * y_delta - margin
q.mediaBox.upperRight = x0 + (j+1) * x_delta + margin, y0 + (i+1) * y_delta + margin
output.addPage(q)
output.write(dst_f)
src_f.close()
dst_f.close()
if __name__ == '__main__':
input, output, row, col, margin = sys.argv[1:]
split_page(input, output, int(row), int(col), int(margin))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment