DEV Community

Cover image for Stop Printing Blurry Barcodes: Generating Native TSPL & ZPL in Plain JavaScript
Ajay Sukhadeve
Ajay Sukhadeve

Posted on

Stop Printing Blurry Barcodes: Generating Native TSPL & ZPL in Plain JavaScript

If you've ever tried printing barcode labels from a web application using standard window.print(), CSS @media print, or rendering an HTML <canvas> to an image, you've probably encountered this frustrating scenario:

On your 4K monitor, the barcode looks razor-sharp. But when it feeds out of a thermal label printer (like a Zebra, TSC, Rollo, Xprinter, or Munbyn), the bars look slightly fuzzy, the edges are jagged, and your warehouse barcode scanner completely refuses to read it.

Here is the dirty secret of thermal printers: They don't have color, and they don't have grayscale. They only know how to burn a dot or leave it blank.

When a browser renders a canvas or SVG, it applies anti-aliasing to smooth out lines. A 203 DPI thermal printhead can't print a "half-black" subpixel—so the printer driver tries to dither it into tiny checkerboard patterns. Those dithered pixels destroy barcode tolerances.

In this deep-dive, we'll look at why canvas-to-printer pipelines fail, how thermal printer command languages (ZPL and TSPL) work under the hood, and how you can generate raw, pixel-perfect label code directly in client-side JavaScript.


The Root Cause: 203 DPI vs. Browser Anti-Aliasing

Most standard industrial and desktop shipping label printers operate at 203 DPI (Dots Per Inch).

  • In metric units, 203 DPI is almost exactly 8 dots per millimeter (203 / 25.4 = 7.992 dots/mm).
  • High-end models run at 300 DPI, which is roughly 11.81 dots per millimeter (~12 dots/mm).

When you draw a barcode with a library onto an HTML <canvas>:

// A typical browser canvas render
ctx.fillStyle = "#000000";
ctx.fillRect(10.5, 20, 2.3, 100); // Fractional pixel coordinates!
Enter fullscreen mode Exit fullscreen mode

Because coordinates or scale factors often land on fractional CSS pixels (e.g., 2.3px), the browser anti-aliases the edge by painting adjacent pixels in gray (rgba(0,0,0,0.4)).

When sent to a thermal printer:

  1. The printer driver receives a bitmap with gray edges.
  2. The thermal head only has binary heating elements (1 = burn ribbon/coating, 0 = off).
  3. The driver applies a halftoning/dithering algorithm (like Floyd-Steinberg).
  4. The sharp straight edge of your barcode bar turns into a ragged zigzag.
  5. A 1D laser scanner or CCD imager measures bar-to-space ratios with strict mathematical tolerances (Code 128 requires precise module widths). The dithered edges create decode errors.

The Solution: Native Printer Control Languages

Instead of rendering a picture of a label and hoping the Windows or Mac spooler dithers it accurately, industrial logistics software speaks to the printer in its native language.

The two most widely used languages in the world are:

  1. ZPL II (Zebra Programming Language): Standard on all Zebra industrial and desktop printers, and emulated by most modern thermal printers.
  2. TSPL / TSPL2 (TSC Printer Language): Native to TSC, TVS, Rongta, Xprinter, Gprinter, Everycom, and the majority of budget thermal printers used across Asia and e-commerce fulfillment centers.

When you send a native command like:

BARCODE 50,50,"128",80,1,0,2,4,"SKU-99214"
Enter fullscreen mode Exit fullscreen mode

The printer firmware itself computes the exact physical dots on its heating element. There is zero anti-aliasing, zero scaling distortion, and zero dithering. Every single line is 100% crisp.


1. Generating ZPL II in JavaScript

ZPL commands are wrapped between ^XA (Start Format) and ^XZ (End Format).

Key commands for barcodes:

  • ^FO<x>,<y>: Field Origin (position in dots from top-left)
  • ^BY<w>,<r>,<h>: Default barcode parameters (w = module width in dots, r = wide-to-narrow bar ratio, h = bar height in dots)
  • ^BC<o>,<h>,<f>,<g>,<e>: Code 128 barcode definition
  • ^FD<data>^FS: Field Data and Field Separator
  • ^A0N,<h>,<w>: Scalable font selection

Here is a clean JavaScript function to build a complete ZPL label:

/**
 * Generate ZPL II for a thermal barcode label
 * @param {Object} options
 * @param {number} options.widthMm - Label width in mm
 * @param {number} options.heightMm - Label height in mm
 * @param {number} options.dpi - 203 or 300
 * @param {string} options.title - Product title or header
 * @param {string} options.barcode - Barcode value (Code 128)
 * @param {string} options.price - Optional price text
 * @returns {string} ZPL command string
 */
