summaryrefslogtreecommitdiff
path: root/page_manipulation/a5_book.py
blob: 1e004e06d8fc5c6ce723d8d42d42eaf01de51dc9 (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3

import argparse
import os.path
import subprocess

try:
        import pypdf
except ImportError:
        pypdf = None


SIGNATURE = (
    15, 0,
    1, 14,
    13, 2,
    3, 12,
    11, 4,
    5, 10,
    9, 6,
    7, 8
)


def get_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--pagespec",
        help="Page selection. At the moment only '<start>-<end>' is supported"
    )
    parser.add_argument(
        "file",
        help="Name of the PDF file",
    )
    return parser


def main():
    parser = get_parser()
    args = parser.parse_args()

    if not args.pagespec:
        if not pypdf:
            print("Detecting the number of pages in the pdf requires pypdf")
            sys.exit(1)
        reader = pypdf.PdfReader(args.file)
        start = 1
        end = end = len(reader.pages)
    else:
        pspec = args.pagespec.split('-')
        try:
            start = int(pspec[0])
            end = int(pspec[1])
        except ValueError:
            parser.print_usage()
        except IndexError:
            parser.print_usage()

    pages = [str(i) for i in range(start, end+1)]
    if len(pages) % 16 != 0:
        empty = 16 - len(pages) % 16
        pages = pages + ["{}"] * empty

    rearranged = []
    while pages:
        for i in SIGNATURE:
            rearranged.append(pages[i])
        pages = pages[16:]

    base, ext = os.path.splitext(args.file)
    out_fname = base + '-book' + ext

    subprocess.run([
       'pdfjam',
       '--nup', '2x1',
       "--landscape",
       #'--no-tidy',
       '-o', out_fname,
       args.file,
       ','.join(rearranged)
    ])


if __name__ == "__main__":
    main()