<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[ownbarcode]]></title><description><![CDATA[ownbarcode]]></description><link>https://ownbarcode.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 23:16:37 GMT</lastBuildDate><atom:link href="https://ownbarcode.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Stop Printing Blurry Barcodes: Generating Native TSPL & ZPL in Plain JavaScript]]></title><description><![CDATA[Why thermal printers hate HTML canvas, how 203 DPI dithering breaks barcode scanners, and how to generate raw TSPL and ZPL code directly in client-side…]]></description><link>https://ownbarcode.hashnode.dev/stop-printing-blurry-barcodes-generating-native-tspl-zpl-in-plain-javascript</link><guid isPermaLink="true">https://ownbarcode.hashnode.dev/stop-printing-blurry-barcodes-generating-native-tspl-zpl-in-plain-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[hardware]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Ajay Sukhadeve]]></dc:creator><pubDate>Sat, 28 Nov 2026 05:17:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0895b5d57f3d3d7a0634c6/b9a4239d-3c02-4677-ba0b-25e13a805708.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you've ever tried printing barcode labels from a web application using standard <code>window.print()</code>, CSS <code>@media print</code>, or rendering an HTML <code>&lt;canvas&gt;</code> to an image, you've probably encountered this frustrating scenario:</p>
<p>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.</p>
<p>Here is the dirty secret of thermal printers: <strong>They don't have color, and they don't have grayscale. They only know how to burn a dot or leave it blank.</strong></p>
<p>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.</p>
<p>In this deep-dive, we'll look at why canvas-to-printer pipelines fail, how thermal printer command languages (<strong>ZPL</strong> and <strong>TSPL</strong>) work under the hood, and how you can generate raw, pixel-perfect label code directly in client-side JavaScript.</p>
<hr />
<h2>The Root Cause: 203 DPI vs. Browser Anti-Aliasing</h2>
<p>Most standard industrial and desktop shipping label printers operate at <strong>203 DPI</strong> (Dots Per Inch). </p>
<ul>
<li>In metric units, 203 DPI is almost exactly <strong>8 dots per millimeter</strong> (<code>203 / 25.4 = 7.992 dots/mm</code>).</li>
<li>High-end models run at <strong>300 DPI</strong>, which is roughly <strong>11.81 dots per millimeter</strong> (~12 dots/mm).</li>
</ul>
<p>When you draw a barcode with a library onto an HTML <code>&lt;canvas&gt;</code>:</p>
<pre><code class="language-javascript">// A typical browser canvas render
ctx.fillStyle = "#000000";
ctx.fillRect(10.5, 20, 2.3, 100); // Fractional pixel coordinates!
</code></pre>
<p>Because coordinates or scale factors often land on fractional CSS pixels (e.g., <code>2.3px</code>), the browser anti-aliases the edge by painting adjacent pixels in gray (<code>rgba(0,0,0,0.4)</code>).</p>
<p>When sent to a thermal printer:</p>
<ol>
<li>The printer driver receives a bitmap with gray edges.</li>
<li>The thermal head only has binary heating elements (<code>1</code> = burn ribbon/coating, <code>0</code> = off).</li>
<li>The driver applies a halftoning/dithering algorithm (like Floyd-Steinberg).</li>
<li>The sharp straight edge of your barcode bar turns into a ragged zigzag.</li>
<li>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.</li>
</ol>
<hr />
<h2>The Solution: Native Printer Control Languages</h2>
<p>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.</p>
<p>The two most widely used languages in the world are:</p>
<ol>
<li><strong>ZPL II (Zebra Programming Language)</strong>: Standard on all Zebra industrial and desktop printers, and emulated by most modern thermal printers.</li>
<li><strong>TSPL / TSPL2 (TSC Printer Language)</strong>: Native to TSC, TVS, Rongta, Xprinter, Gprinter, Everycom, and the majority of budget thermal printers used across Asia and e-commerce fulfillment centers.</li>
</ol>
<p>When you send a native command like:</p>
<pre><code class="language-text">BARCODE 50,50,"128",80,1,0,2,4,"SKU-99214"
</code></pre>
<p>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.</p>
<hr />
<h2>1. Generating ZPL II in JavaScript</h2>
<p>ZPL commands are wrapped between <code>^XA</code> (Start Format) and <code>^XZ</code> (End Format).</p>
<p>Key commands for barcodes:</p>
<ul>
<li><code>^FO&lt;x&gt;,&lt;y&gt;</code>: Field Origin (position in dots from top-left)</li>
<li><code>^BY&lt;w&gt;,&lt;r&gt;,&lt;h&gt;</code>: Default barcode parameters (<code>w</code> = module width in dots, <code>r</code> = wide-to-narrow bar ratio, <code>h</code> = bar height in dots)</li>
<li><code>^BC&lt;o&gt;,&lt;h&gt;,&lt;f&gt;,&lt;g&gt;,&lt;e&gt;</code>: Code 128 barcode definition</li>
<li><code>^FD&lt;data&gt;^FS</code>: Field Data and Field Separator</li>
<li><code>^A0N,&lt;h&gt;,&lt;w&gt;</code>: Scalable font selection</li>
</ul>
<p>Here is a clean JavaScript function to build a complete ZPL label:</p>
<pre><code class="language-javascript">/**
 * 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");
}
</code></pre>
<hr />
<h2>2. Generating TSPL / TSPL2 in JavaScript</h2>
<p>TSPL syntax is human-readable, imperative, and unit-aware. You can specify coordinates directly in dots or millimeters.</p>
<p>Key TSPL commands:</p>
<ul>
<li><code>SIZE &lt;w&gt; mm, &lt;h&gt; mm</code>: Label dimensions</li>
<li><code>GAP &lt;m&gt; mm, &lt;n&gt; mm</code>: Distance between label roll die-cuts</li>
<li><code>CLS</code>: Clears the printer image buffer (mandatory before every label)</li>
<li><code>BARCODE &lt;x&gt;,&lt;y&gt;,"code type",&lt;height&gt;,&lt;human_readable&gt;,&lt;rotation&gt;,&lt;narrow_dots&gt;,&lt;wide_dots&gt;,"content"</code></li>
<li><code>TEXT &lt;x&gt;,&lt;y&gt;,"font",&lt;rotation&gt;,&lt;x-multi&gt;,&lt;y-multi&gt;,"content"</code></li>
<li><code>PRINT &lt;sets&gt;,&lt;copies&gt;</code>: Trigger print engine</li>
</ul>
<p>Here is the JavaScript generator for TSPL:</p>
<pre><code class="language-javascript">/**
 * 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");
}
</code></pre>
<hr />
<h2>3. How to Send Raw Code to the Printer from the Browser</h2>
<p>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?</p>
<p>You have three clean options:</p>
<h3>Option A: Direct <code>.prn</code> Download (Zero Setup, Universal)</h3>
<p>Create a <code>Blob</code> with MIME type <code>application/octet-stream</code> and trigger a download. On Windows or Mac, users can drag the file into a shared printer queue or use <code>copy label.prn \\localhost\thermal_printer</code>:</p>
<pre><code class="language-javascript">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);
}
</code></pre>
<h3>Option B: WebUSB or WebSerial API (Driverless Direct Printing!)</h3>
<p>Modern Chromium browsers (Chrome, Edge, Opera) support the <strong>WebSerial API</strong> and <strong>WebUSB API</strong>. Many thermal printers enumerate as USB CDC or Serial COM devices:</p>
<pre><code class="language-javascript">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);
  }
}
</code></pre>
<p><em>Note: This works completely inside the browser with zero native software installed!</em></p>
<h3>Option C: Zebra Browser Print / Local Relay Agent</h3>
<p>For enterprise Zebra setups, Zebra provides a lightweight local localhost WebSocket daemon ("Zebra Browser Print") that accepts ZPL over <code>POST http://localhost:9100/write</code>.</p>
<hr />
<h2>Live Tool &amp; Playground</h2>
<p>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, check out the interactive tool:</p>
<p>👉 <strong><a href="https://ownbarcode.com/tspl-zpl-label-code">TSPL &amp; ZPL Barcode Label Generator on OwnBarcode</a></strong></p>
<p>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 <a href="https://ownbarcode.com/">ownbarcode.com</a> for bulk barcode exports and check digit calculations.</p>
<hr />
<h2>Takeaways</h2>
<ul>
<li><strong>Never rely on <code>window.print()</code> for 203 DPI thermal barcodes</strong> if you need high read reliability with laser scanners.</li>
<li>Canvas anti-aliasing causes dithering artifacts on 1-bit thermal printheads.</li>
<li>Sending raw <strong>ZPL</strong> or <strong>TSPL</strong> strings offloads the rasterization to the printer firmware's native vector engine.</li>
<li>Modern Web APIs like <strong>WebSerial</strong> allow web applications to print raw commands directly to hardware without passing through bloated driver dialogs.</li>
</ul>
<p>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!</p>
]]></content:encoded></item><item><title><![CDATA[I built a barcode generator that never sends your data to a server. Printing was the hard part.]]></title><description><![CDATA[Notes from building ownbarcode.com: client-side PDF writer, Excel corruption detection, and printer dot snapping.]]></description><link>https://ownbarcode.hashnode.dev/i-built-a-barcode-generator-that-never-sends-your-data-to-a-server-printing-was-the-hard-part</link><guid isPermaLink="true">https://ownbarcode.hashnode.dev/i-built-a-barcode-generator-that-never-sends-your-data-to-a-server-printing-was-the-hard-part</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[privacy]]></category><category><![CDATA[open source]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Ajay Sukhadeve]]></dc:creator><pubDate>Thu, 26 Nov 2026 22:39:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0895b5d57f3d3d7a0634c6/4a3a9287-ff07-47d9-b0dc-a14ecef09a81.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Drawing a barcode in the browser is easy. JsBarcode does it in one line.</p>
<p>Getting that barcode to <strong>print at the right size, on a cheap thermal label printer, and still scan</strong> took far longer than the drawing part. This post covers the problems I ran into while building <a href="https://ownbarcode.com/">ownbarcode</a>, a free barcode and label generator for small sellers, and how I fixed them in plain JavaScript.</p>
<p>All of it runs in the browser. No sign-up, no upload, no analytics script. Product names, prices and SKUs never leave the page.</p>
<h2>Why client-side only</h2>
<p>Most of my users are small shops and online sellers in India. They print MRP stickers, Amazon FNSKU labels and carton labels on 50 × 25 mm thermal rolls.</p>
<p>Many free generators I tried had at least one of these problems:</p>
<ul>
<li>A watermark, or "free for non-commercial use only"</li>
<li>A sign-up wall before you can download</li>
<li>Your whole product list goes to their server for a bulk job</li>
<li>A PNG at screen resolution, which prints blurry</li>
</ul>
<p>Rendering in the browser fixes the privacy problem and the cost problem in one move. A static site can't leak data it never receives. It also costs almost nothing to host, so there's no reason to add a paywall.</p>
<p>The stack is deliberately boring:</p>
<ul>
<li>Static HTML pages, built with a few Python scripts</li>
<li><a href="https://github.com/lindell/JsBarcode">JsBarcode</a> for 1D codes, <a href="https://github.com/metafloor/bwip-js">bwip-js</a> for PDF417, Data Matrix and GS1, a small QR library</li>
<li><a href="https://sheetjs.com/">SheetJS</a> (vendored, not from a CDN) for Excel import</li>
<li>Everything else is hand-written</li>
</ul>
<h2>Problem 1: "Print" in the browser ruins the scale</h2>
<p>The first version used <code>window.print()</code>. On paper the barcode came out 3–8% too small or too large. That depended on the browser, the printer driver and whether "Fit to page" was on (it usually is).</p>
<p>That's a real problem. An EAN-13 barcode has a minimum size: bars too thin, and cheap scanners fail.</p>
<p>The fix was to stop letting the browser decide the size. I wrote a small PDF writer that reads the barcode SVG and outputs a PDF <strong>whose page is exactly the label size in millimetres</strong>.</p>
<p>PDF units are points (1/72 inch), so the core of it is one constant:</p>
<pre><code class="language-js">var MM = 72 / 25.4; // points per millimetre

// A 50 × 25 mm label becomes a 141.73 × 70.87 pt page
var mediaBox = [0, 0, 50 * MM, 25 * MM];
</code></pre>
<p>Then each SVG <code>&lt;rect&gt;</code> and <code>&lt;path&gt;</code> becomes a PDF drawing command. Bars stay as vectors, so they're sharp at any printer resolution.</p>
<p>Two details made a big difference:</p>
<p><strong>1. Force colours to pure black or white.</strong> Thermal printers have no grey. A <code>#222</code> bar can come out dithered and fuzzy, so every colour is pushed to one of two values:</p>
<pre><code class="language-js">// returns null for no paint, 0 for black, 1 for white
function tone(c) {
  if (c == null) return undefined;
  c = String(c).trim().toLowerCase();
  if (!c || c === 'none' || c === 'transparent') return null;
  if (c === 'white') return 1;
  if (c === 'black' || c === 'currentcolor') return 0;
  // ...parse hex / rgb(), then threshold on brightness
}
</code></pre>
<p><strong>2. Tell the PDF viewer not to scale it.</strong> The PDF catalog gets <code>/ViewerPreferences &lt;&lt; /PrintScaling /None &gt;&gt;</code>. Not every viewer respects it, so the print dialog still says to choose 100% / Actual size. Together, these remove the "Fit to page" default that was causing most of the size errors.</p>
<p>The whole writer is about 12 KB unminified, with no dependencies. It only supports what my own SVGs use: <code>&lt;rect&gt;</code>, <code>&lt;path&gt;</code> (M, L, H, V, C, Z), <code>&lt;g&gt;</code> transforms and <code>&lt;text&gt;</code>. Writing a full SVG-to-PDF converter would have been a much bigger project.</p>
<h2>Problem 2: Excel eats barcodes</h2>
<p>The bulk generator lets you upload a spreadsheet of products and get a sheet of labels. A typical spreadsheet of product codes, saved as CSV, looks like this:</p>
<pre><code>8.90123E+12,Ajwain 50 g,45
</code></pre>
<p>That was meant to be <code>8901234567890</code>. Excel had stored it as a number, displayed it in scientific notation, and the CSV export kept the display version. Leading zeros on UPC codes vanish the same way: <code>012345678905</code> becomes <code>12345678905</code>.</p>
<p>Silently turning these into barcodes would be the worst possible outcome. The seller would print 500 labels with the wrong code.</p>
<p>So the importer does three things:</p>
<ol>
<li><strong>Reads <code>.xlsx</code> directly</strong>, not just CSV, so it can see the stored cell text and number format instead of the rounded value.</li>
<li><strong>Flags anything that looks damaged.</strong> It checks for <code>E+</code> notation, codes that are one digit short of a valid length, and failed check digits. It shows a warning instead of guessing.</li>
<li><strong>Parses in a Web Worker</strong>, so a large sheet doesn't freeze the page.</li>
</ol>
<p>The worker also checks magic bytes before handing the file to SheetJS. That way a renamed <code>.csv</code> or a random file gets a clear error:</p>
<pre><code class="language-js">const bytes = new Uint8Array(data.buffer);
const zipped   = bytes[0] === 0x50 &amp;&amp; bytes[1] === 0x4b &amp;&amp; bytes[2] === 3 &amp;&amp; bytes[3] === 4; // .xlsx
const compound = [0xd0,0xcf,0x11,0xe0,0xa1,0xb1,0x1a,0xe1].every((b, i) =&gt; bytes[i] === b); // old .xls
if (!zipped &amp;&amp; !compound) throw Error('This is not a valid .xlsx or .xls workbook.');
</code></pre>
<p>The file is read with <code>file.arrayBuffer()</code> and passed to the worker. No <code>fetch</code>, no upload.</p>
<h2>Problem 3: printer dots are not millimetres</h2>
<p>A 203 dpi thermal printer, the most common kind in small shops, prints dots that are 25.4 / 203 ≈ <strong>0.125 mm</strong> wide. It cannot print a bar 0.33 mm wide, which is the nominal EAN-13 module width. It prints either 2 dots (0.25 mm) or 3 dots (0.375 mm).</p>
<p>If you send it 0.33 mm anyway, the driver rounds each bar on its own. Some bars become 2 dots, some 3. The bar-to-space ratios that the scanner depends on drift, and you get a barcode that looks fine but scans badly.</p>
<p>The fix is to choose the module width in <strong>whole printer dots</strong> first, then build everything else from that:</p>
<pre><code class="language-js">// simplified
function snapModule(targetMm, dpi) {
  const dotMm = 25.4 / dpi;
  const dots = Math.max(1, Math.round(targetMm / dotMm));
  return { dots, mm: dots * dotMm };
}

snapModule(0.33, 203); // { dots: 3, mm: 0.375 } -&gt; about 114% of nominal size, inside EAN's 80–200% range
snapModule(0.33, 300); // { dots: 4, mm: 0.339 }
</code></pre>
<p>The site also has a scan check page built on the same idea. It renders the barcode at the printer's real resolution and decodes the bars back from the bitmap. Then it repeats that test with half a dot of "ink spread" added to every bar, to see if it would still read on a slightly worn print head. It's not a replacement for a real scanner, but it catches the obvious mistakes before you waste a roll of labels.</p>
<h2>Problem 4: Hindi on a printer with no Hindi font</h2>
<p>Indian MRP labels often need Hindi text and the ₹ sign. Most thermal printers have built-in fonts for ASCII only. Send them Devanagari through TSPL or ZPL text commands and you get boxes or nothing.</p>
<p>The solution is to stop sending text at all. The browser already renders Hindi perfectly, so:</p>
<ol>
<li>Draw the whole label (text, ₹ price and barcode) on a canvas at the printer's exact dot size, for example about 400 × 200 dots for 50 × 25 mm at 203 dpi.</li>
<li>Threshold it to a 1-bit image. No greys, just like the PDF writer.</li>
<li>Send it as a bitmap: <code>BITMAP</code> for TSPL printers (TSC, TVS), <code>^GFA</code> for ZPL (Zebra), with compression on the ZPL side to keep files small.</li>
</ol>
<p>The printer doesn't need to know any Hindi. It just prints dots. The barcode data itself always stays ASCII digits, because that's what scanners and retail systems expect.</p>
<p>The PDF writer does the same thing on a smaller scale. Plain ASCII text is written as real PDF text in Helvetica or Courier. Any string with Hindi or ₹ is drawn as a sharp 1-bit image at 600 dpi instead, because embedding a Devanagari font would add hundreds of KB to every PDF.</p>
<h2>What I'd do differently</h2>
<ul>
<li><strong>Test on a real printer much earlier.</strong> My own tests parse the generated PDF, rasterise it and decode the barcodes back, and they pass. But a real printer and a roll of labels will show problems that no unit test finds.</li>
<li><strong>Ship fewer formats at first.</strong> EAN-13, Code 128 and QR cover most of what small sellers need. ITF-14, GS1-128 and PDF417 came later, and they could have waited.</li>
<li><strong>Make the Hindi version from day one, not as a translation.</strong> Hindi-speaking sellers search differently and ask different questions. The Hindi pages are their own pages, not a copy of the English ones.</li>
</ul>
<h2>Try it, break it</h2>
<p>The site is at <strong><a href="https://ownbarcode.com/">ownbarcode.com</a></strong> (Hindi: <a href="https://ownbarcode.com/hi/">ownbarcode.com/hi/</a>). It covers EAN-13, UPC-A, Code 128, Code 39, ITF-14, QR, Data Matrix, PDF417 and GS1-128. It also has MRP labels, bulk labels from Excel, and TSPL/ZPL code for thermal printers.</p>
<p>Some honest gaps: the TSPL/ZPL output and the Hindi bitmap labels haven't been tested on every printer model yet. If you own a TSC, TVS, Zebra or any other label printer and something prints wrong, I'd really like to hear about it in the comments.</p>
<p>And if you've solved the "browser print scaling" problem in a better way than generating a PDF, please tell me how.</p>
]]></content:encoded></item><item><title><![CDATA[Validating EAN and UPC barcodes in JavaScript, and catching what Excel does to them]]></title><description><![CDATA[A 10-line check digit function, plus five ways a spreadsheet quietly corrupts product codes]]></description><link>https://ownbarcode.hashnode.dev/validating-ean-and-upc-barcodes-in-javascript-and-catching-what-excel-does-to-them</link><guid isPermaLink="true">https://ownbarcode.hashnode.dev/validating-ean-and-upc-barcodes-in-javascript-and-catching-what-excel-does-to-them</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[excel]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Ajay Sukhadeve]]></dc:creator><pubDate>Thu, 26 Nov 2026 20:49:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0895b5d57f3d3d7a0634c6/1e64a019-595d-4af6-a97f-0a1d2da8a0f7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you build anything that handles product data, like an inventory app, a store import or a label printer, you will get barcode numbers from spreadsheets. Some of them will be broken, and nothing will tell you.</p>
<p>This post covers two things:</p>
<ol>
<li>How the GS1 check digit works (EAN-13, UPC-A, EAN-8, GTIN-14) and a short JavaScript function to validate it.</li>
<li>Five ways spreadsheets corrupt barcode numbers, and how to catch each one before you print 500 wrong labels.</li>
</ol>
<p>All code is plain JavaScript with no dependencies.</p>
<h2>How the check digit works</h2>
<p>The last digit of every EAN or UPC code is a check digit, calculated from the other digits. Scanners use it to catch misreads. You can use it to catch bad data.</p>
<p>The rule is the same for all GS1 codes, as long as you <strong>count from the right</strong>:</p>
<ol>
<li>Take every digit except the last one.</li>
<li>Starting from the rightmost of those, multiply digits by 3, 1, 3, 1, ... in turn.</li>
<li>Add the results.</li>
<li>The check digit is whatever brings the total up to the next multiple of 10.</li>
</ol>
<p>Example: <code>400638133393</code> + check digit.</p>
<table>
<thead>
<tr>
<th>Digit (right to left)</th>
<th>3</th>
<th>9</th>
<th>3</th>
<th>3</th>
<th>3</th>
<th>1</th>
<th>8</th>
<th>3</th>
<th>6</th>
<th>0</th>
<th>0</th>
<th>4</th>
</tr>
</thead>
<tbody><tr>
<td>Weight</td>
<td>3</td>
<td>1</td>
<td>3</td>
<td>1</td>
<td>3</td>
<td>1</td>
<td>3</td>
<td>1</td>
<td>3</td>
<td>1</td>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>Product</td>
<td>9</td>
<td>9</td>
<td>9</td>
<td>3</td>
<td>9</td>
<td>1</td>
<td>24</td>
<td>3</td>
<td>18</td>
<td>0</td>
<td>0</td>
<td>4</td>
</tr>
</tbody></table>
<p>The sum is 89. The next multiple of 10 is 90, so the check digit is <strong>1</strong>, and the full EAN-13 is <code>4006381333931</code>.</p>
<p>Counting from the right is the trick that makes one function work for every length. In an EAN-13, the weights from the left are 1, 3, 1, 3, .... In a UPC-A they are 3, 1, 3, 1, .... Both are 3, 1, 3, 1, ... from the right.</p>
<pre><code class="language-js">function gs1CheckDigit(body) {
  let sum = 0;
  for (let i = 0; i &lt; body.length; i++) {
    const d = body.charCodeAt(body.length - 1 - i) - 48; // '0' is char code 48
    sum += i % 2 === 0 ? d * 3 : d;
  }
  return (10 - (sum % 10)) % 10;
}

function isValidGtin(code) {
  if (!/^\d+$/.test(code) || ![8, 12, 13, 14].includes(code.length)) return false;
  return gs1CheckDigit(code.slice(0, -1)) === Number(code.at(-1));
}

gs1CheckDigit('400638133393'); // 1
isValidGtin('4006381333931');  // true  (EAN-13)
isValidGtin('036000291452');   // true  (UPC-A)
isValidGtin('4006381333932');  // false
</code></pre>
<p>Always keep barcodes as <strong>strings</strong>, never numbers. The next section shows why.</p>
<p>A valid check digit only proves the number is well-formed. It does not prove the number is registered to the brand. Real retail barcodes come from GS1, so a made-up number with a correct check digit can still be rejected by a marketplace or a supermarket.</p>
<h2>Five ways spreadsheets corrupt barcodes</h2>
<h3>1. Scientific notation: <code>8.90123E+12</code></h3>
<p>Excel stores a 13-digit code as a number and may show it as <code>8.90123E+12</code>. If the file is saved as CSV, that display text is often what ends up in the file.</p>
<p><strong>This one can't be fixed in code.</strong> The last digits are gone, and <code>8.90123E+12</code> could be thousands of different barcodes. The only safe action is to reject the row and ask for the column to be re-exported as text.</p>
<pre><code class="language-js">/^\d+(\.\d+)?e\+?\d+$/i.test('8.90123E+12'); // true -&gt; reject the row
</code></pre>
<h3>2. Lost leading zeros: <code>36000291452</code></h3>
<p>UPC-A codes often start with 0. Stored as a number, <code>036000291452</code> becomes <code>36000291452</code>, which is 11 digits.</p>
<p>You can detect it: if an 11-digit value becomes a valid UPC-A when you add a <code>0</code> in front, it probably lost its zero. But <strong>flag it and don't fix it silently</strong>. About 1 in 10 random 11-digit numbers will pass that check by chance.</p>
<h3>3. Precision loss above 15 digits</h3>
<p>Excel keeps only 15 significant digits. That's fine for EAN-13 and GTIN-14. But an 18-digit SSCC shipping code is silently rounded:</p>
<pre><code>Typed:  376123450000000017
Stored: 376123450000000000
</code></pre>
<p>JavaScript numbers have the same kind of limit (about 15–16 digits), so <code>Number('376123450000000017')</code> gives the same wrong value. Another reason to keep everything as strings.</p>
<p>A heuristic: an 18-digit value ending in several zeros, with a check digit that fails, is very likely a rounded SSCC.</p>
<h3>4. A trailing <code>.0</code>: <code>4006381333931.0</code></h3>
<p>This usually comes from a script, not from Excel. In pandas, a column of codes with one empty cell becomes a float column. Export it and every code gets <code>.0</code> on the end.</p>
<p>This one is safe to fix: strip a trailing <code>.0</code> and validate what's left.</p>
<h3>5. Thousands separators and invisible spaces</h3>
<p>If the cell was formatted as a number with separators, you get <code>4,006,381,333,931</code>. If someone copied codes from a web page or a PDF, you can get non-breaking spaces (<code>\u00a0</code>) or zero-width spaces (<code>\u200b</code>) that you can't see.</p>
<p>Strip whitespace, including the invisible kinds. Treat commas as a warning, because they mean the column was a number and may also have lost zeros or digits.</p>
<h2>Putting it together</h2>
<pre><code class="language-js">function inspectCode(raw) {
  const s = String(raw).replace(/[\s\u00a0\u200b]/g, '');

  if (/^\d+(\.\d+)?e\+?\d+$/i.test(s))
    return { ok: false, problem: 'Scientific notation: digits are lost. Re-export the column as text.' };

  if (/^\d{1,3}(,\d{3})+$/.test(s))
    return { ok: false, problem: 'Thousands separators: the cell was formatted as a number.' };

  const v = s.replace(/\.0+$/, '');
  if (isValidGtin(v))
    return { ok: true, value: v, note: v !== s ? 'Removed a trailing .0' : undefined };

  if (/^\d{11}$/.test(v) &amp;&amp; isValidGtin('0' + v))
    return { ok: false, suggestion: '0' + v, problem: 'Looks like a UPC-A that lost its leading zero.' };

  if (/^\d{12}$/.test(v))
    return { ok: false, problem: `Check digit fails. As an EAN-13 body, the check digit would be ${gs1CheckDigit(v)}.` };

  return { ok: false, problem: 'Not a valid EAN/UPC/GTIN.' };
}
</code></pre>
<p>Running it on some typical spreadsheet values:</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Result</th>
</tr>
</thead>
<tbody><tr>
<td><code>8.90123E+12</code></td>
<td>rejected, digits lost</td>
</tr>
<tr>
<td><code>36000291452</code></td>
<td>flagged, suggests <code>036000291452</code></td>
</tr>
<tr>
<td><code>4006381333931.0</code></td>
<td>ok, <code>4006381333931</code></td>
</tr>
<tr>
<td><code>4,006,381,333,931</code></td>
<td>rejected, number formatting</td>
</tr>
<tr>
<td><code>" 4006381333931\u00a0"</code></td>
<td>ok, <code>4006381333931</code></td>
</tr>
<tr>
<td><code>400638133393</code></td>
<td>flagged, check digit would be 1</td>
</tr>
<tr>
<td><code>4006381333932</code></td>
<td>rejected, wrong check digit</td>
</tr>
</tbody></table>
<h2>Better: read the <code>.xlsx</code> directly</h2>
<p>All of this checking is damage control. If you can, accept the <code>.xlsx</code> file itself instead of a CSV. With <a href="https://sheetjs.com/">SheetJS</a> and <code>cellText: true</code>, you can read the formatted text of each cell, which avoids many of these problems.</p>
<p>You can do the parsing in a Web Worker in the browser, so the file never has to be uploaded anywhere.</p>
<h2>Where this came from</h2>
<p>I ran into every one of these while building the bulk label tool on <a href="https://ownbarcode.com/bulk-barcode-generator">ownbarcode</a>, a free barcode and label generator that runs entirely in the browser. If you just need to check a few codes by hand, there's a <a href="https://ownbarcode.com/check-digit-calculator">check digit calculator</a> there too.</p>
<p>If you've seen a spreadsheet break barcodes in a way that isn't on this list, please share it in the comments. I'm collecting them.</p>
]]></content:encoded></item></channel></rss>