# ZPL Label Templates: Build Dynamic Product Labels by API

> Build ZPL label templates with dynamic product names, SKUs, and barcodes. Follow a working Python example, avoid layout errors, and print through an API.

Published 2026-12-03 · https://printscaler.com/blog/zpl-label-templates-dynamic-product-labels

![Thermal printer producing an inventory barcode label beside a scanner and laptop with an abstract label layout](https://printscaler.com/blog/images/zpl-label-templates-dynamic-product-labels-39.jpg)

ZPL label templates combine printer commands with variable data to produce consistent product, inventory, and warehouse labels. Start with a layout sized for your printer’s resolution, substitute validated values, and send the resulting ZPL directly to a compatible label printer. This tutorial builds a reusable 4 × 2-inch product label in Python, then prints it through PrintScaler’s HTTPS API.

## What a reusable ZPL label template contains

ZPL is a printer command language used by Zebra and compatible label printers. Instead of sending a rendered page, you send instructions describing text, barcodes, positions, and label dimensions.

A useful template separates three concerns:

- **Layout:** Where each field appears and how large it is.
- **Data:** Product names, SKUs, storage locations, and barcode values.
- **Delivery:** Which printer receives the finished label and how your application tracks the request.

That separation matters when a warehouse adds a printer or changes its product database. You should be able to update routing without rewriting the label, or change a product name without modifying printer commands.

The example below generates each complete label in your application. It does not require uploading a stored format to printer memory. Stored formats are another ZPL technique, but application-generated templates are straightforward to version, inspect, and deploy across locations.

### Confirm that the printer understands ZPL

A label printer is not automatically a ZPL printer. Check the exact model, firmware, and active command language before using this template. Some devices use another language, and compatibility modes may support only part of ZPL.

For this workflow, use a printer configured to accept RAW ZPL. If your device only supports printing through its operating-system driver, a PDF workflow may be more appropriate. The [ZPL versus PDF guide](https://printscaler.com/blog/zpl-vs-pdf-shipping-labels) explains that format decision in more detail.

## Set label dimensions before positioning fields

ZPL coordinates are measured in dots, not inches or CSS pixels. A template designed for one resolution will not retain its physical size automatically at another resolution.

Use this approximate conversion:

```text
size in dots = size in inches × printer DPI
```

For a 4 × 2-inch label:

| Printer resolution | Approximate width | Approximate height |
|---|---:|---:|
| 203 DPI | 812 dots | 406 dots |
| 300 DPI | 1,200 dots | 600 dots |
| 600 DPI | 2,400 dots | 1,200 dots |

Some printer specifications describe resolution in dots per millimeter, so check the device documentation when exact dimensions matter.

This tutorial uses a **203 DPI printer with 4-inch-wide, 2-inch-long media**. The template declares `^PW812` for print width and `^LL406` for label length. Those commands do not change the installed printhead resolution or replace media calibration.

Before adjusting coordinates, verify:

1. The actual label width and feed length.
2. Whether the stock uses gaps, black marks, or continuous media.
3. The printer’s configured media sensing mode.
4. Its printable width and existing position offsets.

A physically misconfigured printer cannot be fixed reliably by moving every field a few dots in the template.

## Start with this 4 × 2-inch ZPL product label

The following example includes a product name, readable SKU, bin location, and Code 128 barcode:

```text
^XA
^PW812
^LL406
^LH0,0
^FO32,28^A0N,34,30^FB748,2,4,L,0^FDBlue Cotton T-Shirt - Medium^FS
^FO32,126^A0N,28,24^FDSKU: TSHIRT-BLU-M^FS
^FO32,166^A0N,28,24^FDBIN: A-03-12^FS
^BY2,2,76
^FO32,224^BCN,76,Y,N,N^FDTSHIRT-BLU-M^FS
^XZ
```

Save this as a text file for inspection, but send its contents as RAW printer data rather than printing it as a text document.

### Understand the commands you will actually edit

| Command | Purpose in this template |
|---|---|
| `^XA` and `^XZ` | Begin and end one label format |
| `^PW812` | Set the print width in dots |
| `^LL406` | Set the label length in dots |
| `^LH0,0` | Set the label home position |
| `^FOx,y` | Position the next field |
| `^A0N,h,w` | Select font 0, normal orientation, and character dimensions |
| `^FB748,2,4,L,0` | Define a left-aligned text block with up to two lines |
| `^FD` and `^FS` | Begin field data and end the field |
| `^BY2,2,76` | Set barcode module width and other barcode defaults |
| `^BCN,76,Y,N,N` | Print a normal-orientation Code 128 barcode with readable text |

The first number in `^BY2,2,76` makes the narrow barcode module two dots wide. At 203 DPI, that is approximately 0.25 mm. Whether this is appropriate depends on your scanner, print quality, barcode length, and any applicable labeling requirements.

This is an internal inventory-label example, not a certified shipping, GS1, healthcare, or regulated-product label.

## Generate dynamic ZPL labels safely in Python

Do not insert arbitrary database values directly between `^FD` and `^FS`. ZPL has control characters, so a product name containing command-like input can alter the label instead of appearing as ordinary text.

The generator below uses two different rules:

- Human-readable fields accept printable ASCII and are hex-encoded with `^FH`.
- Barcode values accept only a short, explicitly allowed SKU format.

Keeping the barcode rule narrow also avoids accidentally introducing Code 128 control sequences. Adapt the rule deliberately if your identifier system needs additional characters.

```python
import re

SKU_PATTERN = re.compile(r"[A-Z0-9-]{1,16}")


def hex_text(value: str, max_length: int) -> str:
    if not isinstance(value, str):
        raise ValueError("Label text must be a string")
    if not value or len(value) > max_length:
        raise ValueError("Label text is empty or too long")
    if any(ord(char) < 32 or ord(char) > 126 for char in value):
        raise ValueError("This template accepts printable ASCII only")
    return "".join(f"_{byte:02X}" for byte in value.encode("ascii"))


def product_label(name: str, sku: str, location: str) -> str:
    if not isinstance(sku, str) or not SKU_PATTERN.fullmatch(sku):
        raise ValueError("SKU must be 1–16 uppercase letters, digits, or hyphens")

    name_data = hex_text(name, 48)
    sku_data = hex_text(f"SKU: {sku}", 21)
    location_data = hex_text(f"BIN: {location}", 24)

    return f"""^XA
^PW812
^LL406
^LH0,0
^FO32,28^A0N,34,30^FB748,2,4,L,0^FH_^FD{name_data}^FS
^FO32,126^A0N,28,24^FH_^FD{sku_data}^FS
^FO32,166^A0N,28,24^FH_^FD{location_data}^FS
^BY2,2,76
^FO32,224^BCN,76,Y,N,N^FD{sku}^FS
^XZ"""


zpl = product_label(
    name="Blue Cotton T-Shirt - Medium",
    sku="TSHIRT-BLU-M",
    location="A-03-12",
)
```

With `^FH_`, each underscore followed by two hexadecimal digits represents one data byte. Encoding every byte keeps the text-escaping rule simple and consistent.

The length checks are application guardrails, not a guarantee of visual fit. Proportional fonts, long unbroken words, and different product names still require physical testing. For difficult catalogs, create a separate short label name rather than shrinking every product title until it becomes unreadable.

### What about accented characters and other languages?

This example intentionally rejects non-ASCII text. International printing needs an explicit character-encoding strategy plus printer firmware and fonts that support the required characters.

Do not simply remove the validation and assume UTF-8 will work. Validate the complete path—source text, byte encoding, ZPL character-set selection, and available glyphs—on the actual printer model.

## Print the template through PrintScaler

Once your application generates valid ZPL, printing it is a separate HTTPS operation. PrintScaler delivers RAW data to a connected printer, allowing a cloud application to reach hardware at a warehouse or store.

### 1. Connect the printer and install the agent

Connect the printer to a Windows, macOS, Linux, or Raspberry Pi computer. Confirm that the computer recognizes it, then install the [PrintScaler agent](https://printscaler.com/download).

Enter the pairing code in the dashboard to link the computer. The agent runs in the background, starts after reboots, and communicates through an outbound WebSocket connection, without requiring inbound firewall ports.

Use the dashboard’s test-page function to check the connection where supported by the printer setup. Then send a small ZPL label to verify RAW-language compatibility; a general connectivity test alone does not prove that ZPL is supported.

### 2. Identify the target printer

Get the printer’s ID from your PrintScaler setup and associate it with a trusted workstation or warehouse configuration in your application.

Do not let a browser submit an unrestricted printer ID. Your backend should authorize the user and choose among printers permitted for that account or location. Keep the PrintScaler API key on the server.

The [API reference](https://printscaler.com/docs) covers authentication, printers, and print jobs.

### 3. Submit the generated ZPL as RAW data

The following code continues from the Python generator above and uses only Python’s standard library:

```python
import base64
import json
import os
import urllib.request

payload = {
    "printerId": int(os.environ["PRINTSCALER_PRINTER_ID"]),
    "contentType": "raw_base64",
    "content": base64.b64encode(zpl.encode("ascii")).decode("ascii"),
    "title": "Inventory label TSHIRT-BLU-M",
}

request = urllib.request.Request(
    "https://api.printscaler.com/v1/printjobs",
    data=json.dumps(payload).encode("utf-8"),
    headers={
        "Authorization": f"Bearer {os.environ['PRINTSCALER_API_KEY']}",
        "Content-Type": "application/json",
        "X-Idempotency-Key": os.environ["LABEL_PRINT_OPERATION_ID"],
    },
    method="POST",
)

with urllib.request.urlopen(request, timeout=30) as response:
    print(response.read().decode("utf-8"))
```

Configure the environment variables in your server or job worker. `LABEL_PRINT_OPERATION_ID` should be a persisted identifier for this specific print operation, not a newly generated value on every retry.

Use the same key when retrying an uncertain request. An intentional additional label needs a new operation ID. A SKU alone is not a suitable key because the same SKU may legitimately need labels many times.

If you use an AI coding assistant to integrate this into your application, provide the [Markdown API reference](https://printscaler.com/printscaler-api.md) so it can work from the actual endpoint and authentication details.

### 4. Track delivery instead of treating HTTP success as paper output

An accepted API request is not proof that a readable label is attached to the correct item. Jobs can progress through states including `new`, `sent_to_client`, `queued`, `in_progress`, `done`, and error states.

Use [signed print-job webhooks](https://printscaler.com/docs#webhooks) to update your application rather than repeatedly submitting the same label while waiting. Verify webhook signatures and handle repeated deliveries safely.

PrintScaler can queue jobs while a computer is offline and deliver them when it reconnects, subject to configurable expiration. Decide whether an old inventory label should still print after a long interruption. Also avoid interpreting `done` as independent barcode inspection or proof of physical application.

## Validate the template with real products and scanners

A screen preview can catch obvious positioning mistakes, but it cannot reproduce the entire physical printing process. Test with the actual media, printer, ribbon if applicable, and scanner used on the warehouse floor.

Use this acceptance checklist:

1. **Print the shortest and longest supported SKUs.** Check barcode width and readable text.
2. **Test wide product names.** Repeated wide characters can expose text overflow that ordinary names miss.
3. **Inspect all four edges.** Leave room for normal registration variation.
4. **Scan with production equipment.** Test the expected working distance and lighting.
5. **Compare the decoded value with the source SKU.** A successful beep alone is insufficient validation.
6. **Print several consecutive labels.** Look for feed drift or skipped stock.
7. **Test an offline-and-reconnect cycle.** Confirm that queueing behavior matches your operating procedure.

Preserve blank quiet zones around the barcode. Avoid adding borders, location text, or graphics immediately beside it just because unused space is available.

Keep several representative input records with each template version. Reprinting those records after a layout change is a simple regression test.

## Common template problems and their fixes

### The label becomes smaller on a replacement printer

Check resolution first. The same 812-dot width occupies less physical space at 300 DPI than at 203 DPI.

Maintain separate tested templates for each supported resolution, or generate coordinates from a consistent measurement system. Do not scale only `^PW` and `^LL`: font sizes, field positions, barcode modules, and margins also need attention. Barcode modules require sensible integer dot widths.

### Product text overlaps the barcode

Limit the text block and reserve explicit vertical space. Avoid allowing an unlimited product description into a fixed-height label.

Prefer a dedicated label description, a second layout for unusually long names, or a clear validation failure. Silent truncation can remove the distinguishing part of a product name.

### The printer outputs command text or blank labels

Confirm that you submitted `raw_base64`, not a PDF content type, and that the decoded content begins with the expected ZPL format. Then verify printer-language support and the local RAW delivery path.

For a broader diagnostic sequence, see [Zebra printer not printing ZPL](https://printscaler.com/blog/zebra-printer-not-printing-zpl).

### One retry produces an unwanted extra label

Persist the operation ID before the first API call and reuse it after a timeout. Do not automatically reprint solely because your application has not yet received a completion event.

A deliberate reprint should be a distinct, authorized action with its own operation ID and an audit reason in your application.

## Plan for production volume

Keep the template version, input record reference, target printer, and print-operation ID together in your application’s records. This makes it easier to investigate an incorrect label without guessing which layout was active.

PrintScaler charges per print request, not per page. The Free plan includes 100 prints per month and one connected computer, making it useful for initial template testing. Review the [current plans](https://printscaler.com/pricing) when sizing a production deployment.

The API rate limit is 10 requests per second with a burst of 30. Use a controlled worker queue for bulk labeling rather than launching an unrestricted request for every inventory row at once.

## Turn a tested template into a repeatable workflow

Reliable ZPL label templates start with the right dimensions, constrained variable data, and physical barcode testing. Keep template generation separate from delivery, and track each requested label as an identifiable operation.

Once your sample label scans correctly, [create a free PrintScaler account](https://printscaler.com/signup), connect a compatible printer, and send your first dynamically generated label from your application.

## Frequently asked questions

### How do I create a ZPL label template?

Start with the label dimensions and printer resolution, then define fields between ^XA and ^XZ using positioning, text, and barcode commands. Replace example values with validated application data and test the resulting label on the actual printer.

### Can I put variables directly into a ZPL file?

Your application can substitute values into a template before sending the completed ZPL to the printer. Placeholders such as {{sku}} are not automatically interpreted by the printer; your application must replace them, or you must deliberately use ZPL’s stored-format mechanisms.

### Will a 203 DPI ZPL template work on a 300 DPI printer?

It may print, but it will not preserve the intended physical dimensions because coordinates are measured in dots. Adjust positions, fonts, label dimensions, and barcode module widths, then validate the revised template on the 300 DPI device.

### How do I stop product data from changing ZPL commands?

Validate each field and encode human-readable field data using an appropriate ZPL escaping method, such as ^FH hexadecimal indicators. Apply separate, strict validation to barcode data because barcode commands can have their own special input sequences.

### Can I print ZPL label templates from a cloud application?

Yes. Generate the ZPL on your backend and submit it to PrintScaler as raw_base64 or raw_uri using POST https://api.printscaler.com/v1/printjobs. A connected PrintScaler agent delivers the job to the local printer, which must support ZPL.

### Does a successful print request mean the barcode is readable?

No. API acceptance and job status describe the printing workflow, not independent inspection of the physical barcode. Validate labels with production scanners and compare the decoded values with your source records.
