+# some basic input validation
+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:
+ fail_with_msg("%s: page range string lacks '-': %s" % (err_msg_prefix, p_string))
+ tokens = p_string.split("-")
+ if len(tokens) > 2:
+ fail_with_msg("%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:
+ fail_with_msg("%s: page range string carries values that are neither integer, nor 'start', nor 'end': %s" % (err_msg_prefix, p_string))
+ if int(token) < 1:
+ fail_with_msg("%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:
+ fail_with_msg("%s: page range starts higher than it ends: %s" % (err_msg_prefix, p_string))
+
+for filename in args.input_file:
+ if not os.path.isfile(filename):
+ fail_with_msg("-i: %s is not a file" % filename)
+ try:
+ with open(filename, 'rb') as file:
+ pypdf.PdfReader(file)
+ except pypdf.errors.PdfStreamError:
+ fail_with_msg("-i: cannot interpret %s as PDF file" % filename)
+if args.page_range:
+ for p_string in args.page_range:
+ validate_page_range(p_string, "-p")
+ if len(args.page_range) > len(args.input_file):
+ fail_with_msg("more -p arguments than -i arguments")
+if args.crops:
+ for c_string in args.crops:
+ initial_split = c_string.split(':')
+ if len(initial_split) > 2:
+ fail_with_msg("-c: cropping string has multiple ':': %s" % c_string)
+ if len(initial_split) > 1:
+ validate_page_range(initial_split[0], "-c")
+ crops = initial_split[1].split(",")
+
+ else:
+ crops = initial_split[0].split(",")
+ if len(crops) != 4:
+ fail_with_msg("-c: cropping should contain three ',': %s" % c_string)
+ for crop in crops:
+ try:
+ float(crop)
+ except:
+ fail_with_msg("-c: non-number crop in %s" % c_string)
+if args.rotate_page:
+ for r in args.rotate_page:
+ try:
+ int(r)
+ except:
+ fail_with_msg("-r: non-integer value: %s" % r)
+ if r < 1:
+ fail_with_msg("-r: value must not be <1: %s" % r)
+try:
+ float(args.print_margin)
+except:
+ fail_with_msg("-m: non-float value: %s" % arg.print_margin)