home · contact · privacy
In Bookmaker, add spine size parameter.
[misc] / bookmaker.py
1 #!/usr/bin/env python3
2 import pypdf
3 import argparse
4 import io
5 from reportlab.lib.pagesizes import A4
6 a4_width, a4_height = A4
7
8 parser = argparse.ArgumentParser(description="build print-ready book PDF")
9 parser.add_argument("-i", "--input_file", action="append", required=True, help="input PDF file")
10 parser.add_argument("-o", "--output_file", required=True, help="output PDF file")
11 parser.add_argument("-p", "--page_range", action="append", help="page range, e.g., '3-end'")
12 parser.add_argument("-c", "--crop_range", action="append", help="crops left, bottom, right, top – e.g., '10,10,10,10'; prefix with ':'-delimited page range to limit effect")
13 parser.add_argument("-n", "--nup4", action='store_true', help="puts 4 input pages onto 1 output page")
14 parser.add_argument("-a", "--analyze", action="store_true", help="print lines identifying spine, page borders")
15 parser.add_argument("-t", "--symmetry", action="store_true", help="alternate horizontal crops between odd and even pages")
16 parser.add_argument("-r", "--rotate", dest="rotate", type=int, action="append", help="rotate page of number by 90° (usable multiple times on same page!)")
17 parser.add_argument("-m", "--margin", type=float, default=4.3, help="print margin in mm (default 4.3)")
18 parser.add_argument("-s", "--spine", type=float, default=10, help="on --nup4, mm width of margin hidden in spine (default 10)")
19 args = parser.parse_args()
20
21
22 # select pages from input files
23 def parse_page_range(range_string, pages):
24     start_page = 0
25     end_page = len(pages)
26     if range_string:
27         start, end = range_string.split('-')
28         if not (len(start) == 0 or start == "start"):
29             start_page = int(start) - 1
30         if not (len(end) == 0 or end == "end"):
31             end_page = int(end)
32     return start_page, end_page
33 pages_to_add = []
34 opened_files = []
35 for i, input_file in enumerate(args.input_file):
36     file = open(input_file, 'rb')
37     opened_files += [file]
38     reader = pypdf.PdfReader(file)
39     range_string = None
40     if args.page_range and len(args.page_range) > i:
41         range_string = args.page_range[i]
42     start_page, end_page = parse_page_range(range_string, reader.pages)
43     for page_num in range(start_page, end_page):
44         page = reader.pages[page_num]
45         pages_to_add += [page]
46         print("read in %s page number %d" % (input_file, page_num+1))
47
48 # rotate page canvas
49 if args.rotate:
50     for rotate in args.rotate:
51         page = pages_to_add[rotate - 1]
52         page.add_transformation(pypdf.Transformation().translate(tx=-a4_width/2, ty=-a4_height/2))
53         page.add_transformation(pypdf.Transformation().rotate(-90))
54         page.add_transformation(pypdf.Transformation().translate(tx=a4_width/2, ty=a4_height/2))
55
56 # normalize all pages to portrait A4
57 for page in pages_to_add:
58     if "/Rotate" in page:
59         page.rotate(360 - page["/Rotate"])
60     page.mediabox.left = 0
61     page.mediabox.bottom = 0
62     page.mediabox.top = a4_height
63     page.mediabox.right = a4_width
64     page.cropbox = page.mediabox
65
66 # determine page crops, zooms
67 crops_at_page = [(0,0,0,0)]*len(pages_to_add)
68 zoom_at_page = [1]*len(pages_to_add)
69 if args.crop_range:
70   for crop_range in args.crop_range:
71       initial_split = crop_range.split(':')
72       if len(initial_split) > 1:
73           page_range = initial_split[0]
74           crops = initial_split[1]
75       else:
76           page_range = None
77           crops = initial_split[0]
78       start_page, end_page = parse_page_range(page_range, pages_to_add)
79       crop_left, crop_bottom, crop_right, crop_top = [float(x) for x in  crops.split(',')]
80       cropped_width  = a4_width - crop_left - crop_right
81       cropped_height = a4_height - crop_bottom - crop_top
82       zoom = 1
83       zoom_horizontal = a4_width / (a4_width - crop_left - crop_right)
84       zoom_vertical = a4_height / (a4_height - crop_bottom - crop_top)
85       if (zoom_horizontal > 1 and zoom_vertical < 1) or (zoom_horizontal < 1 and zoom_vertical > 1):
86           print("Error: opposing zooms.")
87           exit(1)
88       elif zoom_horizontal + zoom_vertical > 2:
89           zoom = min(zoom_horizontal, zoom_vertical)
90       else:
91           zoom = max(zoom_horizontal, zoom_vertical)
92       for page_num in range(start_page, end_page):
93           crops_at_page[page_num] = (crop_left, crop_bottom, crop_right, crop_top)
94           zoom_at_page[page_num] = zoom
95
96 writer = pypdf.PdfWriter()
97 if not args.nup4:
98     odd_page = True
99     for i, page in enumerate(pages_to_add):
100         crop_left, crop_bottom, crop_right, crop_top = crops_at_page[i]
101         zoom = zoom_at_page[i]
102         if args.symmetry and odd_page:
103             page.add_transformation(pypdf.Transformation().translate(tx=-crop_right, ty=-crop_bottom))
104         else:
105             page.add_transformation(pypdf.Transformation().translate(tx=-crop_left, ty=-crop_bottom))
106         page.add_transformation(pypdf.Transformation().scale(zoom, zoom))
107         cropped_width  = a4_width - crop_left - crop_right
108         cropped_height = a4_height - crop_bottom - crop_top
109         page.mediabox.right = cropped_width * zoom
110         page.mediabox.top = cropped_height * zoom
111         writer.add_page(page)
112         odd_page = not odd_page
113
114 else:
115     points_per_mm = 2.83465
116     n_pages_per_axis = 2
117     spine_limit = args.spine * points_per_mm
118     printable_margin = args.margin * points_per_mm
119     printable_scale = (a4_width - 2*printable_margin)/a4_width
120     half_width = a4_width / n_pages_per_axis
121     half_height = a4_height / n_pages_per_axis
122     section_scale_factor = 1 / n_pages_per_axis
123     spine_part_of_page = (spine_limit / half_width) / printable_scale
124     bonus_shrink_factor = 1 - spine_part_of_page
125     new_page_order = []
126     new_i_order = []
127     eight_pack = []
128     mod_to_8 = len(pages_to_add) % 8
129     if mod_to_8 > 0:
130         for _ in range(8 - mod_to_8):
131             new_page = pypdf.PageObject.create_blank_page(width=a4_width, height=a4_height)
132             pages_to_add += [new_page]
133     i = 0
134     n_eights = 0
135     for page in pages_to_add:
136         if i == 0:
137             eight_pack = []
138         eight_pack += [page]
139         i += 1
140         if i == 8:
141             i = 0
142             new_i_order += [8 * n_eights + 3,
143                             8 * n_eights + 0,
144                             8 * n_eights + 7,
145                             8 * n_eights + 4,
146                             8 * n_eights + 1,
147                             8 * n_eights + 2,
148                             8 * n_eights + 5,
149                             8 * n_eights + 6]
150             n_eights += 1
151             new_page_order += [eight_pack[3]]  # page front, upper left
152             new_page_order += [eight_pack[0]]  # page front, upper right
153             new_page_order += [eight_pack[7]]  # page front, lower left
154             new_page_order += [eight_pack[4]]  # page front, lower right
155             new_page_order += [eight_pack[1]]  # page back, upper left
156             new_page_order += [eight_pack[2]]  # page back, upper right
157             new_page_order += [eight_pack[5]]  # page back, lower left
158             new_page_order += [eight_pack[6]]  # page back, lower right
159     i = 0
160     page_count = 0
161     front_page = True
162     for j, page in enumerate(new_page_order):
163         if i == 0:
164             new_page = pypdf.PageObject.create_blank_page(width=a4_width, height=a4_height)
165
166         # in-section transformations: align pages on top, left-hand pages to left, right-hand to right
167         new_i = new_i_order[j]
168         crop_left, crop_bottom, crop_right, crop_top = crops_at_page[new_i]
169         zoom = zoom_at_page[new_i]
170         page.add_transformation(pypdf.Transformation().translate(ty=(a4_height / zoom - (a4_height - crop_top))))
171         if i == 0 or i == 2:
172             if args.symmetry:
173                 page.add_transformation(pypdf.Transformation().translate(tx=-crop_left))
174             else:
175                 page.add_transformation(pypdf.Transformation().translate(tx=-crop_right))
176         elif i == 1 or i == 3:
177             if args.symmetry:
178                 page.add_transformation(pypdf.Transformation().translate(tx=(a4_width / zoom - (a4_width - crop_left))))
179             else:
180                 page.add_transformation(pypdf.Transformation().translate(tx=(a4_width / zoom - (a4_width - crop_right))))
181         page.add_transformation(pypdf.Transformation().scale(zoom * bonus_shrink_factor, zoom * bonus_shrink_factor))
182         if i == 2 or i == 3:
183             page.add_transformation(pypdf.Transformation().translate(ty=-2*printable_margin/printable_scale))
184
185         # outer section transformations
186         page.add_transformation(pypdf.Transformation().translate(ty=(1-bonus_shrink_factor)*a4_height))
187         if i == 0 or i == 1:
188             y_section = a4_height
189             page.mediabox.bottom = half_height
190             page.mediabox.top    = a4_height
191         if i == 2 or i == 3:
192             y_section = 0
193             page.mediabox.bottom = 0
194             page.mediabox.top  =   half_height
195         if i == 0 or i == 2:
196             x_section = 0
197             page.mediabox.left   = 0
198             page.mediabox.right  = half_width
199         if i == 1 or i == 3:
200             page.add_transformation(pypdf.Transformation().translate(tx=(1-bonus_shrink_factor)*a4_width))
201             x_section = a4_width
202             page.mediabox.left   = half_width
203             page.mediabox.right  = a4_width
204         page.add_transformation(pypdf.Transformation().translate(tx=x_section, ty=y_section))
205         page.add_transformation(pypdf.Transformation().scale(section_scale_factor, section_scale_factor))
206         new_page.merge_page(page)
207         page_count += 1
208         print("merged page number", page_count)
209         i += 1
210         if i > 3:
211             from reportlab.pdfgen import canvas
212             if args.analyze:
213                 # borders
214                 packet = io.BytesIO()
215                 c = canvas.Canvas(packet, pagesize=A4)
216                 c.setLineWidth(0.1)
217                 c.line(0, a4_height, a4_width, a4_height)
218                 c.line(0, half_height, a4_width, half_height)
219                 c.line(0, 0, a4_width, 0)
220                 c.line(0, a4_height, 0, 0)
221                 c.line(half_width, a4_height, half_width, 0)
222                 c.line(a4_width, a4_height, a4_width, 0)
223                 c.save()
224                 new_pdf = pypdf.PdfReader(packet)
225                 new_page.merge_page(new_pdf.pages[0])
226             printable_offset_x = printable_margin
227             printable_offset_y = printable_margin * a4_height / a4_width
228             new_page.add_transformation(pypdf.Transformation().scale(printable_scale, printable_scale))
229             new_page.add_transformation(pypdf.Transformation().translate(tx=printable_offset_x, ty=printable_offset_y))
230             x_left_spine_limit = half_width * bonus_shrink_factor
231             x_right_spine_limit = a4_width - x_left_spine_limit
232             if args.analyze or front_page:
233                 packet = io.BytesIO()
234                 c = canvas.Canvas(packet, pagesize=A4)
235             if args.analyze:
236                 # # spine lines
237                 c.setLineWidth(0.1)
238                 c.line(x_left_spine_limit, a4_height, x_left_spine_limit, 0)
239                 c.line(x_right_spine_limit, a4_height, x_right_spine_limit, 0)
240             if front_page:
241                 c.setLineWidth(0.2)
242                 cut_depth = 19.5 * points_per_mm
243                 cut_width = 10.5 * points_per_mm
244                 middle_point_depth = 4 * points_per_mm
245
246                 start_up_left_left_x = x_left_spine_limit - 0.5 * cut_width
247                 start_up_left_right_x = x_left_spine_limit + 0.5 * cut_width
248                 middle_point_up_left_y = half_height + middle_point_depth
249                 end_point_up_left_y = half_height + cut_depth
250                 c.line(start_up_left_right_x, half_height, x_left_spine_limit, end_point_up_left_y)
251                 c.line(x_left_spine_limit, end_point_up_left_y, x_left_spine_limit, middle_point_up_left_y)
252                 c.line(x_left_spine_limit, middle_point_up_left_y, start_up_left_left_x, half_height)
253
254                 start_down_right_left_x = x_right_spine_limit - 0.5 * cut_width
255                 start_down_right_right_x = x_right_spine_limit + 0.5 * cut_width
256                 middle_point_down_right_y = half_height - middle_point_depth
257                 end_point_down_right_y = half_height - cut_depth
258                 c.line(start_down_right_left_x, half_height, x_right_spine_limit, end_point_down_right_y)
259                 c.line(x_right_spine_limit, end_point_down_right_y, x_right_spine_limit, middle_point_down_right_y)
260                 c.line(x_right_spine_limit, middle_point_down_right_y, start_down_right_right_x, half_height)
261
262             if args.analyze or front_page:
263                 c.save()
264                 new_pdf = pypdf.PdfReader(packet)
265                 new_page.merge_page(new_pdf.pages[0])
266             writer.add_page(new_page)
267             i = 0
268             front_page = not front_page
269 for file in opened_files:
270     file.close()
271
272 with open(args.output_file, 'wb') as output_file:
273     writer.write(output_file)