View on GitHub

bwip-js // Barcode Writer in Pure JavaScript

Download this project as a .zip file Download this project as a tar.gz file

bwip-js bwip-js is a translation to native JavaScript of the amazing code provided in Barcode Writer in Pure PostScript. The translated code can run on any modern browser or JavaScript-based server framework.

The software has encoding modules for over 90 different barcode types and standards. All linear and two-dimensional barcodes in common use (and many uncommon ones) are available. An exhaustive list of supported barcode types can be found at the end of this document.

Version 1.5 has a replacement for the emscripten-compiled FreeType library (which was causing issues with popular frameworks and pre-allocated too much memory for use in embedded servers). It is still possible to use FreeType with Node.js, but you must explicitly enable it. By default, you get the replacement. Browsers only use the replacement.

The new font library uses bitmapped fonts that were generated by freetype.js at the integral scale factors of 1x - 9x. There should be no change in how the fonts display when the default font sizes are used. If you use custom sizes OR use non-uniform scaling, there may be noticeable differences.

See FreeType Replacement for more details.

RedHat OpenShift API Discontinued

I was informed during the last week of September that RedHat is discontinuing the free service that is used to host the bwip-js public API. The existing solution provided up to three VPS with 24/7 availability. In place of this, they are offering a single VPS "starter" platform that, according to https://www.openshift.com/pricing/index.html, must sleep 18 hours in any 72 hour period. That is hardly comparable and does not serve a global user base.

Because of this, the existing API will likely shutdown on October 1. Sorry for the short notice. This caught me up short as well.

The API has been moved to a new Amazon AWS platform, reachable as:

http://bwipjs-api.metafloor.com/

That more generic URL should help isolate applications in the future if/when the host platform changes.

Same usage as before.

Status

Supported Platforms

Links

Installation

You can download the latest npm module using:

npm install bwip-js

Or the latest code from github:

https://github.com/metafloor/bwip-js

(The bwip-js master branch and the npm version are kept sync'd.)

Online Barcode Generator

An online barcode generator demonstrates all of the features of bwip-js. As of version 1.5, the FreeType library is no longer supported in the demo. Only the OCR-A and OCR-B fonts are available.

Online Barcode API

A bwip-js barcode service is available online, ready to serve up barcode images on demand.

You can generate barcodes from anywhere on the web. Embed the URLs in your HTML documents or retrieve the barcode images directly from your non-JavaScript server. (JavaScript-based servers should use the bwip-js code directly - it will be a lot more performant.)

For details on how to use this service, see Online Barcode API.

Browser Usage

The following is a minimal example of using bwip-js in a React app. It is based on the default App.js file generated by create-react-app.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import bwipjs from 'bwip-js';

class App extends Component {
  constructor(props) {
    super(props);

    bwipjs('mycanvas', {
            bcid:        'code128',       // Barcode type
            text:        '0123456789',    // Text to encode
            scale:       3,               // 3x scaling factor
            height:      10,              // Bar height, in millimeters
            includetext: true,            // Show human-readable text
            textxalign:  'center',        // Always good to set this
        }, function (err, cvs) {
            if (err) {
                // Decide how to handle the error
                // `err` may be a string or Error object
            } else {
                // Nothing else to do in this example...
            }
        });
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <canvas id="mycanvas"></canvas>
      </div>
    );
  }
}
export default App;

The bwipjs() method takes three parameters:

If you would prefer to display the barcode using an <img> tag or with CSS background-image, pass in a detached or hidden canvas to bwip-js, and use the canvas method HTMLCanvasElement.toDataURL to get a data URL. For example:

let canvas = document.createElement('canvas');
bwipjs(canvas, options, function(err, cvs) {
    if (err) {
        // handle the error
    } else {
        // Don't need the second param since we have the canvas in scope...    
        document.getElementById(myimg).src = canvas.toDataURL('image/png');
    }
});

If you want to generate barcodes with text, you must do one extra step after installing bwip-js. The browser-based font manager uses XHR to demand-load fonts as needed. The problem is that the fonts directory where bwip-js gets installed (under node_modules) is usually not accessible. Therefore, you must make the fonts visible to your applcation.

For React apps, you must copy (or link) the fonts to the public/ directory. If you are using linux or unix-like:

cd my-app
ln -s node_modules/bwip-js/fonts public/bwipjs-fonts

