ZPL how-to
Send ZPL to a Zebra printer from Python
A Zebra printer draws the label itself from the ZPL it receives. Your Python only has to get the ZPL there as raw bytes, and the standard library already has what a network printer needs.
What goes wrong
Anything that prints through the printer driver, as a document, renders the ZPL as text: the label comes out with the ZPL source on it, or blank. The bytes have to reach the printer unchanged, by one of the two routes below.
The code needs Python 3.10 or later. The label used throughout, on 4 × 2 inch stock:
^XA
^FO40,40^A0N,50,50^FDHello from Python^FS
^XZA network printer: port 9100
A networked Zebra printer listens on TCP port 9100 and prints whatever ZPL arrives there. Open a connection, send the bytes, close it. It needs nothing outside the standard library.
import socket
def send_zpl(host: str, zpl: str, port: int = 9100) -> None:
# Port 9100 is the printer's raw port: whatever arrives there is printed as ZPL.
with socket.create_connection((host, port), timeout=10) as conn:
conn.sendall(zpl.encode("utf-8"))send_zpl("192.168.1.50", "^XA^FO40,40^A0N,50,50^FDHello from Python^FS^XZ")- Use the printer's IP address or host name. Print a configuration label from the printer to find it.
- Port 9100 has to be reachable from where the code runs. A firewall between them shows up as a
TimeoutErroror aConnectionRefusedError, not as an error from the printer. - Several labels can go in one call, one
^XA…^XZblock after another. - Port 9100 sends nothing back, so a send that succeeds means the printer received the bytes, not that the label printed. To check for an open head or no paper, send
~HSand read the status the printer returns.
A USB printer on Windows: the spooler, in RAW mode
A printer installed in Windows takes jobs through the print spooler. Sent with the data type RAW, the spooler passes the bytes straight to the printer and the driver never renders them. The standard library has no way to do this, so it uses win32print from the pywin32 package (pip install pywin32).
import win32print # pip install pywin32
def send_zpl_windows(printer_name: str, zpl: str) -> None:
# "RAW" tells the spooler to pass the bytes through, so the driver never renders them.
data = zpl.encode("utf-8")
printer = win32print.OpenPrinter(printer_name)
try:
win32print.StartDocPrinter(printer, 1, ("Label", None, "RAW"))
try:
win32print.StartPagePrinter(printer)
written = win32print.WritePrinter(printer, data)
if written != len(data):
raise OSError(f"The spooler took {written} of {len(data)} bytes.")
win32print.EndPagePrinter(printer)
finally:
win32print.EndDocPrinter(printer)
finally:
win32print.ClosePrinter(printer)send_zpl_windows("ZDesigner ZD421-203dpi ZPL", zpl)- For a printer on this machine, the name is the printer's name exactly as Windows shows it under Printers & scanners. For one shared from another machine, use its share path as a raw string,
r"\\server\share": in a plain string,\\is a single backslash. The name Windows shows for a shared printer is not oneOpenPrinteraccepts. - pywin32 raises
pywintypes.errorwhen a call fails, such as for a printer name that does not exist, so there are no return codes to check. - Windows only. On Linux or macOS, send to port 9100, or set the printer up in CUPS as a raw queue so it passes the bytes through.
Things that trip people up
TypeError: a bytes-like object is required. Sockets and the spooler take bytes, not astr. Encode the ZPL with.encode('utf-8'), as the code above does.- The printer prints the ZPL as text. It is not in ZPL mode: some Zebra models also speak EPL or a line-print mode. Set the printer language to ZPL from its menu or its web page.
- Part of a value is missing. A
^or~in your data is read as a command. Printing ^, ~ and _ in ZPL shows the fix. - Accented letters print wrong. The code above sends UTF-8, which the printer only reads as UTF-8 after
^CI28. Accented characters in ZPL shows where it goes.
The same label with zeepler
Send this body to POST https://api.zeepler.com/v1/zeeplify with your API key in the x-api-key header. It is a working request, not an illustration: on every change, our tests run this same file through the API's code and compare the result with the ZPL below.
1{2 "config": {3 "size": "4x2"4 },5 "data": {6 "item": "Hex nut M8",7 "sku": "HN-M8-Z"8 },9 "templates": [10 {11 "type": "Text",12 "dataPath": "item",13 "coords": [40, 40],14 "font": "0,50"15 },16 {17 "type": "BarCode",18 "dataPath": "sku",19 "coords": [40, 120]20 }21 ]22}And the ZPL that comes back, ready to send to the printer:
^XA^MCY^XZ
^XA
^SZ2
^MMT
^MNY
^LL406
^PW812
^LH0,0
^CF0,50^FO40,40^FDHex nut M8^FS
^BY2,2,59^FO40,120^BCN,,N,N,N,A^FDHN-M8-Z^FS
^XZInstead of building ZPL strings in Python, send the values and the layout as JSON, and send whatever comes back to the printer by either route above. This is the Python that sent the request shown, again with only the standard library:
import json
import os
import urllib.request
# The key comes from configuration, never from source code. A missing or
# empty one fails here, not with a 401 from the API.
API_KEY = os.environ.get("ZEEPLER_API_KEY", "")
if not API_KEY:
raise RuntimeError("Set ZEEPLER_API_KEY to your zeepler API key.")
def bin_label(item: str, sku: str) -> str:
body = {
"config": {"size": "4x2"},
"data": {"item": item, "sku": sku},
"templates": [
{"type": "Text", "dataPath": "item", "coords": [40, 40], "font": "0,50"},
{"type": "BarCode", "dataPath": "sku", "coords": [40, 120]},
],
}
request = urllib.request.Request(
"https://api.zeepler.com/v1/zeeplify",
data=json.dumps(body).encode("utf-8"),
headers={"Content-Type": "application/json", "x-api-key": API_KEY},
)
with urllib.request.urlopen(request, timeout=30) as response:
return response.read().decode("utf-8")send_zpl("192.168.1.50", bin_label("Hex nut M8", "HN-M8-Z"))A body the API cannot turn into a label comes back as a 400, which urlopen raises as urllib.error.HTTPError. Read the error's body for the list of problem fields. Nothing reaches the printer.
zeepler escapes ^, ~ and _ in the values for you. When a value has accented letters or any other character outside ASCII, its ZPL sets ^CI28 itself and switches back to ^CI0 at the end of the label.
Sending it
- Call the API from your own server or integration engine, not from a web page. An API key in a browser is a key anyone can copy.
- A successful call answers
200with the ZPL as plain text. A request the API cannot turn into a label answers400with every problem listed by field, and is not billed. - Send the ZPL to a Zebra or other ZPL printer at 203 dpi. At 300 dpi the same label prints at two-thirds of the size.
The API reference has every field and status code.
Related guides
- QR code size in ZPL: How ^BQ magnification sets the size of a QR code, and how to work out the size in dots.
- Printing ^, ~ and _ in ZPL: Why a caret or tilde in your data cuts the field short, and how ^FH prints them.
- Font size in ZPL: Setting text height with ^A and ^CF, converting points to dots, and why ^CF carries over.
- Send ZPL to a Zebra printer from C#: Send ZPL from .NET to a network printer on port 9100, or to a USB printer through the Windows spooler, without the driver redrawing it.
- Code 128 barcodes in ZPL: Set a Code 128 barcode's width and height with ^BY and ^BC, work out its width in dots, and pick subsets A, B and C.
- Accented characters in ZPL (^CI28): Print é, ç, ô and € with ^CI28, switch the printer back with ^CI0, and what to do on older firmware.
- Change a barcode to a QR code in ZPL: Swap ^BC for ^BQ, start the field data with QA, so the first characters scan, and reset the ^BY left over from the barcode.
Help with an integration
Email info@zeepler.com. You will get a reply within 2 business days. The support policy covers response times and version changes.