[Tutor] Windows printing

Tim Golden mail at timgolden.me.uk
Thu Sep 23 15:22:02 CEST 2010


On 23/09/2010 14:05, Rance Hall wrote:
> For the first roll-out and testing I figured plaintext was good enough.
>
> Future revisions will probably use the PDF library you also referred
> to on your page.
>
> Either way that is as printer ready as I expect I will be able to get it.

One option you might want to consider is to use IE as a print
engine. Here's some code I use to print stuff via IE, converting
it to HTML via Pygments. (Handy for printing Python code).

Obviously you could skip the conversion step and just format your
ticket as HTML in the normal way. The key bit is the multipurpose
ExecWB function. The second param controls whether the printer
selection dialog is shown or not. I generally tell it not to
prompt, which goes to the default. In this example I've set it to
1 which forces a prompt.

<code>
import os, sys
import codecs
import glob
import tempfile
import time

import pygments
from pygments.lexers import get_lexer_for_filename
from pygments.formatters import HtmlFormatter
import win32com.client


css_filepath = os.path.join (os.path.dirname (__file__), "print.css")

def main (fileglob, encoding="utf-8"):
   ie = win32com.client.gencache.EnsureDispatch 
("InternetExplorer.Application")
   html_filepaths = []
   try:
     for filepath in glob.glob (fileglob):
       formatter = HtmlFormatter (
         title=filepath,
         linenos="inline",
         full=True,
         cssfile=css_filepath,
         noclobber_cssfile=True
       )
       lexer = get_lexer_for_filename (filepath)
       with tempfile.NamedTemporaryFile (suffix=".html", delete=False) 
as html_file:
         utext = codecs.open (filepath, encoding=encoding).read ()
         highlighted = pygments.highlight (utext, lexer, formatter)
         html_file.write (highlighted.encode ("utf8"))

       #
       # Load the temporary HTML file up in IE and
       # print it to the default printer, relying
       # on the fact the IE will load Windows filepaths
       # without strictly requiring file:// URLs with
       # escaped paths.
       #
       ie.Navigate (html_file.name)
       while ie.ReadyState != 4 or ie.Busy:
         pass
       ie.ExecWB (6, 1, None, None)
       while ie.ReadyState != 4 or ie.Busy:
         pass
       html_filepaths.append (html_file.name)
   finally:
     #
     # This is arbitrary, but avoids having to implement
     # event handlers. It takes a while for the print
     # handler to complete; wait until it does before
     # closing IE.
     #
     time.sleep (5)
     ie.Quit ()
     for filepath in html_filepaths:
       os.unlink (filepath)

if __name__ == '__main__':
   main (*sys.argv[1:])



</code>

TJG


More information about the Tutor mailing list