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