Zebra Printer/Label maker code explanation
For this example I’m using a Zebra R110Xi4, but all Zebra printers follow the same principles although their might be some differences.
Install
To start using the printer you first have to install the drivers. These are easily found on Printers Support | Zebra by entering your printer.
After downloading the drivers you can follow the installation instructions. Here you must choose the right printer you’re going to be working with.
When the printer is setup, we can start programming to get the information printed on the label.
In the code below we print the product name, gtin, expiry date and batch onto the label in the preferred place, font and size.
Check the printer name
for printer in win32print.EnumPrinters(2):
print(printer[2])
If installed correctly you will see your Zebra-printer in the list.
Note down the name you will need it later.
Zebra-Programming-Language
Zebra uses their own language to dictate how to label will be printed. As an example this is the code we used to print a label with a GS1-barcode and information (make sure u save it in a variable):
ZPL-Language example
zpl = f"""
^XA
^CF0,40
^FO65,40^FDProduct:^FS
^FO235,40^FD{product_name}^FS
^FO65,80^FDGTIN:^FS
^FO235,80^FD{gtin}^FS
^FO65,120^FDExpiry:^FS
^FO235,120^FD{expiry}^FS
^FO65,160^FDBatch:^FS
^FO235,160^FD{batch}^FS
^BY2,2,80
^FO65,225^BCN,80,Y,N,N
^FD>;>801{gtin}17{expiry}10>6{batch}>8^FS
^XZ
"""
To include the programming of RFID tags, the include to following code in the ZPL:
^RS8 ; RFID settings (EPC Gen 2, Automatic settings)
^RF5,5,2,1^FD{RFID}^FS ; write “1234567890” as hex (ASCII) to EPC-memory
^WT ; Start writing
Connecting to the printer
Connecting to the printer can be done in multiple ways depending on the printer-type, but most printers can handle USB or Ethernet. Using the code below, if you want to use Ethernet fill in the host parameter (and port if needed), for USB use fill in the name of the printer (see “Check the printer name” header). Make sure you import ‘win32print’ and ‘socket’ library.
Example Function to connect to the printer
import win32print, socket
def send_zpl_to_printer(zpl, host=None, port=9100, printer_name=None):
if host is not None:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
s.sendall(zpl.encode('utf-8'))
except BaseException as E :
print(f"Some error with connecting to socket server: {E}")
else:
if printer_name is None:
printer_name = win32print.GetDefaultPrinter()
hprinter = win32print.OpenPrinter(printer_name)
try:
job = win32print.StartDocPrinter(hprinter, 1, ("ZPL Label", None, "RAW"))
win32print.StartPagePrinter(hprinter)
win32print.WritePrinter(hprinter, zpl.encode('utf-8'))
win32print.EndPagePrinter(hprinter)
win32print.EndDocPrinter(hprinter)
logger.info("Succesfully send data to printer")
finally:
win32print.ClosePrinter(hprinter)