Convert PDF into a stapeable book


stapleablebook.py

Permalink View in github Raw

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
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)