function generateZPL({ widthMm, heightMm, dpi = 203, title, barcode, price }) {
  const dpmm = dpi === 300 ? 11.81 : 8.0; // dots per mm
  const totalDotsW = Math.round(widthMm * dpmm);
  const totalDotsH = Math.round(heightMm * dpmm);

  const lines = [
    "^XA",
    `^PW${totalDotsW}`,          // Print width
    `^LL${totalDotsH}`,          // Label length
    "^LH0,0",                   // Label home origin

    // Header Text
    `^FO${Math.round(4 * dpmm)},${Math.round(4 * dpmm)}`,
    `^A0N,${Math.round(3.5 * dpmm)},${Math.round(3.5 * dpmm)}`,
    `^FD${title}^FS`,

    // Barcode: Code 128 (width 2 dots, height ~12mm)
    `^FO${Math.round(4 * dpmm)},${Math.round(9 * dpmm)}`,
    `^BY2,3,${Math.round(12 * dpmm)}`,
    `^BCN,${Math.round(12 * dpmm)},Y,N,N`, // Normal orientation, print interpretation line
    `^FD${barcode}^FS`,

    // Price Footer (if present)
    price ? `^FO${Math.round(4 * dpmm)},${Math.round(23 * dpmm)}^A0N,${Math.round(4 * dpmm)},${Math.round(4 * dpmm)}^FDPrice: ${price}^FS` : "",

    "^XZ"
  ];

  return lines.filter(Boolean).join("\n");
}
Enter fullscreen mode Exit fullscreen mode

2. Generating TSPL / TSPL2 in JavaScript

TSPL syntax is human-readable, imperative, and unit-aware. You can specify coordinates directly in dots or millimeters.

Key TSPL commands:

  • SIZE <w> mm, <h> mm: Label dimensions
  • GAP <m> mm, <n> mm: Distance between label roll die-cuts
  • CLS: Clears the printer image buffer (mandatory before every label)
  • BARCODE <x>,<y>,"code type",<height>,<human_readable>,<rotation>,<narrow_dots>,<wide_dots>,"content"
  • TEXT <x>,<y>,"font",<rotation>,<x-multi>,<y-multi>,"content"
  • PRINT <sets>,<copies>: Trigger print engine

Here is the JavaScript generator for TSPL:

/**
 * Generate TSPL code for TSC/Everycom/Xprinter label printers
 */
function generateTSPL({ widthMm, heightMm, gapMm = 2, title, barcode, price }) {
  const lines = [
    `SIZE ${widthMm} mm, ${heightMm} mm`,
    `GAP ${gapMm} mm, 0 mm`,
    "DIRECTION 1",
    "CLS",

    // Header Text (Font "3" is built-in 12x20 dot ROM font)
    `TEXT 30,30,"3",0,1,1,"${title}"`,

    // Code 128 Barcode: x=30, y=70, height=80 dots, human readable=1, rot=0, narrow=2, wide=4
    `BARCODE 30,70,"128",80,1,0,2,4,"${barcode}"`,

    // Optional Footer Text
    price ? `TEXT 30,190,"3",0,1,1,"MRP: ${price}"` : null,

    "PRINT 1,1"
  ];

  return lines.filter(Boolean).join("\r\n");
}
Enter fullscreen mode Exit fullscreen mode

3. How to Send Raw Code to the Printer from the Browser

Now that you have the raw ZPL or TSPL string in JavaScript, how do you actually print it without a generic printer driver re-rasterizing it?

You have three clean options:

Option A: Direct .prn Download (Zero Setup, Universal)

Create a Blob with MIME type application/octet-stream and trigger a download. On Windows or Mac, users can drag the file into a shared printer queue or use copy label.prn \\localhost\thermal_printer:

function downloadPrnFile(filename, content) {
  const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename.endsWith(".prn") ? filename : `${filename}.prn`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}
Enter fullscreen mode Exit fullscreen mode

Option B: WebUSB or WebSerial API (Driverless Direct Printing!)

Modern Chromium browsers (Chrome, Edge, Opera) support the WebSerial API and WebUSB API. Many thermal printers enumerate as USB CDC or Serial COM devices:

async function printDirectSerial(rawCode) {
  try {
    // Prompt user to select their thermal printer COM port
    const port = await navigator.serial.requestPort();
    await port.open({ baudRate: 9600 }); // standard for TSC/Zebra

    const encoder = new TextEncoder();
    const writer = port.writable.getWriter();
    await writer.write(encoder.encode(rawCode));
    writer.releaseLock();
    await port.close();
    console.log("Printed successfully via WebSerial!");
  } catch (err) {
    console.error("WebSerial print failed:", err);
  }
}
Enter fullscreen mode Exit fullscreen mode

Note: This works completely inside the browser with zero native software installed!

Option C: Zebra Browser Print / Local Relay Agent

For enterprise Zebra setups, Zebra provides a lightweight local localhost WebSocket daemon ("Zebra Browser Print") that accepts ZPL over POST http://localhost:9100/write.


Live Tool & Playground

If you want to test and generate TSPL and ZPL code for custom label sizes (like 50x25mm, 4x6" shipping labels, or jewellery tags) with live code previews and 1-click downloads, I built an interactive tool for it:

👉 TSPL & ZPL Barcode Label Generator on OwnBarcode

It runs 100% client-side in the browser, supports both 203 DPI and 300 DPI, and costs $0. You can also explore the rest of the privacy-first toolkit on ownbarcode.com for bulk barcode exports and check digit calculations.


Takeaways

  • Never rely on window.print() for 203 DPI thermal barcodes if you need high read reliability with laser scanners.
  • Canvas anti-aliasing causes dithering artifacts on 1-bit thermal printheads.
  • Sending raw ZPL or TSPL strings offloads the rasterization to the printer firmware's native vector engine.
  • Modern Web APIs like WebSerial allow web applications to print raw commands directly to hardware without passing through bloated driver dialogs.

Have you tackled thermal printing in your web apps? How are you handling label queues in production? Drop your thoughts or questions in the comments below!

Top comments (0)