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