-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpdf-create-empty
executable file
·55 lines (47 loc) · 1.79 KB
/
pdf-create-empty
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python3
# Dependencies:
# - python3.7 or later
# - gs (Ghostscript)
import argparse, os, re, subprocess, sys
def main(args):
d=args.dimensions
o=args.output
if not o:
o=f'empty-{d}.pdf'
if os.path.exists(o):
die(f'Output file {o} already exists')
dm=m("^([0-9.]+)(pts|pt|in|cm|mm)x([0-9.]+)(pts|pt|in|cm|mm)$", d)
w=None
h=None
try:
w=int(float(dm[1])*({'pts':1,'pt':1,'in':72,'cm':28.3,'mm':2.83}[dm[2]]))
h=int(float(dm[3])*({'pts':1,'pt':1,'in':72,'cm':28.3,'mm':2.83}[dm[4]]))
except:
die('Invalid dimensions')
subprocess.run([
'gs', '-dBATCH', '-dNOPAUSE', '-dSAFER', '-dQUIET',
f'-sOutputFile={o}',
'-sDEVICE=pdfwrite',
f'-dDEVICEWIDTHPOINTS={w}', f'-dDEVICEHEIGHTPOINTS={h}',
], check=True)
print(f'Wrote a pdf file with dimensions {w}x{h} pts to {o}')
def m(pattern, string):
match = re.match(pattern, string, re.DOTALL)
if not match:
return None
if(match.group(0) != string):
die(f'Pattern /${pattern}/ matched only part of string')
ret = []
for index in range((match.lastindex or 0)+1):
ret.append(match.group(index))
return ret
def die(reason):
print(reason, file=sys.stderr)
sys.exit(2)
pyver = sys.version_info
if not (pyver.major == 3 and pyver.minor >= 7):
die("Requires python 3.7 or later")
parser = argparse.ArgumentParser(description='Create an empty, transparent PDF file.')
parser.add_argument('-o', '--output', metavar='FILE', type=str, help='Output PDF file. (default: empty-DIMENSIONS.pdf)')
parser.add_argument('-d', '--dimensions', type=str, default='3inx2in', help='The page dimensions of the file to create. Supports units pts, in, cm, and mm. (default: 3inx2in)')
main(parser.parse_args(sys.argv[1:]))