Skip to content

benjamn/bwip-js

 
 

// Barcode Writer in Pure JavaScript

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.

Status

  • Current bwip-js version is 0.15.1 (24-Nov-2015)
  • Current BWIPP version is 2015-11-24
  • Node.js compatibility >= v0.10 (reported to work with v0.8 but not tested).
  • npm dependencies: none

Links

Online Barcode Generator

An online barcode generator demonstrates all of the features of bwip-js. It showcases the new font rendering provided by the FreeType library, and allows using your own fonts. All fonts are stored locally on your computer; the generator is 100% client-side JavaScript.

The demo is tested on the latest versions of Firefox and Chrome, along with IE10. IE11 should work, and so should the latest versions of Opera and Safari, but they are untested.

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 Generator API.

Node.js Request Handler

The online barcode service is implemented as a Node.js application. The code used for the service is available as part of the bwip-js source code. See the Barcode API for details on how the URL query parameters must be structured.

The following is a minimal example of how to use the request handler:

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

// Example of how to load a font into bwipjs. 
//	bwipjs.loadFont(fontname, sizemult, fontdata)
//
// To unload a font (and free up space for another):
//	bwipjs.unloadFont(fontname)
//
bwipjs.loadFont('Inconsolata', 108,
            require('fs').readFileSync('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('BWIP-JS: 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 also use bwip-js to generate PNG images directly.

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

// Optionally load some custom fonts.  Maximum 8.
// OpenType and TrueType are supported.
bwipjs.loadFont('Inconsolata', 108,
            require('fs').readFileSync('Inconsolata.otf', 'binary'));

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
		textfont:		'Inconsolata',	// Use your custom font
		textsize:		13				// Font size, in points
	}, 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:

  • scaleX : The x-axis scaling factor. Must be an integer > 0. Default is 2.

  • scaleY : The y-axis scaling factor. Must be an integer > 0. Default is scaleX.

  • scale : Sets both the x-axis and y-axis scaling factors. Must be an integer > 0.

  • rotate : Allows rotating the image to one of the four orthogonal orientations. A string value. Must be one of:

    • "N" : Normal (not rotated). The default.
    • "R" : Clockwise (right) 90 degree rotation.
    • "L" : Counter-clockwise (left) 90 degree rotation.
    • "I" : Inverted 180 degree rotation.
  • monochrome : Sets the human-readable text to render in monochrome. Boolean true or false. Default is false which renders 256-level gray-scale anti-aliased text.

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

Features

An Emscripten compiled version of the FreeType library is integrated into bwip-js.

Embedded in the FreeType library are open-source versions of the OCR-A and OCR-B fonts provided by the Tsukurimashou Font Family project.

A description of how FreeType was compiled for use with bwip-js can be found at: Compiling FreeType with Emscripten.

OCR Fonts

The barcode images generated by bwip-js are essentially identical to using BWIPP with Ghostscript. The most significant difference is the use of the OCR-A and OCR-B fonts. Barcodes and the OCR fonts are like chocolate and hazelnut; they were meant to go together. Unfortunately, most PostScript environments do not provide the OCR fonts and must fallback to Courier, Helvetica, and other less-than-ideal typefaces.

The following two images show the differences in typeface. The image below was rendered by bwip-js:

bwip-js ISBN

And the next image was rendered using BWIPP with Ghostscript:

BWIPP/Ghostscript ISBN

The new font functionality is implemented with the following logic:

  • OCR-B is used as the default font for all barcodes.
  • OCR-A is used for the extra text on the ISBN, ISMN and ISSN symbols.

These defaults can be overridden using BWIPP options. The fonts are known to the PostScript emulation as OCR-A and OCR-B. For example, to switch the font to OCR-A, you would specify the option:

textfont=OCR-A

For the text above the barcode on the ISBN, ISMN, and ISSN symbols, the font can be changed using isbntextfont, ismntextfont, and issntextfont, respectively.

The code in demo.html shows how to load your own fonts into bwip-js. See Preloading Fonts Into FreeType and Loading Fonts During Runtime for descriptions of the two techniques.

The online barcode generator pre-loads the Inconsolata font, which can be seen using the option:

textfont=Inconsolata

For example, we can render an alternate version of the ISBN barcodes shown above with the Inconsolata font using the BWIPP options:

includetext guardwhitespace textfont=Inconsolata isbntextfont=Inconsolata isbntextsize=11

ISBN Using Inconsolata

Background Color

A second difference between BWIPP and bwip-js rendering occurs with the backgroundcolor option. The BWIPP implementation of background color is a bit inconsistent. For some bar code types, the background color extends into the human readable text, and for others, it does not. The bwip-js PostScript emulation implements BWIPP's background color handling but the front-end interfaces in the demo and in the node module explicitly override the option. They extend the background color to cover the entire image, including all human readable text.

The first/left image in each pair is from BWIPP using ghostscript, the second from bwip-js.

BWIPP EAN-13 bwip-js EAN-13

BWIPP Code128 bwip-js Code128

BWIPP ISBN bwip-js ISBN

If you want to use BWIPP's original background color handling, look for the following lines in node-bwipjs (or lib/canvas.js if using the browser code):

// Feature or bug, BWIPP does not extend the background color into
// the human readable text.  Fix that in the bitmap interface.
if (opts.backgroundcolor) {
	bw.bitmap(new Bitmap(parseInt(''+opts.backgroundcolor, 16)));
	delete opts.backgroundcolor;
} else {
	bw.bitmap(new Bitmap);
}

Comment out or remove the if part of the logic, leaving only bw.bitmap(new Bitmap);.

By default, if the backgroundcolor option is not specified, bwip-js renders the image with a transparent background.

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 software is organized in the following directory structure:

bwip-js/
	bwip.js			# Main bwip-js code.
	demo.html		# The bwip-js demo
	freetype.js		# The Emscripten-compiled FreeType library
	freetype.js.mem	# Demand loaded memory image
	node-bwipjs		# Node.js module
	node-zlibPNG	# Node.js module that implements a PNG encoder
	package.json	# Node.js/npm configuration
	bwipp/			# The cross-compiled BWIPP encoders and renderers
	lib/			# Utilities required by the demo

Usage

Version 0.8 was an API-breaking release. If you have implemented code based on previous versions, you must update your code in three areas. This wiki page describes the changes.

Using the demo with a file:// URL is no longer supported.

Emscripten optimizes the FreeType library by separating the memory intialization image and using XHR (when running in a browser) to demand load it. Because of this, you can no longer reliably use the demo via the file:// scheme in a browser's URL bar. Firefox supports XHR with file://, Chrome and IE do not.

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

If you would like to implement your own interface to bwip-js, see Integrating bwip.js Into Your Code. I would also recommend looking at the node-bwipjs module to see how it was done for Node.js. Getting the FreeType module to cooperate with the BWIPP cross-compiled code was not straightforward.

Supported Barcode Types

• AusPost 4 State Customer Code • Aztec Code • Aztec Runes • BC412 • Channel Code • Codabar • Codablock F • Code 11 • Code 128 • Code 16K • Code 25 • Code 39 • Code 39 Extended • Code 49 • Code 93 • Code 93 Extended • Code One • Compact Aztec Code • Compact PDF417 • COOP 2 of 5 • Custom 1D symbology • Custom 4 state symbology • Data Matrix • Datalogic 2 of 5 • Deutsche Post Identcode • Deutsche Post Leitcode • EAN-13 • EAN-13 Composite • EAN-2 (2 digit addon) • EAN-5 (5 digit addon) • EAN-8 • EAN-8 Composite • Flattermarken • GS1 Composite 2D Component • GS1 Data Matrix • GS1 DataBar Expanded • GS1 DataBar Expanded Composite • GS1 DataBar Expanded Stacked • GS1 DataBar Expanded Stacked Composite • GS1 DataBar Limited • GS1 DataBar Limited Composite • GS1 DataBar Omnidirectional • GS1 DataBar Omnidirectional Composite • GS1 DataBar Stacked • GS1 DataBar Stacked Composite • GS1 DataBar Stacked Omnidirectional • GS1 DataBar Stacked Omnidirectional Composite • GS1 DataBar Truncated • GS1 DataBar Truncated Composite • GS1 QR Code • GS1-128 • GS1-128 Composite • GS1-14 • HIBC Codablock F • HIBC Code 128 • HIBC Code 39 • HIBC Data Matrix • HIBC MicroPDF417 • HIBC PDF417 • HIBC QR Code • IATA 2 of 5 • Industrial 2 of 5 • Interleaved 2 of 5 (ITF) • ISBN • ISMN • ISSN • Italian Pharmacode • ITF-14 • Japan Post 4 State Customer Code • Matrix 2 of 5 • MaxiCode • Micro QR Code • MicroPDF417 • Miscellaneous symbols • MSI Modified Plessey • PDF417 • Pharmaceutical Binary Code • Pharmazentralnummer (PZN) • Plessey UK • PosiCode • QR Code • Royal Dutch TPG Post KIX • Royal Mail 4 State Customer Code • SSCC-18 • Telepen • Telepen Numeric • Two-track Pharmacode • UPC-A • UPC-A Composite • UPC-E • UPC-E Composite • USPS Intelligent Mail • USPS PLANET • USPS POSTNET •

Packages

No packages published

Languages

  • JavaScript 83.9%
  • PostScript 15.8%
  • Other 0.3%