File: gmPrinting.py

package info (click to toggle)
gnumed-server 22.15-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 46,556 kB
  • sloc: sql: 1,217,005; python: 15,469; sh: 1,553; makefile: 20
file content (286 lines) | stat: -rw-r--r-- 9,768 bytes parent folder | download | duplicates (4)
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
__doc__ = """GNUmed printing."""

__author__  = "K.Hilbert <Karsten.Hilbert@gmx.net>"
__license__ = 'GPL v2 or later (details at http://www.gnu.org)'
# =======================================================================
import logging
import sys
import os
import io
import time


if __name__ == '__main__':
	sys.path.insert(0, '../../')
from Gnumed.pycommon import gmShellAPI
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmLog2


_log = logging.getLogger('gm.printing')


known_printjob_types = [
	'medication_list',
	'generic_document'
]

external_print_APIs = [
	'gm-print_doc',
	'os_startfile',			# win, mostly
	'gsprint',				# win
	'acrobat_reader',		# win
	'gtklp',				# Linux
	'Internet_Explorer',	# win
	'Mac_Preview'			# MacOSX
]

#=======================================================================
# internal print API
#-----------------------------------------------------------------------
def print_files(filenames=None, jobtype=None, print_api=None, verbose=False):

	_log.debug('printing "%s": %s', jobtype, filenames)

	for fname in filenames:
		try:
			open(fname, 'r').close()
		except Exception:
			_log.exception('cannot open [%s], aborting', fname)
			return False

	if jobtype not in known_printjob_types:
		print("unregistered print job type <%s>" % jobtype)
		_log.warning('print job type "%s" not registered', jobtype)

	if print_api not in external_print_APIs:
		_log.warning('print API "%s" unknown, trying all', print_api)

	if print_api == 'os_startfile':
		return _print_files_by_os_startfile(filenames = filenames)
	if print_api == 'gm-print_doc':
		return _print_files_by_shellscript(filenames = filenames, jobtype = jobtype, verbose = verbose)
	if print_api == 'gsprint':
		return _print_files_by_gsprint_exe(filenames = filenames, verbose = verbose)
	if print_api == 'acrobat_reader':
		return _print_files_by_acroread_exe(filenames = filenames, verbose = verbose)
	if print_api == 'gtklp':
		return _print_files_by_gtklp(filenames = filenames, verbose = verbose)
	if print_api == 'Internet_Explorer':
		return _print_files_by_IE(filenames = filenames)
	if print_api == 'Mac_Preview':
		return _print_files_by_mac_preview(filenames = filenames, verbose = verbose)

	# else try all
	if (sys.platform == 'darwin') or (os.name == 'mac'):
		if _print_files_by_mac_preview(filenames = filenames, verbose = verbose):
			return True
	elif os.name == 'posix':
		if _print_files_by_gtklp(filenames = filenames, verbose = verbose):
			return True
	elif os.name == 'nt':
		if _print_files_by_shellscript(filenames = filenames, jobtype = jobtype, verbose = verbose):
			return True
		if _print_files_by_gsprint_exe(filenames = filenames, verbose = verbose):
			return True
		if _print_files_by_acroread_exe(filenames = filenames, verbose = verbose):
			return True
		if _print_files_by_os_startfile(filenames = filenames):
			return True
		if _print_files_by_IE(filenames = filenames):
			return True
		return False

	if _print_files_by_shellscript(filenames = filenames, jobtype = jobtype, verbose = verbose):
		return True

	return False

#=======================================================================
# external print APIs
#-----------------------------------------------------------------------
def _print_files_by_mac_preview(filenames=None, verbose=False):

#	if os.name != 'mac':				# does not work
	if sys.platform != 'darwin':
		_log.debug('MacOSX <open> only available under MacOSX/Darwin')
		return False
	for filename in filenames:
		cmd_line = [
			'open',				# "open" must be in the PATH
			'-a Preview',		# action = Preview
			filename
		]
		success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
		if not success:
			return False
	return True

#-----------------------------------------------------------------------
def _print_files_by_IE(filenames=None):

	if os.name != 'nt':
		_log.debug('Internet Explorer only available under Windows')
		return False
	try:
		from win32com import client as dde_client
	except ImportError:
		_log.exception('<win32com> Python module not available for use in printing')
		return False
	try:
		i_explorer = dde_client.Dispatch("InternetExplorer.Application")
		for filename in filenames:
			if i_explorer.Busy:
				time.sleep(1)
			i_explorer.Navigate(os.path.normpath(filename))
			if i_explorer.Busy:
				time.sleep(1)
			i_explorer.Document.printAll()
		i_explorer.Quit()
	except Exception:
		_log.exception('error calling IE via DDE')
		return False

	return True

#-----------------------------------------------------------------------
def _print_files_by_gtklp(filenames=None, verbose=False):

