Send a line of text to an ESC/POS printer in Python using win32print

1.1k Views Asked by At

I am trying to send a line of text to a thermal printer which uses ESC/P using win32api.

I am aware of the existence of python-escpos, but I want to understand how the raw printing works.

The printer is conected and configured as default printer. Printing a default page in windows settings works.

This is the code I am trying. Do I need to use any other escape command before sending the actual test? -I am already sending an ESC+@ initialize command-

import os, sys
import win32print

printer_name = win32print.GetDefaultPrinter ()
print(printer_name)
#
# raw_data could equally be raw PCL/PS read from
#  some print-to-file operation
#
if sys.version_info >= (3,):
    print(1)
    raw_data = bytes ("This is a test", "utf-8")
else:
    print(2)
    raw_data = "This is a test"

hPrinter = win32print.OpenPrinter (printer_name)
try:
    print(3)
    hJob = win32print.StartDocPrinter (hPrinter, 1, ("test of raw data", None, "RAW"))
    try:
        print(4)
        win32print.StartPagePrinter (hPrinter)
        a = win32print.WritePrinter (hPrinter, raw_data)
        print(a)
        win32print.EndPagePrinter (hPrinter)
    finally:
        print(5)
        win32print.EndDocPrinter (hPrinter)
finally:
    print(6)
    win32print.ClosePrinter (hPrinter)
0

There are 0 best solutions below