-
Notifications
You must be signed in to change notification settings - Fork 11
/
tifftopdf.py
142 lines (129 loc) · 4.21 KB
/
tifftopdf.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#!/usr/bin/env python
# file: tifftopdf.py
# vim:fileencoding=utf-8:ft=python
#
# Copyright © 2012-2017 R.F. Smith <rsmith@xs4all.nl>.
# SPDX-License-Identifier: MIT
# Created: 2012-06-29T21:02:55+02:00
# Last modified: 2020-04-01T20:56:47+0200
"""
Convert TIFF files to PDF format.
Using the utilities tiffinfo and tiff2pdf from the libtiff package.
"""
from functools import partial
import argparse
import concurrent.futures as cf
import logging
import os
import re
import subprocess as sp
import sys
__version__ = "2020.04.01"
def main():
"""
Entry point for tifftopdf.
"""
args = setup()
func = tiffconv
if args.jpeg:
logging.info("using JPEG compression.")
func = partial(tiffconv, jpeg=True, quality=args.quality)
with cf.ThreadPoolExecutor(max_workers=os.cpu_count()) as tp:
for fn, rv in tp.map(func, args.files):
if rv == 0:
logging.info(f'finished "{fn}"')
else:
logging.error(f"conversion of {fn} failed, return code {rv}")
def setup():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--log",
default="warning",
choices=["debug", "info", "warning", "error"],
help="logging level (defaults to 'warning')",
)
parser.add_argument("-j", "--jpeg", help="use JPEG compresion", action="store_true")
parser.add_argument(
"-q",
"--quality",
help="JPEG compresion quality (default 85)",
type=int,
default=85,
)
parser.add_argument("-v", "--version", action="version", version=__version__)
parser.add_argument(
"files", metavar="file", nargs="+", help="one or more files to process"
)
args = parser.parse_args(sys.argv[1:])
logging.basicConfig(
level=getattr(logging, args.log.upper(), None),
format="%(levelname)s: %(message)s",
)
logging.debug(f"command line arguments = {sys.argv}")
logging.debug(f"parsed arguments = {args}")
# Check for requisites
try:
for prog in ("tiffinfo", "tiff2pdf"):
sp.run([prog], stdout=sp.DEVNULL, stderr=sp.DEVNULL)
logging.debug(f"found “{prog}”")
except FileNotFoundError:
logging.error(f"required program “{prog}” not found")
sys.exit(1)
return args
def tiffconv(fname, jpeg=False, quality=85):
"""
Start a tiff2pdf process for given file.
Arguments:
name: Name of the tiff file to convert.
jpeg: Use JPEG compression.
quality: JPEG compression quality.
Returns:
A 2-tuple (input filename, tiff2pdf return value).
"""
try:
args = ["tiffinfo", fname]
p = sp.run(args, stdout=sp.PIPE, stderr=sp.DEVNULL)
txt = p.stdout.decode().split()
if "Width:" not in txt:
raise ValueError("no width in TIF")
index = txt.index("Width:")
width = float(txt[index + 1])
length = float(txt[index + 4])
try:
index = txt.index("Resolution:")
xres = float(txt[index + 1][:-1])
yres = float(txt[index + 2])
except ValueError:
xres, yres = None, None
outname = re.sub(r"\.tif{1,2}?$", ".pdf", fname, flags=re.IGNORECASE)
program = ["tiff2pdf"]
if xres:
args = [
"-w",
str(width / xres),
"-l",
str(length / xres),
"-x",
str(xres),
"-y",
str(yres),
"-o",
outname,
fname,
]
else:
args = ["-o", outname, "-z", "-p", "A4", "-F", fname]
logging.warning(f"no resolution in {fname}. Fitting to A4")
if jpeg:
args = program + ["-n", "-j", "-q", str(quality)] + args
else:
args = program + args
logging.info(f'calling "{args}"')
rv = sp.run(args, stdout=sp.DEVNULL, stderr=sp.DEVNULL)
logging.info(f'created "{outname}"')
return (fname, rv.returncode)
except Exception as e:
logging.error(f'starting conversion of "{fname}" failed: {e}')
return (fname, 0)
if __name__ == "__main__":
main()