Last active
August 29, 2015 14:07
-
-
Save ongspxm/c1946bdeb7c7208cab8e to your computer and use it in GitHub Desktop.
Forming booklets from PDF files
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, 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