-
Notifications
You must be signed in to change notification settings - Fork 0
/
shuffle
executable file
·81 lines (68 loc) · 1.92 KB
/
shuffle
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
#!/usr/bin/env python
from argparse import ArgumentParser
from pathlib import Path
from typing import Dict, List
import pikepdf
layouts: Dict[int, List[int]] = {4: [1, 4, 5, 8, 3, 2, 7, 6]}
page_sizes = {
"a0": (2384, 3370),
"a1": (1684, 2384),
"a2": (1190, 1684),
"a3": (842, 1190),
"a4": (595, 842),
"a5": (420, 595),
"a6": (298, 420),
"a7": (210, 298),
"a8": (148, 210),
"b0": (2835, 4008),
"b1": (2004, 2835),
"b2": (1417, 2004),
"b3": (1001, 1417),
"b4": (709, 1001),
"b5": (499, 709),
"b6": (354, 499),
"b7": (249, 354),
"b8": (176, 249),
"b9": (125, 176),
"b10": (88, 125),
"letter": (612, 792),
"legal": (612, 1008),
}
parser = ArgumentParser()
parser.add_argument("inputpdf", help="Input PDF")
parser.add_argument(
"--page-size",
choices=page_sizes.keys(),
required=True,
help="Input PDF page size",
)
parser.add_argument(
"--pages-per-side",
type=int,
choices=layouts.keys(),
required=True,
help="Number of pages per side",
)
def shuffle(inputpdf: str, size: str, layout: List[int]):
inpath = Path(inputpdf)
outpath = f"{inpath.stem}_reordered{inpath.suffix}"
npages = len(layout)
with pikepdf.open(inputpdf) as pdf:
# pad with blank pages to make total number of pages a multiple of 8
for i in range(npages - (len(pdf.pages) % npages)):
pdf.add_blank_page(page_size=size)
# reorder pages to match layout
def _getitem(j: int):
return lambda k: pdf.pages[k - 1 j * npages]
for i in range(len(pdf.pages) // npages):
pdf.pages[i * npages : i * npages npages] = list(
map(_getitem(i), layout)
)
pdf.save(outpath)
if __name__ == "__main__":
opts = parser.parse_args()
shuffle(
opts.inputpdf,
page_sizes[opts.page_size],
layouts[opts.pages_per_side],
)