How do i print to a printer using python?

Eric Brunel eric.brunel at pragmadev.com
Thu Sep 5 04:17:31 EDT 2002


Naveed Iqbal wrote:
> I have to print to a standard printer. I take the data from the
> keyboard and print it using the printer. Please help me....my job
> depends on this!!!!

Things are quite different on Unix and Windows. Just a sample (untested) 
program to print "Hello world!" to the default printer on both platforms:

----Unix----------------------
import os
p = os.popen('lpr', 'w')
p.write("Hello world!\n")
p.close()
------------------------------

----Windows-------------------
import win32ui

dc = win32ui.CreateDC()
dc.CreatePrinterDC()
dc.SetMapMode(4)        # This is UI_MM_LOENGLISH
## With this map mode, 12 points is 12*100/72 units = 16
font = win32ui.CreateFont({'name' : 'Arial', 'height' : 16})
dc.SelectObject(font)

dc.StartDoc("HelloWorld")
dc.StartPage()
dc.TextOut(40, 40, "Hello world!")
dc.EndPage()
dc.EndDoc()
------------------------------

And now you wish you were on Unix ;-)!

For more information on the Windows version, see the documenattion for 
win32ui @ 
http://aspn.activestate.com//ASPN/Python/Reference/Products/ActivePython/PythonWin/modules.html 
and Micro$oft MFC documenation @ 
http://msdn.microsoft.com/library/default.asp

Good luck!

PS: I'm actually a little biased towards Unix... In fact, if you have the 
printer directly connected to your PC, opening LPT1: and just writing the 
text to it should work. But if it's a network printer, the only solution is 
the code above...

We also can make things a little more complicated on Unix by using 
PostScript. But it's still shorter:

import os
p = os.popen('lpr', 'w')
p.write('%!PS\n')
p.write('/Helvetica findfont 12 scalefont setfont\n')
p.write('/cm { 72 mul 2.54 div } def\n')
p.write('1 cm 28 cm moveto\n')
p.write('(Hello world!) show\n')
p.write('showpage\n')
p.close()
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list