Barcode generation library written in JavaScript that works in both the browser and on Node.js

Overview

JsBarcode

Build Status Scrutinizer Code Quality CDN License

Introduction

JsBarcode is a barcode generator written in JavaScript. It supports multiple barcode formats and works in browsers and with Node.js. It has no dependencies when it is used for the web but works with jQuery if you are into that.

Demo

Barcode Generator

Simple CodePen Demo

Settings CodePen Demo

Supported barcodes:

Examples for browsers:

First create a canvas (or image)

<svg id="barcode"></svg>
<!-- or -->
<canvas id="barcode"></canvas>
<!-- or -->
<img id="barcode"/>

Simple example:

JsBarcode("#barcode", "Hi!");
// or with jQuery
$("#barcode").JsBarcode("Hi!");
Result:

Result

Example with options:

JsBarcode("#barcode", "1234", {
  format: "pharmacode",
  lineColor: "#0aa",
  width:4,
  height:40,
  displayValue: false
});
Result:

Result

More advanced use case:

JsBarcode("#barcode")
  .options({font: "OCR-B"}) // Will affect all barcodes
  .EAN13("1234567890128", {fontSize: 18, textMargin: 0})
  .blank(20) // Create space between the barcodes
  .EAN5("12345", {height: 85, textPosition: "top", fontSize: 16, marginTop: 15})
  .render();
Result:

Result

Or define the value and options in the HTML element:

Use any jsbarcode-* or data-* as attributes where * is any option.

<svg class="barcode"
  jsbarcode-format="upc"
  jsbarcode-value="123456789012"
  jsbarcode-textmargin="0"
  jsbarcode-fontoptions="bold">
</svg>

And then initialize it with:

JsBarcode(".barcode").init();
Result:

Result

Retrieve the barcode values so you can render it any way you'd like

Pass in an object which will be filled with data.

const data = {};
JsBarcode(data, 'text', {...options});

data will be filled with a encodings property which has all the needed values. See wiki for an example of what data looks like.

Setup for browsers:

Step 1:

Download or get the CDN link to the script:

Name Supported barcodes Size (gzip) CDN / Download
All All the barcodes! 10.1 kB JsBarcode.all.min.js
CODE128 CODE128 (auto and force mode) 6.2 kB JsBarcode.code128.min.js
CODE39 CODE39 5.1 kB JsBarcode.code39.min.js
EAN / UPC EAN-13, EAN-8, EAN-5, EAN-2, UPC (A) 6.6 kB JsBarcode.ean-upc.min.js
ITF ITF, ITF-14 5 kB JsBarcode.itf.min.js
MSI MSI, MSI10, MSI11, MSI1010, MSI1110 5 kB JsBarcode.msi.min.js
Pharmacode Pharmacode 4.7 kB JsBarcode.pharmacode.min.js
Codabar Codabar 4.9 kB JsBarcode.codabar.min.js

Step 2:

Include the script in your code:

<script src="JsBarcode.all.min.js"></script>

Step 3:

You are done! Go generate some barcodes 😄

Bower and npm:

You can also use Bower or npm to install and manage the library.

bower install jsbarcode --save
npm install jsbarcode --save

Node.js:

With canvas:

var JsBarcode = require('jsbarcode');

// Canvas v1
var Canvas = require("canvas");
// Canvas v2
var { createCanvas } = require("canvas");

// Canvas v1
var canvas = new Canvas();
// Canvas v2
var canvas = createCanvas();

JsBarcode(canvas, "Hello");

// Do what you want with the canvas
// See https://github.com/Automattic/node-canvas for more information

With svg:

const { DOMImplementation, XMLSerializer } = require('xmldom');
const xmlSerializer = new XMLSerializer();
const document = new DOMImplementation().createDocument('http://www.w3.org/1999/xhtml', 'html', null);
const svgNode = document.createElementNS('http://www.w3.org/2000/svg', 'svg');

JsBarcode(svgNode, 'test', {
    xmlDocument: document,
});

const svgText = xmlSerializer.serializeToString(svgNode);

