-
Notifications
You must be signed in to change notification settings - Fork 309
README 2.0
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 2.0 introduces a new font rendering module based on the code at stb_truetype.h. This port was manually converted from the original C source and is both small and fast. It implements scalable, anti-aliased fonts and has been tuned to produce nearly identical character metrics as FreeType. The new library is usable in both Node.js and modern browsers.
The emscripten compiled freetype.js and the bitmapped fonts used in prior versions have been removed from this project. Likewise, the extra steps needed to get the bitmapped fonts to work in the browser have been eliminated.
To upgrade your code to the 2.0 release, you must make some minor changes. See Upgrading to 2.0.
- Current bwip-js version is BWIPJS_VERS
- Current BWIPP version is BWIPP_VERS
- Node.js compatibility: 0.12+
- Browser compatibility: Edge, Firefox, Chrome
Emulating PostScript is non-trivial but most of the needed functionality is available in relatively modern JavaScript. The basic features required are:
- Uint8Array
- Map (for-of iteration not used so older JS works)
If your JavaScript environment does not support those, there is no way to make this code work.
- Home Page
- Repository
bwipjs
Methods Reference- Online Barcode Generator
- Online Barcode API
- npm Page
- BWIPP Documentation
- Differences From BWIPP
- Supported Barcode Types
- Using Your Own Fonts
- Annotated Example Drawing Object
- Working with BWIPP Rendering Data
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.)
An online barcode generator demonstrates all of the features of bwip-js. The app is also available in the root bwip-js directory. See Demo Apps.
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.
Most of the public methods of the bwip-js export use an options object. Only two values are required:
-
bcid
: The name of the barcode type/symbol. -
text
: The text to encode.
All remaining options are optional, though you may find some quite useful.
The options values can be divided into two parts, bwip-js specific options and BWIPP options.
The bwip-js 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 isscaleX
. -
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.
-
-
padding
: Shorthand for settingpaddingtop
,paddingleft
,paddingright
, andpaddingbottom
. -
paddingwidth
: Shorthand for settingpaddingleft
andpaddingright
. -
paddingheight
: Shorthand for settingpaddingtop
andpaddingbottom
. -
paddingtop
: Sets the height of the padding area, in points, on the top of the barcode image. Rotates and scales with the image. -
paddingleft
: Sets the width of the padding area, in points, on the left side of the barcode image. Rotates and scales with the image. -
paddingright
: Sets the width of the padding area, in points, on the right side of the barcode image. Rotates and scales with the image. -
paddingbottom
: Sets the height of the padding area, in points, on the bottom of the barcode image. Rotates and scales with the image. -
backgroundcolor
: This is actually a BWIPP option but is better handled by the bwip-js drawing code. Takes either a hex RRGGBB or hex CCMMYYKK string value.
For the BWIPP specific options, 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 scale options multiply the width
, height
, and padding
.
To use within a browser, add the following to the head of your page:
<script type="text/javascript" src="file-or-url-path-to/bwip-js/dist/bwip-js-min.js"></script>
When developing your code, you may want to use dist/bwip-js.js
to get better stack
traces.
If you are using RequireJS
or another module/packaging utility, the bwip-js script is
structured as a UMD and should work with your environment.
The script adds a single bwipjs
global object. To draw a barcode to a canvas:
try {
bwipjs.toCanvas('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
});
} catch (e) {
// `e` may be a string or Error object
}
The bwipjs.toCanvas()
method takes two parameters:
- The canvas on which to render the barcode. This can by an
id
string or the actual canvas element. The rendering will automatically resize the canvas to match the barcode image. - A bwip-js/BWIPP options object.
On return from toCanvas()
, the barcode image will have been fully rendered to the canvas.
If you would prefer to display the barcode using an <img>
tag or with CSS background-image
,
pass in a detached or hidden canvas, and use the canvas method
HTMLCanvasElement.toDataURL
to get a data URL. For example:
let canvas = document.createElement('canvas');
try {
bwipjs.toCanvas(canvas, options);
document.getElementById(myimg).src = canvas.toDataURL('image/png');
} catch (e) {
// `e` may be a string or Error object
}
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 {
componentDidMount() {
try {
bwipjs.toCanvas('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
});
} catch (e) {
// `e` may be a string or Error object
}
}
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;
See the Browser Usage section for details on the toCanvas()
method.
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');
// This shows how to load the Inconsolata font, supplied with the bwip-js distribution.
// The path to your fonts will be different.
//bwipjs.loadFont('Inconsolata', 100,
// require('fs').readFileSync('./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.request(req, res); // Executes asynchronously
}
}).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.
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) {
// `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
}
});
If you would prefer to work with Promises, omit the callback function and
toBuffer()
will return a Promise:
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
})
.then(png => {
// `png` is a Buffer as in the example above
})
.catch(err => {
// `err` may be a string or Error object
});
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>
bwip-js can be used as a command line tool.
$ npm install -g bwip-js
$ bwip-js
Usage: bwip-js symbol-name text [options...] png-file
bwip-js --bcid=symbol-name --text=text [options...] png-file
Try 'bwip-js --help' for more information.
Try 'bwip-js --symbols' for a list of supported barcode symbols.
Usage example:
$ bwip-js qrcode 123456789 ~/qrcode.png
There are two demonstration html apps located in the root bwip-js directory:
-
demo.html
is a full featured demonstation of bwip-js barcode rendering. It uses bwip-js' built-in graphics to draw to a canvas. The images produced will match pixel-for-pixel with the images produced by node.js. -
examples/svg.html
is an example of how to use bwip-js with your own drawing methods. It converts the drawing commands to the equivalent SVG. When the drawing is complete, the SVG is both rendered on the screen and displayed as text.
Both demos can be run directly from a modern browser using the file://
scheme.