home · contact · privacy
3737edc6bebf019dc9ed2ba880f7f7208e09e854
[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 spine_limit = 1 * points_per_cm
12
13 parser = argparse.ArgumentParser(description="build print-ready book PDF")
14 parser.add_argument("-i", "--input_file", action="append", required=True, help="input PDF file")
15 parser.add_argument("-o", "--output_file", required=True, help="output PDF file")
16 parser.add_argument("-p", "--page_range", action="append", help="page range, e.g., '3-end'")
17 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")
18 parser.add_argument("-s", "--symmetry", action="store_true", help="alternate horizontal crops between odd and even pages")
19 parser.add_argument("-r", "--rotate", dest="rotate", type=int, action="append", help="rotate page of number by 90° (usable multiple times on same page!)")
20 parser.add_argument("-n", "--nup4", action='store_true', help="puts 4 input pages onto 1 output page")
21 parser.add_argument("-a", "--analyze", action="store_true", help="in --nup4, print lines identifying spine, page borders")
22 parser.add_argument("-m", "--margin", type=float, default=0.43, help="print margin for --nup4 in cm (default 0.43)")
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 new_page_num = 0
40 for i, input_file in enumerate(args.input_file):
41     file = open(input_file, 'rb')
42     opened_files += [file]
43     reader = pypdf.PdfReader(file)
44     range_string = None
45     if args.page_range and len(args.page_range) > i:
46         range_string = args.page_range[i]
47     start_page, end_page = parse_page_range(range_string, reader.pages)
48     for old_page_num in range(start_page, end_page):
49         new_page_num += 1
50         page = reader.pages[old_page_num]
51         pages_to_add += [page]
52         print("-i, -p: read in %s page number %d as new page %d" % (input_file, old_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, crop symmetry
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     # single-page output
113     print("building 1-input-page-per-output-page book")
114     odd_page = True
115     for i, page in enumerate(pages_to_add):
116         crop_left, crop_bottom, crop_right, crop_top = crops_at_page[i]
117         zoom = zoom_at_page[i]
118         page.add_transformation(pypdf.Transformation().translate(tx=-crop_left, ty=-crop_bottom))
119         page.add_transformation(pypdf.Transformation().scale(zoom, zoom))
120         cropped_width  = a4_width - crop_left - crop_right
121         cropped_height = a4_height - crop_bottom - crop_top
122         page.mediabox.right = cropped_width * zoom
123         page.mediabox.top = cropped_height * zoom
124         writer.add_page(page)
125         odd_page = not odd_page
126
127 else:
128     print("-n: building 4-input-pages-per-output-page book")
129     n_pages_per_axis = 2
130     printable_margin = args.margin * points_per_cm
131     printable_scale = (a4_width - 2*printable_margin)/a4_width
132     half_width = a4_width / n_pages_per_axis
133     half_height = a4_height / n_pages_per_axis
134     section_scale_factor = 1 / n_pages_per_axis
135     spine_part_of_page = (spine_limit / half_width) / printable_scale
136     bonus_shrink_factor = 1 - spine_part_of_page
137     new_page_order = []
138     new_i_order = []
139     eight_pack = []
140     mod_to_8 = len(pages_to_add) % 8
141     if mod_to_8 > 0:
142         for _ in range(8 - mod_to_8):
143             new_page = pypdf.PageObject.create_blank_page(width=a4_width, height=a4_height)
144             pages_to_add += [new_page]
145     i = 0
146     n_eights = 0
147     for page in pages_to_add:
148         if i == 0:
149             eight_pack = []
150         eight_pack += [page]
151         i += 1
152         if i == 8:
153             i = 0
154             new_i_order += [8 * n_eights + 3,
155                             8 * n_eights + 0,
156                             8 * n_eights + 7,
157                             8 * n_eights + 4,
158                             8 * n_eights + 1,
159                             8 * n_eights + 2,
160                             8 * n_eights + 5,
161                             8 * n_eights + 6]
162             n_eights += 1
163             new_page_order += [eight_pack[3]]  # page front, upper left
164             new_page_order += [eight_pack[0]]  # page front, upper right
165             new_page_order += [eight_pack[7]]  # page front, lower left
166             new_page_order += [eight_pack[4]]  # page front, lower right
167             new_page_order += [eight_pack[1]]  # page back, upper left
168             new_page_order += [eight_pack[2]]  # page back, upper right
169             new_page_order += [eight_pack[5]]  # page back, lower left
170             new_page_order += [eight_pack[6]]  # page back, lower right
171     i = 0
172     page_count = 0
173     front_page = True
174     for j, page in enumerate(new_page_order):
175         if i == 0:
176             new_page = pypdf.PageObject.create_blank_page(width=a4_width, height=a4_height)
177
178         # in-section transformations: align pages on top, left-hand pages to left, right-hand to right
179         new_i = new_i_order[j]
180         crop_left, crop_bottom, crop_right, crop_top = crops_at_page[new_i]
181         zoom = zoom_at_page[new_i]
182         page.add_transformation(pypdf.Transformation().translate(ty=(a4_height / zoom - (a4_height - crop_top))))
183         if i == 0 or i == 2:
184             page.add_transformation(pypdf.Transformation().translate(tx=-crop_left))
185         elif i == 1 or i == 3:
186             page.add_transformation(pypdf.Transformation().translate(tx=(a4_width / zoom - (a4_width - crop_right))))
187         page.add_transformation(pypdf.Transformation().scale(zoom * bonus_shrink_factor, zoom * bonus_shrink_factor))
188         if i == 2 or i == 3:
189             page.add_transformation(pypdf.Transformation().translate(ty=-2*printable_margin/printable_scale))
190
191         # outer section transformations
192         page.add_transformation(pypdf.Transformation().translate(ty=(1-bonus_shrink_factor)*a4_height))
193         if i == 0 or i == 1:
194             y_section = a4_height
195             page.mediabox.bottom = half_height
196             page.mediabox.top    = a4_height
197         if i == 2 or i == 3:
198             y_section = 0
199             page.mediabox.bottom = 0
200             page.mediabox.top  =   half_height
201         if i == 0 or i == 2:
202             x_section = 0
203             page.mediabox.left   = 0
204             page.mediabox.right  = half_width
205         if i == 1 or i == 3:
206             page.add_transformation(pypdf.Transformation().translate(tx=(1-bonus_shrink_factor)*a4_width))
207             x_section = a4_width
208             page.mediabox.left   = half_width
209             page.mediabox.right  = a4_width
210         page.add_transformation(pypdf.Transformation().translate(tx=x_section, ty=y_section))
211         page.add_transformation(pypdf.Transformation().scale(section_scale_factor, section_scale_factor))
212         new_page.merge_page(page)
213         page_count += 1
214         print("merged page number", page_count)
215         i += 1
216         if i > 3:
217             from reportlab.pdfgen import canvas
218             if args.analyze:
219                 # borders
220                 packet = io.BytesIO()
221                 c = canvas.Canvas(packet, pagesize=A4)
222                 c.setLineWidth(0.1)
223                 c.line(0, a4_height, a4_width, a4_height)
224                 c.line(0, half_height, a4_width, half_height)
225                 c.line(0, 0, a4_width, 0)
226                 c.line(0, a4_height, 0, 0)
227                 c.line(half_width, a4_height, half_width, 0)
228                 c.line(a4_width, a4_height, a4_width, 0)
229                 c.save()
230                 new_pdf = pypdf.PdfReader(packet)
231                 new_page.merge_page(new_pdf.pages[0])
232             printable_offset_x = printable_margin
233             printable_offset_y = printable_margin * a4_height / a4_width
234             new_page.add_transformation(pypdf.Transformation().scale(printable_scale, printable_scale))
235             new_page.add_transformation(pypdf.Transformation().translate(tx=printable_offset_x, ty=printable_offset_y))
236             x_left_spine_limit = half_width * bonus_shrink_factor
237             x_right_spine_limit = a4_width - x_left_spine_limit
238             if args.analyze or front_page:
239                 packet = io.BytesIO()
240                 c = canvas.Canvas(packet, pagesize=A4)
241             if args.analyze:
242                 # # spine lines
243                 c.setLineWidth(0.1)
244                 c.line(x_left_spine_limit, a4_height, x_left_spine_limit, 0)
245                 c.line(x_right_spine_limit, a4_height, x_right_spine_limit, 0)
246             if front_page:
247                 c.setLineWidth(0.2)
248
249                 start_up_left_left_x = x_left_spine_limit - 0.5 * cut_width
250                 start_up_left_right_x = x_left_spine_limit + 0.5 * cut_width
251                 middle_point_up_left_y = half_height + middle_point_depth
252                 end_point_up_left_y = half_height + cut_depth
253                 c.line(start_up_left_right_x, half_height, x_left_spine_limit, end_point_up_left_y)
254                 c.line(x_left_spine_limit, end_point_up_left_y, x_left_spine_limit, middle_point_up_left_y)
255                 c.line(x_left_spine_limit, middle_point_up_left_y, start_up_left_left_x, half_height)
256
257                 start_down_right_left_x = x_right_spine_limit - 0.5 * cut_width
258                 start_down_right_right_x = x_right_spine_limit + 0.5 * cut_width
259                 middle_point_down_right_y = half_height - middle_point_depth
260                 end_point_down_right_y = half_height - cut_depth
261                 c.line(start_down_right_left_x, half_height, x_right_spine_limit, end_point_down_right_y)
262                 c.line(x_right_spine_limit, end_point_down_right_y, x_right_spine_limit, middle_point_down_right_y)
263                 c.line(x_right_spine_limit, middle_point_down_right_y, start_down_right_right_x, half_height)
264
265             if args.analyze or front_page:
266                 c.save()
267                 new_pdf = pypdf.PdfReader(packet)
268                 new_page.merge_page(new_pdf.pages[0])
269             writer.add_page(new_page)
270             i = 0
271             front_page = not front_page
272
273 # write and close
274 for file in opened_files:
275     file.close()
276 with open(args.output_file, 'wb') as output_file:
277     writer.write(output_file)