Options:

For information about how to use the options, see the wiki page.

Option Default value Type
format "auto" (CODE128) String
width 2 Number
height 100 Number
displayValue true Boolean
text undefined String
fontOptions "" String
font "monospace" String
textAlign "center" String
textPosition "bottom" String
textMargin 2 Number
fontSize 20 Number
background "#ffffff" String (CSS color)
lineColor "#000000" String (CSS color)
margin 10 Number
marginTop undefined Number
marginBottom undefined Number
marginLeft undefined Number
marginRight undefined Number
valid function(valid){} Function

Contributions and feedback:

We ❤️ contributions and feedback.

If you want to contribute, please check out the CONTRIBUTING.md file.

If you have any question or suggestion create an issue or ask about it in the gitter chat.

Bug reports should always be done with a new issue.

License:

JsBarcode is shared under the MIT license. This means you can modify and use it however you want, even for comercial use. But please give this the Github repo a and write a small comment of how you are using JsBarcode in the gitter chat.

Comments
  • "Renderer is not a constructor"

    This is not a direct issue for us, but to help you improve your code, I thought I'd share something I found. We are getting the Exception "i is not a constructor". You can safely catch and ignore the exception, and everything seems to work fine, but it is still there.

    My code now is the following:

    try {
        JsBarcode(imgID, barValue, {format:barFormat, displayValue:showValue, fontSize:parseInt(barFont), width:parseInt(barWidth), height:parseInt(barHeight), ratio:0.8});
    } catch (err) {
        jslog("Error when using JsBarcode: " + err.message);
        //There is an error in JsBarcode we need to ignore (ie: i is not a constructor)
    }
    
    Bug Awaiting More Feedback 
    opened by Scheder 25
  • npm install fail

    npm install fail

    npm ERR! Darwin 15.5.0
    npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "i" "jsbarcode"
    npm ERR! node v6.2.0
    npm ERR! npm  v3.9.5
    npm ERR! path /Users/chenzhuokai/Documents/Projects/WXBook-Node-Print/node_modules/jsbarcode/bin/cli.js
    npm ERR! code ENOENT
    npm ERR! errno -2
    npm ERR! syscall chmod
    
    npm ERR! enoent ENOENT: no such file or directory, chmod '/Users/chenzhuokai/Documents/Projects/WXBook-Node-Print/node_modules/jsbarcode/bin/cli.js'
    npm ERR! enoent ENOENT: no such file or directory, chmod '/Users/chenzhuokai/Documents/Projects/WXBook-Node-Print/node_modules/jsbarcode/bin/cli.js'
    npm ERR! enoent This is most likely not a problem with npm itself
    npm ERR! enoent and is related to npm not being able to find a file.
    npm ERR! enoent 
    

    And also use github url in package.json did't work.

    Here is full error log. http://pastebin.com/tTRT6GK4

    Bug 
    opened by bruceCzK 14
  • Minification problem?

    Minification problem?

    I get the following error calling the minified JsBarcode script. It does not occur with the unminified version:

    JsBarcode.all.min.js:2 Uncaught SyntaxError: Invalid regular expression: /^[ -_È-Ï]*/: Range out of order in character class

    This is under Chrome version 58 (64-bit).

    Mark

    opened by markpotts123 13
  • Suggestion: support data-barcode on target object

    Suggestion: support data-barcode on target object

    I am using your great library in an web application where the barcode value(s) are being output from a db. As the values for that barcode are dynamic and there will be more than one barcode I can't construct the values in JS by using an ID.

    For the time being I use a jQuery snippet which reads the barcode information from the data property.

    As your script uses string.search it is necessary to first cast the result of the data-call value to string to avoid an exception.

    HTML <img class="barcode" data-barcode="4012700014825">

    JS

    $(document).ready(function () {
        $('.barcode').each(function () {
            var barcodeValue = "" + $( this ).data('barcode'),
                barcodeType = "ean" + barcodeValue.length;
    
            $( this ).JsBarcode(barcodeValue, {
                format: barcodeType , 
                height: 40, 
                displayValue:true, 
                fontSize:14, 
                textMargin: 2, 
                background: "transparent", 
                margin: 0
            });
        });            
    });
    

    It would be great to add support for this data property by default.

    Enhancement 
    opened by fschaeffer 13
  • EAN13 - wrong value encoded in bars

    EAN13 - wrong value encoded in bars

    Input: 12 position with leading zeros, e.g. 000000000001 Output text representation 12 positions plus control sum: 0000000000017 Value read from bars 11 positions plus control sum: 000000000017

    Encoded one position less than it supposed to be.

    opened by piotr-rusol 12
  • Uncaught TypeError: window[c.format] is not a function(…)

    Uncaught TypeError: window[c.format] is not a function(…)

    No idea what's going on. It just doesn't work ;)

    Uncaught TypeError: window[c.format] is not a function(…)

    $("body").append("<img id='barcode'>");
    [<body>​…​</body>​]
    $("#barcode").JsBarcode("Hi!");
    JsBarcode.all.min.js:19 Uncaught TypeError: window[c.format] is not a function(…)(anonymous function) @ JsBarcode.all.min.js:19JsBarcode @ JsBarcode.all.min.js:19f.fn.JsBarcode @ JsBarcode.all.min.js:21(anonymous function) @ VM1196:2InjectedScript._evaluateOn @ VM1159:875InjectedScript._evaluateAndWrap @ VM1159:808InjectedScript.evaluate @ VM1159:664
    JsBarcode("#barcode","JsBarcode is easy!",{width:1,height:25});
    JsBarcode.all.min.js:19 Uncaught TypeError: window[c.format] is not a function(…)(anonymous function) @ JsBarcode.all.min.js:19JsBarcode @ JsBarcode.all.min.js:19(anonymous function) @ VM1199:2InjectedScript._evaluateOn @ VM1159:875InjectedScript._evaluateAndWrap @ VM1159:808InjectedScript.evaluate @ VM1159:664
    
    opened by ljack 12
  • Encode FNC3 startcode

    Encode FNC3 startcode

    I'm wondering if there is a way to encode FNC3 for Code128 barcodes using this library?

    Specifically I am using react-native-barcode-builder (which uses this library internally) to generate barcodes on react native.

    opened by julienvincent 11
  • nodejs xmldom svg support

    nodejs xmldom svg support

    I'd like to create an svg Element in nodejs using xmldom and then generate an svg barcode just like you can when using jsBarcode in a browser context.

    const { DOMImplementation } = require('xmldom');
    const document = new DOMImplementation().createDocument('http://www.w3.org/1999/xhtml', 'html', null);
    
    const svgNode = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    
    jsBarcode(svgNode, 'test', {
      format: 'CODE128C',
      displayValue: false,
      width: 4,
      height: 100
    });
    

    I'd hope it should be able to re-use the same renderers.SVGRenderer from here, would need to figure out how to tell if it's passed an xmldom svg element

    opened by pseudo-su 11
  • Cannot scan after printing

    Cannot scan after printing

    Hey Lindell,

    First off, great library. I upgraded to the latest JsBarcode and am using svg to my big delight. I can create and scan (with my phone) perfectly on my computer screen, but when i print out the barcode, somehow the lines become thicker. When I check the html, it clearly shows that as many pixels are used for the white space as the black space, but after printing, there seems to be less whitespace... :(

    opened by Scheder 10
  • Barcodes are blurry when printed from Chrome and other browsers

    Barcodes are blurry when printed from Chrome and other browsers

    Even the example page at: http://lindell.me/JsBarcode/ is producing a blurry barcode when you go to print from Chrome.

    IE is a little more crisp, but not by much.

    opened by Jaded-Design 10
  • Support for GS1-128

    Support for GS1-128

    Does this library support rendering GS1-128 barcodes? It would be great if it does, cause I not been able to make work other generator's libraries, and really like this one.

    New Barcode 
    opened by davidgcalle 9
  • In ShadowDom : NoElementException: No element to render on.

    In ShadowDom : NoElementException: No element to render on.

    Hi Folks,

    Having trouble when I have my Angular element in the shadow dom. It can't seem to find the element. I am loading in the javascript to execute JsBarcode from a server and creating a script element on the shadowRoot. It is executing, but it can't find the element in question.

    Is there any way to work around this issue?

    set scriptContents(javascript: string) {
            this._scriptContents = javascript;
            const scriptElement = document.createElement('script');
            
    
            scriptElement.textContent = javascript;
            this.elementRef.nativeElement.shadowRoot.appendChild(scriptElement);
        }
    
    opened by AshMcConnell 0
  • ISBN13 Barcode

    ISBN13 Barcode

    It would be great to have a 'real' ISBN13 Barcode support (not the UPC).

    ISBN13 uses formatted ISBN Text above as well the Code below the Barcode: https://github.com/lindell/JsBarcode/issues/137#issuecomment-1266428922

    opened by no64 0
  • AN EXTREMELY CRITICAL ISSUE: donations!

    AN EXTREMELY CRITICAL ISSUE: donations!

    Hey @lindell, your work with this library is just amazing and I really like how small it's size is compared to other ones, but I see that the active development has been hanging slower recently. Would money donations help you or any other contributors to keep the development more active? I am just a bit weary that the library suddenly goes archived while I use it in my company. Thanks to everyone involved in that project, it is amazing.

    opened by phtdacosta 0
  • EAN5/EAN2 - advanced JsBarcode syntax - Background Color BUG

    EAN5/EAN2 - advanced JsBarcode syntax - Background Color BUG

    If using the 'advanced JsBarcode syntax' to add EAN5/EAN2 AddOns the background color option is not accepted. Background is always 'white'

    .. or is there a special option for the background in the advanced JsBarcode syntax?

    *edit - and 'margin' just affect 'top-margin' / 'bottom-margin'

    opened by no64 0
  • Docker instance crashes when creating a JsBarcode push to Canvas (Error code 139)

    Docker instance crashes when creating a JsBarcode push to Canvas (Error code 139)

    "jsbarcode": "^3.11.5",

    I am getting an error when trying to create a new bar code and save it. The below code works perfectly when running it outside of a docker container.

    You can check out the Docker Hub container mannequinbanshee/pointofsale:latest for reference to the setup:

    link to docker

       const CreateSingleBarcode = async (req,h) => {
    
        var BarcodeCanvas = createCanvas();
        var guid = uuid.v1().substring(0,8);
        try{
            **JsBarcode(BarcodeCanvas,guid);**   ## code crashes here with exited with code 139
            var CreatedBarcode = await Barcode.create({"name": guid});
            var canvasData = BarcodeCanvas.toBuffer("image/png");
            var ServerSidePath = Path.join(__dirname,"../../../../static/public/assets/images/Barcodes");
            if(fs.existsSync(ServerSidePath)){
              var success = await fs.writeFile(`${ServerSidePath}/${guid}.png`,canvasData,(error) => {
                if(error){
                    winston.error(error.message);
                }
              });
            }
        }
        catch(e){
            winston.error(e.message);
        }
    
    
        return guid;
        }
    

    The Below image shows the new button which is linked to the above.

    image

    opened by MannequinBanshee 0
Releases(v3.11.5)
a super simple, no-nonsense diagramming library written in react that just works

Introduction DEMO: http://projectstorm.cloud/react-diagrams DOCS (wip) https://projectstorm.gitbook.io/react-diagrams Docs are currently being worked

Storm 7.4k Jan 4, 2023
Perfect pressure-sensitive drawing for both iOS and Android.

rn-perfect-sketch-canvas A React Native component for drawing perfect pressure-sensitive freehand lines using perfect-freehand and Skia renderer. Inst

Robert Soriano 75 Jan 3, 2023
Automatic color generation for Chart.js

chartjs-plugin-autocolors Automatic color generation for Chart.js The generation is based on Janus Troelsen's answer at Stack Overflow. This plugin re

Jukka Kurkela 28 Dec 17, 2022
A reusable charting library written in d3.js

NVD3 - A reusable D3 charting library Inspired by the work of Mike Bostock's Towards Reusable Charts, and supported by a combined effort of Novus and

Novus 7.2k Jan 3, 2023
JS.Sketcher is a parametric 2D and 3D CAD modeler written in pure javascript

JS.Sketcher JS.Sketcher is a parametric 2D and 3D CAD modeler written in pure javascript YouTube Tutorial Video Live Sample Demo 2D Sketcher Help Docs

Val Erastov 1.1k Jan 3, 2023
TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies

TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies; use it with any framework or backend.

null 24 Dec 12, 2022
A plugin for the jQuery javascript library to generate small sparkline charts directly in the browser

jQuery Sparklines This jQuery plugin makes it easy to generate a number of different types of sparklines directly in the browser, using online a line

Gareth Watts 1.2k Jan 4, 2023
Reusable JavaScript library for creating sketchy/hand-drawn styled charts in the browser.

roughViz.js is a reusable JavaScript library for creating sketchy/hand-drawn styled charts in the browser, based on D3v5, roughjs, and handy. Why? Use

Jared Wilber 6.4k Jan 4, 2023
RocketTrades - Discord Stocks and Charts bot. Written for the RocketTrades Discord bot.

Rocket Trades RocketTrades, Discord Charts and Stocks bot. MORE DETAILS AND UPDATES TO COME SOON Getting started • Installation • Configuration • Inte

Ethan Primmer 3 Feb 4, 2022
Apache ECharts is a powerful, interactive charting and data visualization library for browser

Apache ECharts Apache ECharts is a free, powerful charting and visualization library offering an easy way of adding intuitive, interactive, and highly

The Apache Software Foundation 53.8k Jan 9, 2023
Apache ECharts is a powerful, interactive charting and data visualization library for browser

Apache ECharts Apache ECharts is a free, powerful charting and visualization library offering an easy way of adding intuitive, interactive, and highly

The Apache Software Foundation 53.8k Jan 5, 2023
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey

Paper.js - The Swiss Army Knife of Vector Graphics Scripting If you want to work with Paper.js, simply download the latest "stable" version from http:

Paper.js 13.5k Dec 30, 2022
Java library for use with Chart.js javascript library

Chart.java Chart.java enables integration with the excellent Chart.js library from within a Java application. Usage example In Java: BarDataset datase

Marceau Dewilde 102 Dec 16, 2022
Plug is a browser extension for users of the Internet Computer that allows you to access your ICP, Cycles, and other tokens as well as log into IC apps with one click.

Plug Introduction Welcome to Plug! An Internet Computer crypto wallet and authentication provider as a browser extension. Find our latest version in t

Psychedelic 150 Dec 23, 2022
Renders HTML into the browser's canvas

rasterizeHTML.js Renders HTML into the browser's canvas. See the API. Install $ npm install rasterizehtml Then include a script tag with node_modules

Christoph Burgmer 2.3k Dec 30, 2022
danfo.js is an open source, JavaScript library providing high performance, intuitive, and easy to use data structures for manipulating and processing structured data.

Danfojs: powerful javascript data analysis toolkit What is it? Danfo.js is a javascript package that provides fast, flexible, and expressive data stru

JSdata 4k Dec 29, 2022
TChart.js - simple and configurable Bar and Line Chart library in Javascript

TChart.js Simple and configurable Bar and Line Chart library in Javascript Description TChart.js is a canvas-based simple Javascript Bar and Line Char

null 4 Mar 3, 2021
A javascript library that extends D3.js to enable fast and beautiful visualizations.

d3plus D3plus is a JavaScript re-usable chart library that extends the popular D3.js to enable the easy creation of beautiful visualizations. Installi

D3plus 1.6k Dec 2, 2022
Ember Charts 3.5 2.3 L2 JavaScript A powerful and easy to use charting library for Ember.js

Ember Charts A charting library built with the Ember.js and d3.js frameworks. It includes time series, bar, pie, and scatter charts which are easy to

Addepar 793 Dec 7, 2022