-
Notifications
You must be signed in to change notification settings - Fork 0
/
scandocument.py
149 lines (121 loc) · 4.72 KB
/
scandocument.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
143
144
145
146
147
148
149
#!/usr/bin/env python
"""
scandocument.py -- Scans a multi-page documents into a .pdf.
Copyright (c) 2011 Sergei Trofimov [email protected].
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
__author__ = 'Sergei Trofimov'
__version__ = (0, 1, 2)
import os
import sys
import logging
from glob import glob
from tempfile import mkdtemp
#logging.basicConfig(level=logging.DEBUG)
scanimage = '/usr/bin/scanimage'
scanimage_opts = {
'resolution': 300,
'format': 'tiff',
}
tiff2ps = '/usr/bin/tiff2ps'
ps2pdf = '/usr/bin/ps2pdf'
pdfjoin = '/usr/bin/pdfjoin'
def make_command(cmd, args, opts):
return ' '.join([cmd,
' '.join(['--{0}={1}'.format(*i) for i in opts.items()]),
' '.join(map(str, args)),
])
def get_response(message):
resp = raw_input(message + ' yes/no: [yes]').lower()
while True:
if resp in 'yes':
return True
elif resp in 'no':
return False
else:
resp = raw_input(message + ' yes/no: [yes]').lower()
def execute_command(commandstring):
logging.debug('executing: {0}'.format(commandstring))
res = os.system(commandstring)
logging.debug('returned: {0}'.format(res))
return res
def scan_page(cmd, cmdopts, outdir, pageno):
outfile = os.path.join(outdir, ''.join(
[os.path.basename(cmd), "{0:02}".format(pageno), '.tiff']
))
args = [' '.join(['>', outfile]), ]
commandstring = make_command(scanimage, args, scanimage_opts)
status = execute_command(commandstring)
if status:
print "ERROR:", status
sys.exit(1)
return get_response('Scan the next page ({0})?'.format(pageno + 1))
def convert_to_pdf(workdir):
for filepath in glob(os.path.join(workdir, '*.tiff')):
print '.',
basename = os.path.splitext(filepath)[0]
psfile = basename + '.ps'
commandstring = '{0} {1} > {2}'.format(tiff2ps, filepath, psfile)
execute_command(commandstring)
logging.debug('removing {0}'.format(filepath))
os.remove(filepath)
pdffile = basename + '.pdf'
commandstring = '{0} {1} {2}'.format(ps2pdf, psfile, pdffile)
execute_command(commandstring)
logging.debug('removing {0}'.format(psfile))
os.remove(psfile)
print
def join_pdf_pages(workdir, outfile):
tempfiles = map(
lambda x: os.path.join(workdir, x), sorted(os.listdir(workdir)))
commandstring = '{0} {1} -o "{2}"'.format(pdfjoin,
' '.join(tempfiles),
os.path.expanduser(outfile))
execute_command(commandstring)
logging.debug('removing ' + workdir)
for f in tempfiles:
os.remove(f)
def print_help():
print 'python scandocument.py [OUTFILE]'
print
print 'Scan a multi-page document into a .pdf file (OUTFILE).'
print 'If OUTFILE isn\'t specifified, it will be read from STDIN.'
print
if __name__ == '__main__':
if len(sys.argv) > 1:
if sys.argv[1] == '-h' or sys.argv[1] == '--help':
print_help()
sys.exit(0)
outfile = sys.argv[1]
else:
outfile = raw_input('Please specify output file: ')
if not outfile.lower().endswith('.pdf'):
outfile += '.pdf'
workdir = mkdtemp()
logging.debug('using temp dir: {0}'.format(workdir))
raw_input('Insert the first page into the scanner and press return.')
page_count = 1
while scan_page(scanimage, scanimage_opts, workdir, page_count):
page_count += 1
print 'Converting...'
convert_to_pdf(workdir)
logging.debug('writing to ' + outfile)
print 'Writing output.'
join_pdf_pages(workdir, outfile)
logging.debug('removing ' + workdir)
os.rmdir(workdir)
print 'Done.'