#	if os.name != 'posix':
	if sys.platform != 'linux':
		_log.debug('<gtklp> only available under Linux')
		return False
	cmd_line = ['gtklp', '-i', '-# 1']
	cmd_line.extend(filenames)
	success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
	if not success:
		return False
	return True

#-----------------------------------------------------------------------
def _print_files_by_gsprint_exe(filenames=None, verbose=False):
	"""Use gsprint.exe from Ghostscript tools. Windows only.

	- docs: http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm
	- download: http://www.cs.wisc.edu/~ghost/
	"""
	if os.name != 'nt':
		_log.debug('<gsprint.exe> only available under Windows')
		return False
	conf_filename = gmTools.get_unique_filename (
		prefix = 'gm2gsprint-',
		suffix = '.cfg'
	).encode(sys.getfilesystemencoding())
	for filename in filenames:
		conf_file = io.open(conf_filename, mode = 'wt', encoding = 'utf8')
		conf_file.write('-color\n')
		conf_file.write('-query\n')			# printer setup dialog
		conf_file.write('-all\n')			# all pages
		conf_file.write('-copies 1\n')
		conf_file.write('%s\n' % os.path.normpath(filename))
		conf_file.close()
		cmd_line = ['gsprint.exe', '-config', conf_filename]		# "gsprint.exe" must be in the PATH
		success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
		if not success:
			return False
	return True

#-----------------------------------------------------------------------
def _print_files_by_acroread_exe(filenames, verbose=False):
	"""Use Adobe Acrobat Reader. Windows only.

	- docs: http://www.robvanderwoude.com/printfiles.php#PrintPDF
	"""
	if os.name != 'nt':
		_log.debug('Acrobat Reader only used under Windows')
		return False
	for filename in filenames:
		cmd_line = [
			'AcroRd32.exe',					# "AcroRd32.exe" must be in the PATH
			'/s',							# no splash
			'/o',							# no open-file dialog
			'/h',							# minimized
			'/p',							# go straight to printing dialog
			os.path.normpath(filename)
		]
		success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
		if not success:
			# retry with "acroread.exe"
			cmd_line[0] = r'acroread.exe'	# "acroread.exe" must be in the PATH
			success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
			if not success:
				return False
	return True

#-----------------------------------------------------------------------
def _print_files_by_os_startfile(filenames=None):
	try:
		os.startfile
	except AttributeError:
		_log.error('platform does not support "os.startfile()"')
		return False
	for filename in filenames:
		fname = os.path.normcase(os.path.normpath(filename))
		_log.debug('%s -> %s', filename, fname)
		try:
			try:
				os.startfile(fname, 'print')
			except WindowsError as e:
				_log.exception('no <print> action defined for this type of file')
				if e.winerror == 1155:	# try (default) <view> action
					os.startfile(fname)
		except Exception:
			_log.exception('os.startfile() failed')
			gmLog2.log_stack_trace()
			return False
	return True

#-----------------------------------------------------------------------
def _print_files_by_shellscript(filenames=None, jobtype=None, verbose=False):

	paths = gmTools.gmPaths()
	local_script = os.path.join(paths.local_base_dir, '..', 'external-tools', 'gm-print_doc')
	candidates = ['gm-print_doc', local_script, 'gm-print_doc.bat']
	found, binary = gmShellAPI.find_first_binary(binaries = candidates)
	if not found:
		binary = r'gm-print_doc.bat'
	cmd_line = [binary,	jobtype]
	cmd_line.extend(filenames)
	success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
	if not success:
		return False
	return True

#=======================================================================
# main
#-----------------------------------------------------------------------
if __name__ == '__main__':

	if len(sys.argv) < 2:
		sys.exit()

	if sys.argv[1] != 'test':
		sys.exit()

	from Gnumed.pycommon import gmLog2
	from Gnumed.pycommon import gmI18N
	gmI18N.activate_locale()
	gmI18N.install_domain()

	#--------------------------------------------------------------------
	def test_print_files():
		return print_files(filenames = [sys.argv[2]], jobtype = sys.argv[3])
	#--------------------------------------------------------------------
	def test_print_files_by_shellscript():
		print_files(filenames = [sys.argv[2], sys.argv[2]], jobtype = 'generic_document', print_api = 'gm-print_doc')
	#--------------------------------------------------------------------
	def test_print_files_by_gtklp():
		print_files(filenames = [sys.argv[2], sys.argv[2]], jobtype = 'generic_document', print_api = 'gtklp')
	#--------------------------------------------------------------------
	def test_print_files_by_mac_preview():
		print("testing printing via Mac Preview")
		_print_files_by_mac_preview(filenames = [sys.argv[0]])
	#--------------------------------------------------------------------
	print(test_print_files())
	#test_print_files_by_gtklp()
	#test_print_files_by_mac_preview()