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.7 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 vueJS template with node-sass and prettier for make start a new project

A vueJS template with node-sass and prettier for make start a new project

NutDevs.org 0 Jan 2, 2022
Yeoman generator for a Vue, Express, Node, and Mongo stack

A somewhat opinionated Yeoman generator for applications built upon the VENM stack.

Joel Felsinger 47 Dec 15, 2022
A Programming Environment for TypeScript & Node.js built on top of VS Code

Programming Environment for TypeScript & Node.js A battery-included TypeScript framework built on top of Visual Studio Code Website Kretes is a progra

Kretes 677 Dec 11, 2022
Light speed setup for MEVN(Mongo Express Vue Node) Apps

Light speed setup for MEVN stack based web-apps Chat: Telegram Donate: PayPal, Open Collective, Patreon A CLI tool for getting started with the MEVN s

madlabsinc 791 Dec 14, 2022
Aplicação desenvolvida durante o NLW eSports, utilizando Vue, TailwindCSS, Node

nlw-esports NLW eSports Projeto | Tecnologias | Layout | Licença ?? Projeto Nesse desafio, foi desenvolvido uma de jogos ?? Imagens Página inicial Anú

Everton 2 Oct 15, 2022
Etherc - Browser-based ETH vanity address generator with vue.js

Vanity-ETH Browser-based ETH vanity address generator Just type vanity-eth.tk to

null 0 Jan 5, 2022
Vue3+Vite+elementPlus+mockJs+pinia+Scss (javaScript)

Vue3+Vite+elementPlus+mockJs+pinia+Scss (javaScript)

James 2 Feb 21, 2022
🛠 A simple template for building and publishing Vue component/library as a opensource.

vue-lib-template ?? A simple template for building and publishing Vue component/library as a opensource, Base on webpack-simple & bili ?? Feature Ligh

Pongsatorn 17 Apr 5, 2022
A VueJS 3 starter to create Vue applications easily and quickly with Vue Router, Snowpack, TypeScript and SCSS

VueJS 3 Starter ✨ A VueJS 3 starter to create Vue applications easily and quickly with Vue Router, Snowpack, TypeScript and SCSS Architecture ├─ publi

null 1 Jun 1, 2022
Generate the files and directory structure for a new Sails app using webpack and vue.js

sails generate new Generate the files and directory structure for a new Sails app using webpack and vue.js. installation npm install sails-generate-ne

null 5 Feb 21, 2021
Gluing Python web frameworks and Vue.js with a set of scripts... basically a wrapper :smile:

Python and Vue.js gule UPDATE At the moment project is not supported anymore, due to the rapid evolving of the JavaScript ecosystem. It was born like

Christian Strappazzon 40 Dec 24, 2022
A Vue.js starter kit that lets you focus on more programming and less configuration.

vue-starter A Vue.js starter kit that lets you focus on more programming and less configuration. A full-featured Webpack setup with hot-reload, lint-o

Rohit Rai 54 Sep 26, 2022
A WordPress theme with the guts ripped out and replaced with Vue.

VueWordPress Theme Starter Features Getting started Video Training Code Organization New to Vue? External References Features coming soon: Changelog V

Evan Agee 1.6k Dec 21, 2022
The most complete boilerplate for production-ready PWAs. With focus on performance, development speed, and best practices

vuesion The most complete boilerplate for production-ready PWAs. With focus on performance, development speed, and best practices 一个灵活的、可扩展的、自定的,已经准备好

vuesion 2.6k Dec 31, 2022
A seed project with vue, vuex, typescript & webpack with hot reloading and all the good stuf

Vue Vuex TypeScript Webpack seed This seed project includes some of the 'hot' and latests web technologies such as TypeScript, Vue, Vuex,Vuex-Typescri

Israel Zablianov 35 Jan 17, 2022
Bleeding edge vue template focused on code quality and developer happiness.

wemake-vue-template Bleeding edge vue template focused on code quality and developer happiness. This project is used to scaffold new Vue project struc

wemake.services 721 Dec 27, 2022
An ever-evolving, very opinionated architecture and dev environment for new Vue SPA projects using Vue CLI.

Vue Enterprise Boilerplate This is an ever-evolving, very opinionated architecture and dev environment for new Vue SPA projects using Vue CLI. Questio

Ben Hong 7.6k Jan 8, 2023
A CLI generator for Vue components, views and store modules

vue-generator A CLI generator for Vue components, views and store modules Supports Vue 2.x Install $ npm install -g vue-generator Usage The most basic

Hendrik-Jan de Harder 124 Sep 29, 2022
Vue project template for authoring component and their use case

vue-authoring-template Click one of this badge for more info This template is to help authoring Vue component with it's use case in story-scenario (st

Fahmi Akbar Wildana 14 Nov 15, 2021