Skip to content

Instantly share code, notes, and snippets.

@paulera
Created February 17, 2020 14:58
Show Gist options
  • Select an option

  • Save paulera/babf52bba185b3c57d592a4965ed2cfe to your computer and use it in GitHub Desktop.

Select an option

Save paulera/babf52bba185b3c57d592a4965ed2cfe to your computer and use it in GitHub Desktop.
Reorder pages of a PDF file so you can print as a staple-able book
"""
This script will take a PDF file set in the input_file variable and create a file
with similar name but endind with "-stapleablebook.pdf".
To create a A5 sized book, print the resulting file as described below and fold the
whole block of paper in the middle. You can staple it in the middle to create your book.
Printer configuration:
- Pages per sheet = 2
- Twol-sided = Print on both sides
- Flip on short edge
- Scale = fit to paper
"""
input_file = "guide.pdf"
import os
from PyPDF2 import PdfFileWriter, PdfFileReader
fname = os.path.splitext(os.path.basename(input_file))[0]
output_filename = fname + "-stapleablebook.pdf"
pdf_reader = PdfFileReader(input_file)
# Get the number of pages to arrange
original_pages_count = pdf_reader.getNumPages()
# get page dimensions (for blank ones)
_, _, page_width, page_height = pdf_reader.getPage(0)['/MediaBox']
# We can only work with multiples of 4 to arrange the book, so
# find out what is the page count to consider virtually. Non existing
# pages will be added as blank ones.
pages_count = original_pages_count + (4 - original_pages_count%4)
# Find out the new layout of pages in a way that they can be printed
# 2 sheets per page, both sided, in order to make a book we can staple
pages_layout = []
for i in range (int(pages_count / 4)):
pages_layout.append(pages_count - i*2 - 1)
pages_layout.append(i*2)
pages_layout.append(1 + i*2)
pages_layout.append(pages_count - 2 - i*2)
pdf_writer = PdfFileWriter()
for page_index in pages_layout:
if page_index < original_pages_count:
pdf_writer.addPage(pdf_reader.getPage(page_index))
else:
pdf_writer.addBlankPage(page_width, page_height)
with open(output_filename, 'wb') as fd:
pdf_writer.write(fd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment