Created
October 23, 2017 11:00
-
-
Save gngdb/5490a1f14e70ba284bc7b20586b75204 to your computer and use it in GitHub Desktop.
python script to turn a standard pdf into an a5 booklet
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 sys | |
try: | |
import pyPdf | |
except ImportError: | |
import PyPDF2 as pyPdf | |
def addPage(opdf, ipdf, pg): | |
if pg>=len(pages): | |
opdf.addBlankPage(w, h) | |
else: | |
opdf.addPage(ipdf.getPage(pages[pg])) | |
try: | |
args = sys.argv[1:] | |
opdf = pyPdf.PdfFileWriter() | |
ipdf = pyPdf.PdfFileReader(file(args[0], "rb")) | |
ipgs = ipdf.getNumPages() | |
w, h = list(ipdf.getPage(0).mediaBox)[2:] | |
bsze = 0 | |
if len(args)>1: | |
bsze = int(args[1]) | |
if not bsze: | |
bsze = ipgs/4 + 1 | |
### Getting the printing range | |
pages = [] | |
if len(args)>2: | |
for pairs in args[2].split(","): | |
pairs = pairs.split("-") | |
start = int(pairs[0]) | |
if not len(pairs): | |
end = start + 1 | |
try: | |
end = int(pairs[len(pairs)-1]) | |
except: | |
end = int(ipgs-1) | |
pages += range(start-1, end) | |
else: | |
pages += range(0, ipgs) | |
print "Pages:", len(pages) | |
bcnt = 0 | |
util = 0 | |
### Forming the booklet | |
while util<len(pages): | |
frnt = bcnt*4*bsze | |
back = 4*bsze*(bcnt+1) - 1 | |
for i in range(bsze): | |
addPage(opdf, ipdf, back) | |
addPage(opdf, ipdf, frnt) | |
frnt += 1 | |
back -= 1 | |
addPage(opdf, ipdf, frnt) | |
addPage(opdf, ipdf, back) | |
frnt += 1 | |
back -= 1 | |
bcnt += 1 | |
util = bcnt * 4*bsze | |
print "Blank:", util-len(pages) | |
print "Writing to output" | |
oname = args[0].split(".")[0]+"_booklet.pdf" | |
opdfs = file(oname, "wb") | |
opdf.write(opdfs) | |
opdfs.close() | |
print "Done:", oname | |
except: | |
print """ | |
Use the following format: name [size] [range] | |
name Name of the file (*.pdf) | |
size Pieces of paper per sub-booklet (default 0) | |
range Range to print (1,3-4,7-) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment