Sending Text to the Printer (Python)

vegaseat 2 Tallied Votes 4K Views Share

The printer seems to be a much ignored computer peripheral when it comes to programming. This little code snippet explores one way to send text to the default printer. It actually draws the text into an imaginary box on the paper. You can specify the upper left and lower right corners of this box.

# type/draw a text string to the default printer
# needs the win32 extensions package  pywin32-204.win32-py2.4.exe
# from:
# make sure the printer is turned on and ready ...
# tested with Python24    vegaseat    14oct2005

import win32ui
import win32print
import win32con

str1 = \
"""W.H.O. influenza chief Albrecht Stohr is not optimistic that generic producers would be able to
make Tamiflu, the first line of defense against a potential H5N1 bird flu virus pandemic.  He told
reporters in San Diego that the drug has 28 distinct chemical steps and takes a full year to make.
It also involves a dangerous, potentially explosive process step that would drive away all but the
most sophisticated manufacturers. It would take a generic supplier at least "two years" to put such
a complex production plant on stream.

In addition, Stohr said, a starter chemical for Tamiflu is isolated from a Chinese spice called
"star anise", whose seeds are used in flavorings, medicines and cooking oils.  Most of the world
production of "star anise" is located in five provinces of China right now, and the supply has been
back ordered, primarily for the production of Tamiflu by Swiss drug manufacturer Roche.


#str1 = str1 + str1 + str1 + str1  # test height of text area

hDC = win32ui.CreateDC()
print win32print.GetDefaultPrinter()  # test
hDC.StartDoc("Test doc")

# draws text within a box (assume about 1400 dots per inch for typical HP printer)
ulc_x = 1000    # give a left margin
ulc_y = -1000   # give a top margin
lrc_x = 11500   # width of text area-margin, close to right edge of page
lrc_y = -15000  # height of text area-margin, close to bottom of the page
hDC.DrawText(str1, (ulc_x, ulc_y, lrc_x, lrc_y), win32con.DT_LEFT)

Sidney_3 0 Newbie Poster

I took hours trying until I found this code helped a lot, thanks

Djcordeiro 15 Newbie Poster

hello, i´m tying to adapt your code for a Brother QL 700 LABEL,but i'm not getting it.loads the printer name but did not print could help

rproffitt commented: At 15 years ago, it's best to start a new discussion as this is likely what they say? Deprecated. +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.