Package Gnumed :: Package pycommon :: Module gmPrinting |
[frames] | no frames]

# Source Code for Module Gnumed.pycommon.gmPrinting

      1  __doc__ = """GNUmed printing."""
      2
      3  __author__  = "K.Hilbert <Karsten.Hilbert@gmx.net>"
      4  __license__ = 'GPL v2 or later (details at http://www.gnu.org)'
      5  # =======================================================================
      6  import logging
      7  import sys
      8  import os
      9  import io
     10  import time
     11
     12
     13  if __name__ == '__main__':
     14          sys.path.insert(0, '../../')
     15  from Gnumed.pycommon import gmShellAPI
     16  from Gnumed.pycommon import gmTools
     17  from Gnumed.pycommon import gmLog2
     18
     19
     20  _log = logging.getLogger('gm.printing')
     21
     22
     23  known_printjob_types = [
     24          'medication_list',
     25          'generic_document'
     26  ]
     27
     28  external_print_APIs = [
     29          'gm-print_doc',
     30          'os_startfile',                 # win, mostly
     31          'gsprint',                              # win
     32          'acrobat_reader',               # win
     33          'gtklp',                                # Linux
     34          'Internet_Explorer',    # win
     35          'Mac_Preview'                   # MacOSX
     36  ]
     37
     38  #=======================================================================
     39  # internal print API
     40  #-----------------------------------------------------------------------
     41 -def print_files(filenames=None, jobtype=None, print_api=None, verbose=False):
     42
     43          _log.debug('printing "%s": %s', jobtype, filenames)
     44
     45          for fname in filenames:
     46                  try:
     47                          open(fname, 'r').close()
     48                  except:
     49                          _log.exception('cannot open [%s], aborting', fname)
     50                          return False
     51
     52          if jobtype not in known_printjob_types:
     53                  print("unregistered print job type <%s>" % jobtype)
     54                  _log.warning('print job type "%s" not registered', jobtype)
     55
     56          if print_api not in external_print_APIs:
     57                  _log.warning('print API "%s" unknown, trying all', print_api)
     58
     59          if print_api == 'os_startfile':
     60                  return _print_files_by_os_startfile(filenames = filenames)
     61          if print_api == 'gm-print_doc':
     62                  return _print_files_by_shellscript(filenames = filenames, jobtype = jobtype, verbose = verbose)
     63          if print_api == 'gsprint':
     64                  return _print_files_by_gsprint_exe(filenames = filenames, verbose = verbose)
     65          if print_api == 'acrobat_reader':
     66                  return _print_files_by_acroread_exe(filenames = filenames, verbose = verbose)
     67          if print_api == 'gtklp':
     68                  return _print_files_by_gtklp(filenames = filenames, verbose = verbose)
     69          if print_api == 'Internet_Explorer':
     70                  return _print_files_by_IE(filenames = filenames)
     71          if print_api == 'Mac_Preview':
     72                  return _print_files_by_mac_preview(filenames = filenames, verbose = verbose)
     73
     74          # else try all
     75          if (sys.platform == 'darwin') or (os.name == 'mac'):
     76                  if _print_files_by_mac_preview(filenames = filenames, verbose = verbose):
     77                          return True
     78          elif os.name == 'posix':
     79                  if _print_files_by_gtklp(filenames = filenames, verbose = verbose):
     80                          return True
     81          elif os.name == 'nt':
     82                  if _print_files_by_shellscript(filenames = filenames, jobtype = jobtype, verbose = verbose):
     83                          return True
     84                  if _print_files_by_gsprint_exe(filenames = filenames, verbose = verbose):
     85                          return True
     86                  if _print_files_by_acroread_exe(filenames = filenames, verbose = verbose):
     87                          return True
     88                  if _print_files_by_os_startfile(filenames = filenames):
     89                          return True
     90                  if _print_files_by_IE(filenames = filenames):
     91                          return True
     92                  return False
     93
     94          if _print_files_by_shellscript(filenames = filenames, jobtype = jobtype, verbose = verbose):
     95                  return True
     96
     97          return False
     98
     99  #=======================================================================
    100  # external print APIs
    101  #-----------------------------------------------------------------------
    102 -def _print_files_by_mac_preview(filenames=None, verbose=False):
    103
    104  #       if os.name != 'mac':                            # does not work
    105          if sys.platform != 'darwin':
    106                  _log.debug('MacOSX <open> only available under MacOSX/Darwin')
    107                  return False
    108          for filename in filenames:
    109                  cmd_line = [
    110                          'open',                         # "open" must be in the PATH
    111                          '-a Preview',           # action = Preview
    112                          filename
    113                  ]
    114                  success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
    115                  if not success:
    116                          return False
    117          return True
    118
    119  #-----------------------------------------------------------------------
    120 -def _print_files_by_IE(filenames=None):
    121
    122          if os.name != 'nt':
    123                  _log.debug('Internet Explorer only available under Windows')
    124                  return False
    125          try:
    126                  from win32com import client as dde_client
    127          except ImportError:
    128                  _log.exception('<win32com> Python module not available for use in printing')
    129                  return False
    130          try:
    131                  i_explorer = dde_client.Dispatch("InternetExplorer.Application")
    132                  for filename in filenames:
    133                          if i_explorer.Busy:
    134                                  time.sleep(1)
    135                          i_explorer.Navigate(os.path.normpath(filename))
    136                          if i_explorer.Busy:
    137                                  time.sleep(1)
    138                          i_explorer.Document.printAll()
    139                  i_explorer.Quit()
    140          except:
    141                  _log.exception('error calling IE via DDE')
    142                  return False
    143
    144          return True
    145
    146  #-----------------------------------------------------------------------
    147 -def _print_files_by_gtklp(filenames=None, verbose=False):
    148
    149  #       if os.name != 'posix':
    150          if sys.platform != 'linux2':
    151                  _log.debug('<gtklp> only available under Linux')
    152                  return False
    153          cmd_line = ['gtklp', '-i', '-# 1']
    154          cmd_line.extend(filenames)
    155          success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
    156          if not success:
    157                  return False
    158          return True
    159
    160  #-----------------------------------------------------------------------
    161 -def _print_files_by_gsprint_exe(filenames=None, verbose=False):
    162          """Use gsprint.exe from Ghostscript tools. Windows only.
    163
    164          - docs: http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm
    165          - download: http://www.cs.wisc.edu/~ghost/
    166          """
    167          if os.name != 'nt':
    168                  _log.debug('<gsprint.exe> only available under Windows')
    169                  return False
    170          conf_filename = gmTools.get_unique_filename (
    171                  prefix = 'gm2gsprint-',
    172                  suffix = '.cfg'
    173          ).encode(sys.getfilesystemencoding())
    174          for filename in filenames:
    175                  conf_file = io.open(conf_filename, mode = 'wt', encoding = 'utf8')
    176                  conf_file.write('-color\n')
    177                  conf_file.write('-query\n')                     # printer setup dialog
    178                  conf_file.write('-all\n')                       # all pages
    179                  conf_file.write('-copies 1\n')
    180                  conf_file.write('%s\n' % os.path.normpath(filename))
    181                  conf_file.close()
    182                  cmd_line = ['gsprint.exe', '-config', conf_filename]            # "gsprint.exe" must be in the PATH
    183                  success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
    184                  if not success:
    185                          return False
    186          return True
    187
    188  #-----------------------------------------------------------------------
    189 -def _print_files_by_acroread_exe(filenames, verbose=False):
    190          """Use Adobe Acrobat Reader. Windows only.
    191
    192          - docs: http://www.robvanderwoude.com/printfiles.php#PrintPDF
    193          """
    194          if os.name != 'nt':
    195                  _log.debug('Acrobat Reader only used under Windows')
    196                  return False
    197          for filename in filenames:
    198                  cmd_line = [
    199                          'AcroRd32.exe',                                 # "AcroRd32.exe" must be in the PATH
    200                          '/s',                                                   # no splash
    201                          '/o',                                                   # no open-file dialog
    202                          '/h',                                                   # minimized
    203                          '/p',                                                   # go straight to printing dialog
    204                          os.path.normpath(filename)
    205                  ]
    206                  success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
    207                  if not success:
    208                          # retry with "acroread.exe"
    209                          cmd_line[0] = r'acroread.exe'   # "acroread.exe" must be in the PATH
    210                          success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
    211                          if not success:
    212                                  return False
    213          return True
    214
    215  #-----------------------------------------------------------------------
    216 -def _print_files_by_os_startfile(filenames=None):
    217          try:
    218                  os.startfile
    219          except AttributeError:
    220                  _log.error('platform does not support "os.startfile()"')
    221                  return False
    222          for filename in filenames:
    223                  fname = os.path.normcase(os.path.normpath(filename))
    224                  _log.debug('%s -> %s', filename, fname)
    225                  try:
    226                          try:
    227                                  os.startfile(fname, 'print')
    228                          except WindowsError as e:
    229                                  _log.exception('no <print> action defined for this type of file')
    230                                  if e.winerror == 1155:  # try (default) <view> action
    231                                          os.startfile(fname)
    232                  except Exception:
    233                          _log.exception('os.startfile() failed')
    234                          gmLog2.log_stack_trace()
    235                          return False
    236          return True
    237
    238  #-----------------------------------------------------------------------
    239 -def _print_files_by_shellscript(filenames=None, jobtype=None, verbose=False):
    240
    241          paths = gmTools.gmPaths()
    242          local_script = os.path.join(paths.local_base_dir, '..', 'external-tools', 'gm-print_doc')
    243          #candidates = [u'gm-print_doc', u'gm-print_doc.bat', local_script, u'gm-print_doc.bat']
    244          candidates = ['gm-print_doc', local_script, 'gm-print_doc.bat']
    245          found, binary = gmShellAPI.find_first_binary(binaries = candidates)
    246          if not found:
    247                  binary = r'gm-print_doc.bat'
    248          cmd_line = [binary,     jobtype]
    249          cmd_line.extend(filenames)
    250          success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
    251          if not success:
    252                  return False
    253          return True
    254
    255  #=======================================================================
    256  # main
    257  #-----------------------------------------------------------------------
    258  if __name__ == '__main__':
    259
    260          if len(sys.argv) < 2:
    261                  sys.exit()
    262
    263          if sys.argv[1] != 'test':
    264                  sys.exit()
    265
    266          from Gnumed.pycommon import gmLog2
    267          from Gnumed.pycommon import gmI18N
    268          gmI18N.activate_locale()
    269          gmI18N.install_domain()
    270
    271          #--------------------------------------------------------------------
    272 -        def test_print_files():
    273                  return print_files(filenames = [sys.argv[2]], jobtype = sys.argv[3])
    274          #--------------------------------------------------------------------
    275 -        def test_print_files_by_shellscript():
    276                  print_files(filenames = [sys.argv[2], sys.argv[2]], jobtype = 'generic_document', print_api = 'gm-print_doc')
    277          #--------------------------------------------------------------------
    278 -        def test_print_files_by_gtklp():
    279                  print_files(filenames = [sys.argv[2], sys.argv[2]], jobtype = 'generic_document', print_api = 'gtklp')
    280          #--------------------------------------------------------------------
    281 -        def test_print_files_by_mac_preview():
    282                  print("testing printing via Mac Preview")
    283                  _print_files_by_mac_preview(filenames = [sys.argv[0]])
    284          #--------------------------------------------------------------------
    285          print(test_print_files())
    286          #test_print_files_by_gtklp()
    287          #test_print_files_by_mac_preview()
    288