Printing to printer, windows 7

Dave Angel davea at davea.name
Mon Feb 16 22:02:33 EST 2015


On 02/16/2015 09:08 PM, ken.hessel at gmail.com wrote:
> Would seem to be a simple problem.  I just want to print to my printer instead of the console using Python 2.7, Windows 7.  Hours of looking through FAQ's and Google haven't yielded a solution.  Any suggestions appreciated --
>

It is a simple problem.  All you have to do is send the correct bytes to 
a file object that will transfer those bytes to the printer.  It's been 
a long time since I used Windows, but if I recall, you just open the 
device "prn"  or maybe "lpt1" and go.

For example, to print "Hello world" to an Epson MX80, on a local 
parallel port, you'd do

outfile = open("lpt1", "wb")
print >> outfile, "Hello world"

(To be polite, you should use   "\\dev\\lpt1", but I don't know whether 
the simpler form has ever been deprecated by Windows)

Unfortunately, printers have gotten increasingly complicated since the 
days of the MX80.  For example on a HP laser printer, it won't start 
rendering till you send a hex "0c" to it (also known as a formfeed). 
You also may need to control fonts, sizes, justifications, etc., and 
that varies by printer model. Some printers want Postscript.  So you are 
no longer talking to a printer device, but to a complex printer driver.

I'm afraid when I want to print something for the last decade or so, I 
just create some form of document, and use the corresponding program to 
print it for me.  For simple text, I put it in a simple text file, fire 
up emacs, and tell it to print.

If you've managed to get the equivalent of a "print-to-file" output for 
your particular printer, then you can print it by just copying the bytes 
in that file to the "prn" or "lpt1" device.

Depending on the data type you're trying to print, you may be able to 
control the external program from within Python.  For example, if you're 
trying to print a pdf file, I got the following fragment from a google 
search:

import win32api
fname="C:\\somePDF.pdf"
win32api.ShellExecute(0, "print", fname, None,  ".",  0)


In this fragment, you're asking the registered pdf viewer to print it 
for you.  (presumably Acrobat reader or the equivalent)

If you've got a Postscript printer, perhaps the following link will 
help, to print using PIL:
    http://effbot.org/imagingbook/introduction.htm


The conventional way to print to an arbitrary printer, assuming it's 
already installed to your OS, is to use one of the GUI libraries.  If 
your program is already GUI, then this is the way to go.  For example, 
see tkinter, wxpython, qt, ...

In this last case, the drivers and libraries abstract out the particular 
kind of printer, but you need a lot more software to use it.



-- 
DaveA



More information about the Python-list mailing list