Where my-app is the root of your application directory (typically created by create-react-app. Under that directory, should be the public/ and node_modules/ directories.

If you are running windows, copy the files:

cd my-app
mkdir public\bwipjs-fonts
copy node_modules\bwip-js\fonts\* public\bwipjs-fonts

For other frameworks, you may need to take additional steps. The font manager assumes there is a global variable called process.env.PUBLIC_URL, which is set automatically by React. If not set by your framework, assign it manually (adapt as necessary):

window.process = { env: { PUBLIC_URL: path } };

Where path is the URL-path to the directory containing bwipjs-fonts. The font manager appends /bwipjs-fonts/file-name to the value when it requests a file.

Node.js Request Handler

The online barcode API is implemented as a Node.js application. See the Online Barcode API for details on how the URL query parameters must be structured.

A working, minimal example of how to use the request handler can be found in server.js:

// Simple HTTP server that renders barcode images using bwip-js.
const http   = require('http');
const bwipjs = require('bwip-js');

// To use the freetype library for font rendering, you must enable it via useFreetype(),
// then load your custom font(s).  This shows how to load the Inconsolata font, supplied
// with the bwip-js distribution.  The path to your fonts will likely be different.
//bwipjs.useFreetype();
//bwipjs.loadFont('Inconsolata', 108,
//      require('fs').readFileSync(__dirname + '/fonts/Inconsolata.otf', 'binary'));

http.createServer(function(req, res) {
    // If the url does not begin /?bcid= then 404.  Otherwise, we end up
    // returning 400 on requests like favicon.ico.
    if (req.url.indexOf('/?bcid=') != 0) {
        res.writeHead(404, { 'Content-Type':'text/plain' });
        res.end('BWIPJS: Unknown request format.', 'utf8');
    } else {
        bwipjs(req, res);
    }

}).listen(3030);

If you run the above code on your local machine, you can test with the following URL:

http://localhost:3030/?bcid=isbn&text=978-1-56581-231-4+52250&includetext&guardwhitespace

The bwip-js request handler only operates on the URL query parameters and ignores all path information. Your application is free to structure the URL path as needed to implement the desired HTTP request routing.

Node.js Image Generator

You can use bwip-js to generate PNG images directly.

const bwipjs = require('bwip-js');

bwipjs.toBuffer({
        bcid:        'code128',       // Barcode type
        text:        '0123456789',    // Text to encode
        scale:       3,               // 3x scaling factor
        height:      10,              // Bar height, in millimeters
        includetext: true,            // Show human-readable text
        textxalign:  'center',        // Always good to set this
    }, function (err, png) {
        if (err) {
            // Decide how to handle the error
            // `err` may be a string or Error object
        } else {
            // `png` is a Buffer
            // png.length           : PNG file length
            // png.readUInt32BE(16) : PNG image width
            // png.readUInt32BE(20) : PNG image height
        }
    });

Only the first two options bcid and text are required. The other bwip-js specific options are:

All other options are BWIPP specific. You will need to consult the BWIPP documentation to determine what options are available for each barcode type.

Note that bwip-js normalizes the BWIPP width and height options to always be in millimeters. The resulting images are rendered at 72 dpi. To convert to pixels, use a factor of 2.835 px/mm (72 dpi / 25.4 mm/in). The bwip-js option scale multiplies both the width and height options. Likewise, the discrete scaling factors scaleX and scaleY multiply the width and height options, respectively.

Electron Example

With Electron, use the Node.js toBuffer() interface. This is an example index.html file for a basic, single window app:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    Node.js <script>document.write(process.versions.node)</script>,
    Chromium <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.
    <br><br><img id="myimg">
    <pre id="output"></pre>
  </body>

  <script>
    var bwipjs = require('bwip-js');
    bwipjs.toBuffer({ bcid:'qrcode', text:'0123456789' }, function (err, png) {
		if (err) {
		  document.getElementById('output').textContent = err;
		} else {
		  document.getElementById('myimg').src = 'data:image/png;base64,' +
                                                 png.toString('base64');
		}
	  });
  </script>
</html>

Command Line Interface

bwip-js can be used as a command line tool.

npm install -g bwip-js
bwip-js --help

Usage example:

bwip-js --bcid=qrcode --text=123456789 ~/qrcode.png

bwip-js Directory Structure

The software is organized as follows:

bwip-js/
    barcode.ps          # The BWIPP PostScript barcode library
    browser-bitmap.js   # Bitmap interface used by browsers.
    browser-bwipjs.js   # The primary browser import.
    browser-fonts.js    # Browser-based font manager 
    bwipjs.js           # Main bwip-js code, cross-platform
    bwipp.js            # The cross-compiled BWIPP code
    demo.html           # The bwip-js demo
    freetype.js         # The Emscripten-compiled FreeType library
    node-bwipjs.js      # Primary node.js module
    node-bitmap.js      # Node.js module that implements a PNG encoder
    node-fonts.js       # Replacement for freetype.js
    server.js           # Node.js example server
    fonts/              # Font files
    lib/                # Files required by the demo

The above files are part of the master branch. If you wish to compile bwip-js on your own, you will need to clone the develop branch, which contains the cross-compiler, test framework, code-coverage files, benchmark framework, image proofs, etc. Everything used to create and validate bwip-js.

For details on how to compile and test bwip-js, see Compiling bwip-js.

Demo Usage

To run the demo from your HTTP server, you should link the bwip-js directory to the server's public document directory and modify the server's configuration files, if necessary. Then navigate your browser to bwip-js/demo.html.

You cannot run the demo using a file:// URL. The freetype library and the freetype replacement library use XHR, which must run over HTTP.

If you would like to implement your own interface to bwip-js, see Integrating With Your Code. You should also look at the node-bwipjs.js module to see how it was done for Node.js.