Created
April 10, 2015 09:08
-
-
Save renefritze/fd1f715082eb6ff301cb to your computer and use it in GitHub Desktop.
booklet printing
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from pyPdf import PdfFileWriter, PdfFileReader | |
from reportlab.lib import pagesizes | |
from reportlab.pdfgen import canvas | |
from reportlab.lib.units import cm, mm, inch | |
from StringIO import StringIO | |
import sys, tempfile | |
PAGESIZE = pagesizes.A4 | |
class EmptyPageReader( PdfFileReader ): | |
def __init__(self,nPages=1,pagesize=None): | |
buffer = StringIO() | |
c = canvas.Canvas(None) | |
if pagesize is None: | |
pagesize = PAGESIZE | |
c.setPageSize(pagesize) | |
c.showOutline() | |
for page in range(nPages): | |
c.showPage() | |
buffer.write(c.getpdfdata()) | |
buffer.seek(0) | |
super( EmptyPageReader,self ).__init__(buffer) | |
def __call__(s): | |
return s.getPage(0) | |
class OffsetReader( PdfFileReader ): | |
def getPage( s, n ): | |
return super(OffsetReader,s).getPage( n - 1 ) | |
def convert( input_fn, output_fn ): | |
with tempfile.TemporaryFile() as tmp: | |
output = PdfFileWriter() | |
input = PdfFileReader(file(input_fn, "rb")) | |
input_pagecount = input.getNumPages() | |
print '%s has %d pages'%(input_fn,input_pagecount) | |
blank = EmptyPageReader() | |
padded_output = PdfFileWriter() | |
for page in input.pages: | |
padded_output.addPage( page ) | |
for i in range(input_pagecount % 4 ): | |
padded_output.addPage(blank()) | |
padded_output.write(tmp) | |
input = OffsetReader(tmp) | |
n = input.getNumPages() | |
for i in range( ( n ) / 4 ): | |
print i,n | |
output.addPage( input.getPage( n - ( 2 * i ) ) ) | |
output.addPage( input.getPage( ( 2 * i ) + 1 ) ) | |
output.addPage( input.getPage( ( 2 * i ) + 2 ) ) | |
output.addPage( input.getPage( n - ( 2 * i + 1) ) ) | |
with file(output_fn, "wb") as outputStream : | |
output.write(outputStream) | |
if __name__=="__main__": | |
fn = sys.argv[1] | |
o = 'dummy.pdf' | |
convert( fn, o ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment