Skip to content

Instantly share code, notes, and snippets.

@ipanin
Created August 18, 2021 16:11
Show Gist options
  • Save ipanin/4edb04e0397de8f9e2937fe2c40462ba to your computer and use it in GitHub Desktop.
Save ipanin/4edb04e0397de8f9e2937fe2c40462ba to your computer and use it in GitHub Desktop.
Change page sequence in PDF to document as a booklet (2-sided, 2 page per sheet)
# Change page sequence in PDF to document as a booklet
# Booklet is 2-sided, 2 page per sheet
import sys
import os
import PyPDF3 as pdf
fin = pdf.PdfFileReader(open(sys.argv[1], 'rb'))
fout = pdf.PdfFileWriter()
# create a list of page indices
pages = list(range(fin.getNumPages()))
# pad page index list until its len is a multiple of four
while len(pages) % 4: pages.append(None)
# index of the last page
n = len(pages) - 1
# get document dimensions
w = fin.getPage(0).mediaBox.getWidth()
h = fin.getPage(0).mediaBox.getHeight()
# we loop in pairs
for x in range(len(pages) // 2):
# alternately count from the front and back
for index in (x, n - x) if x % 2 else (n - x, x):
if pages[index] is None: fout.addBlankPage(w, h) # pad
else: fout.addPage(fin.getPage(index))
# write the output file
newName = "Booklet-" + os.path.basename(sys.argv[1])
fout.write((open(newName, 'wb')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment