-from reportlab.lib.pagesizes import A4
-a4_width, a4_height = A4
-
-parser = argparse.ArgumentParser(description="build print-ready book PDF")
-parser.add_argument("-i", "--input", dest="input_file", required=True, help="input PDF file")
-parser.add_argument("-o", "--output", dest="output_file", required=True, help="output PDF file")
-parser.add_argument("-p", "--pages", dest="page_range", help="page range, e.g., '3-end'")
-parser.add_argument("-c", "--crop", dest="crop_range", help="crops left, bottom, right, top – e.g., '10,10,10,10'")
-parser.add_argument("-n", "--nup4", dest="nup4", action='store_true', help="puts 4 input pages onto 1 output page")
-parser.add_argument("-a", "--analyze", dest="analyze", action="store_true", help="print lines identifying spine, page borders")
-parser.add_argument("-t", "--symmetry", dest="symmetry", action="store_true", help="alternate horizontal crops between odd and even pages")
-parser.add_argument("-s", "--second", dest="second", help="append second file as input to append")
-parser.add_argument("-r", "--rotate", dest="rotate", help="rotate page of number by 90°")
-parser.add_argument("-m", "--margin", type=float, default=4.3, help="print margin (default 4.3)")
-args = parser.parse_args()
-
-with open(args.input_file, 'rb') as file:
- reader = pypdf.PdfReader(file)
-
- # determine page range
+import os
+import sys
+def fail_with_msg(msg):
+ print("ERROR:", msg)
+ sys.exit(1)
+try:
+ import pypdf
+except ImportError:
+ fail_with_msg("Can't run without pypdf installed.")
+try:
+ from reportlab.lib.pagesizes import A4
+except ImportError:
+ fail_with_msg("Can't run without reportlab installed.")
+
+# some constants
+A4_WIDTH, A4_HEIGHT = A4
+POINTS_PER_CM = 10 * 72 / 25.4
+CUT_DEPTH = 1.95 * POINTS_PER_CM
+CUT_WIDTH = 1.05 * POINTS_PER_CM
+MIDDLE_POINT_DEPTH = 0.4 * POINTS_PER_CM
+SPINE_LIMIT = 1 * POINTS_PER_CM
+help_epilogue = """
+EXAMPLES:
+
+Concatenate two PDFs A.pdf and B.pdf to COMBINED.pdf:
+ bookmaker.py --input_file A.pdf --input_file B.pdf --output_file COMBINED.pdf
+
+Produce OUTPUT.pdf containing all pages of (inclusive) page number range 3-7 from INPUT.pdf:
+ bookmaker.py -i INPUT.pdf --page_range 3-7 -o OUTPUT.pdf
+
+Produce COMBINED.pdf from A.pdf's first 7 pages, B.pdf's pages except its first two, and all pages of C.pdf:
+ bookmaker.py -i A.pdf -p start-7 -i B.pdf -p 3-end -i C.pdf -o COMBINED.pdf
+
+Crop each page 5cm from the left, 10cm from the bottom, 2cm from the right, and 0cm from the top:
+ bookmaker.py -i INPUT.pdf -o OUTPUT.pdf --crops "5,10,2,0"
+
+Include all pages from INPUT.pdf, but crop pages 10-20 by 5cm each from bottom and top:
+ bookmaker.py -i INPUT.pdf -c "10-20:0,5,0,5" -o OUTPUT.pdf
+
+Same crops for pages 10-20, but also crop all pages 30 and later by 3cm each from left and right:
+ bookmaker.py -i INPUT.pdf -o OUTPUT.pdf -c "10-20:0,5,0,5" -c "30-end:3,0,3,0"
+
+Rotate by 90° pages 3, 5, 7; rotate page 7 once more by 90% (i.e. 180° in total):
+ bookmaker.py -i INPUT.pdf -o OUTPUT.pdf --rotate 3 -r 5 -r 7 -r 7
+
+Initially declare 5cm crop from the left and 1cm crop from right, but alternate direction between even and odd pages:
+ bookmaker.py -i INPUT.pdf -o OUTPUT.pdf -c "5,0,1,0" -s
+
+Quarter each OUTPUT.pdf page to carry 4 pages from INPUT.pdf, draw stencils into inner margins for cuts to carry binding strings:
+ bookmaker.py -i INPUT.pdf -o OUTPUT.pdf --nup4
+
+Same as --nup4, but define a printable-region margin of 1.3cm to limit the space for the INPUT.pdf pages in OUTPUT.pdf page quarters:
+ bookmaker.py -i INPUT.pdf -o OUTPUT.pdf -n --print_margin 1.3
+
+Same as -n, but draw lines marking printable-region margins, page quarts, spine margins:
+ bookmaker.py -i INPUT.pdf -o OUTPUT.pdf -n --analyze
+
+NOTES:
+
+For arguments like -p, page numbers are assumed to start with 1 (not 0, which is treated as an invalid page number value).
+
+The target page shape so far is assumed to be A4 in portrait orientation; bookmaker.py normalizes all pages to this format before applying crops, and removes any source PDF /Rotate commands (for their production of landscape orientations).
+
+For --nup4, the -c cropping instructions do not so much erase content outside the cropped area, but rather zoom into the page in a way that maximes the cropped area as much as possible into the available per-page area between printable-area margins and the borders to the other quartered pages. If the zoomed cropped area does not fit in neatly into its per-page area, this will preserve additional page content.
+
+The --nup4 quartering puts pages into a specific order optimized for no-tumble duplex print-outs that can easily be folded and cut into pages of a small A6 book. Each unit of 8 pages from the source PDF is mapped thus onto two subsequent pages (i.e. front and back of a printed A4 paper):
+
+ (front) (back)
++-------+ +-------+
+| 4 | 1 | | 2 | 3 |
+|-------| |-------|
+| 8 | 5 | | 6 | 7 |
++-------+ +-------+
+
+To facilitate this layout, --nup4 also pads the input PDF pages to a total number that is a multiple of 8, by adding empty pages if necessary.
+
+(To turn above double-sided example page into a tiny 8-page book: Cut the paper in two on its horizontal middle line. Fold the two halves by their vertical middle lines, with pages 3-2 and 7-6 on the folds' insides. This creates two 4-page books of pages 1-4 and pages 5-8. Fold them both closed and (counter-intuitively) put the book of pages 5-8 on top of the other one (creating a temporary page order of 5,6,7,8,1,2,3,4). A binding cut stencil should be visible on the top left of this stack – cut it out (with all pages folded together) to add the same inner-margin upper cut to each page. Turn around your 8-pages stack to find the mirror image of aforementioned stencil on the stack's back's bottom, and cut that out too. Each page now has binding cuts on top and bottom of its inner margins. Swap the order of both books (back to the final page order of 1,2,3,4,5,6,7,8), and you now have an 8-pages book that can be "bound" in its binding cuts through a rubber band or the like. Repeat with the next 8-pages double-page, et cetera. (Actually, with just 8 pages, the paper may curl under the pressure of a rubber band – but go up to 32 pages or so, and the result will become quite stable.)
+"""
+
+# some helpers
+def validate_page_range(p_string, err_msg_prefix):
+ err_msg = "%s: invalid page range string: %s" % (err_msg_prefix, p_string)
+ if '-' not in p_string:
+ raise ValueError("%s: page range string lacks '-': %s" % (err_msg_prefix, p_string))
+ tokens = p_string.split("-")
+ if len(tokens) > 2:
+ raise ValueError("%s: page range string has too many '-': %s" % (err_msg_prefix, p_string))
+ for i, token in enumerate(tokens):
+ if token == "":
+ continue
+ if i == 0 and token == "start":
+ continue
+ if i == 1 and token == "end":
+ continue
+ try:
+ int(token)
+ except:
+ raise ValueError("%s: page range string carries values that are neither integer, nor 'start', nor 'end': %s" % (err_msg_prefix, p_string))
+ if int(token) < 1:
+ raise ValueError("%s: page range string may not carry page numbers <1: %s" % (err_msg_prefix, p_string))
+ start = -1
+ end = -1
+ try:
+ start = int(tokens[0])
+ end = int(tokens[1])
+ except:
+ pass
+ if start > 0 and end > 0 and start > end:
+ raise ValueError("%s: page range starts higher than it ends: %s" % (err_msg_prefix, p_string))
+
+def split_crops_string(c_string):
+ initial_split = c_string.split(':')
+ if len(initial_split) > 1:
+ page_range = initial_split[0]
+ crops = initial_split[1]
+ else:
+ page_range = None
+ crops = initial_split[0]
+ return page_range, crops
+
+def parse_page_range(range_string, pages):