### Emscripten SDK Setup and Activation Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-FreeType Downloads, installs, and activates the Emscripten SDK. Ensure to run `emsdk_env.sh` to set up the environment variables. ```bash $ cd ~/emsdk $ ./emsdk update $ ./emsdk install latest $ # Get a cup of coffee or two.... $ ./emsdk activate latest $ . emsdk_env.sh ``` -------------------------------- ### Command Line Interface Usage Source: https://github.com/metafloor/bwip-js/blob/master/README.md Basic usage and example for the bwip-js command-line tool. Install globally using 'npm install -g bwip-js'. The file-name must be of type .png or .svg. ```bash $ npm install -g bwip-js $ bwip-js Usage: bwip-js symbol-name text [options...] file-name bwip-js --bcid=symbol-name --text=text [options...] file-name Example: bwip-js code128 012345678 includetext textcolor=ff0000 my-code128.png file-name must be type: .png or .svg Try 'bwip-js --help' for more information. Try 'bwip-js --symbols' for a list of supported barcode symbols. ``` -------------------------------- ### Basic bwip-js Usage Source: https://github.com/metafloor/bwip-js/blob/master/examples/example.html Illustrates the basic setup for bwip-js, including placeholders for barcode type, text, options, and scale. This is a conceptual example. ```html bwip-js // Barcode Writer in Pure JavaScript Barcode Type: Bar Text: Alt Text: Options: Scale X,Y: Image Rotation: Normal Right Left Invert Show Barcode ``` -------------------------------- ### Install bwip-js Main Package Source: https://github.com/metafloor/bwip-js/blob/master/README.md Use this command to install the main bwip-js package. This package is cross-platform. ```bash npm install bwip-js ``` -------------------------------- ### Install bwip-js via npm Source: https://github.com/metafloor/bwip-js/wiki/README-2.0 Install the latest npm module for bwip-js. ```bash npm install bwip-js ``` -------------------------------- ### Install Linux Build Dependencies Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-FreeType Installs necessary packages like git, Java runtime, cmake, and g++ required for compiling FreeType. ```bash $ sudo apt-get install git $ sudo apt-get install default-jre $ sudo apt-get install cmake $ sudo apt-get install g++ ``` -------------------------------- ### Install and Use bwip-js CLI Source: https://github.com/metafloor/bwip-js/wiki/README-2.0 Install bwip-js globally via npm and use it as a command-line tool for generating barcode images. The CLI supports specifying the barcode symbol, text, and output file. ```bash $ 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. ``` ```bash $ bwip-js qrcode 123456789 ~/qrcode.png ``` -------------------------------- ### Get bwip-js from GitHub Source: https://github.com/metafloor/bwip-js/wiki/README-2.0 Download the latest code directly from the bwip-js GitHub repository. ```bash https://github.com/metafloor/bwip-js ``` -------------------------------- ### Install js-beautify Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-bwipjs Install the `js-beautify` npm package, which is used to format the cross-compiled JavaScript code for better readability. ```bash $ npm install js-beautify ``` -------------------------------- ### Using BWIPP Specific Parameters Source: https://github.com/metafloor/bwip-js/wiki/Online-Barcode-API This example illustrates how to use BWIPP-specific parameters, including boolean flags and valued parameters that require URL-encoded values. ```APIDOC ## GET /?bcid={type}&text={encoded_text}&{bwipp_param}&{bwipp_valued_param}={encoded_value} ### Description Generates a barcode using BWIPP-specific options, demonstrating boolean flags and valued parameters. ### Method GET ### Endpoint http://bwipjs-api.metafloor.com/ ### Parameters #### Query Parameters - **bcid** (string) - Required - The type of barcode to generate. - **text** (string) - Required - The value to encode, potentially containing BWIPP control characters (e.g., '^FNC1'). Must be URL-encoded if necessary. - **parsefnc** (boolean) - Optional - Enables parsing of function characters in the text (BWIPP specific). - **alttext** (string) - Optional - Specifies alternate text, requires URL-encoding (BWIPP specific). ### Request Example ``` http://bwipjs-api.metafloor.com/?bcid=code128&text=%5EFNC1011234567890&parsefnc&alttext=%2801%291234567890 ``` ### Response #### Success Response (200) - Content-Type: image/png - The generated barcode image. #### Error Response (4XX) - Content-Type: text/plain - An error message indicating the issue. ``` -------------------------------- ### Verify Node.js Version Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-bwipjs Verify that Node.js is installed and accessible in your system's PATH. This is a fundamental requirement for compiling and running bwip-js. ```bash $ node --version v5.11.0 ``` -------------------------------- ### Install Platform-Specific bwip-js Packages Source: https://github.com/metafloor/bwip-js/blob/master/README.md Install platform-specific packages if the main package does not work with your build stack. These are ES modules only, except for the node package. ```bash npm install @bwip-js/node ``` ```bash npm install @bwip-js/browser ``` ```bash npm install @bwip-js/react-native ``` ```bash npm install @bwip-js/generic ``` -------------------------------- ### Electron App with Node.js Package Source: https://github.com/metafloor/bwip-js/blob/master/README.md Basic HTML file for a single-window Electron app using the '@bwip-js/node' package to generate a QR code and display it. Ensure the node-js package is installed. ```html Hello World! Node.js , Chromium , Electron , bwip-js , and BWIPP .


  

  

```

--------------------------------

### Electron App Integration with bwip-js

Source: https://github.com/metafloor/bwip-js/wiki/README-2.0

Integrate bwip-js into an Electron application using the Node.js toBuffer() interface. This example shows how to render a QR code and display it in an HTML page.

```html


  
    
    Hello World!
  
  
    Node.js ,
    Chromium ,
    and Electron .
    


  

  

```

--------------------------------

### Basic Barcode Generation

Source: https://github.com/metafloor/bwip-js/wiki/Online-Barcode-API

This example demonstrates how to generate a basic barcode using the required 'bcid' (barcode type) and 'text' (value to encode) parameters.

```APIDOC
## GET /?bcid={type}&text={value}

### Description
Generates a barcode image of the specified type with the given text value.

### Method
GET

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

### Parameters
#### Query Parameters
- **bcid** (string) - Required - The type of barcode to generate (e.g., code128).
- **text** (string) - Required - The value to encode in the barcode.

### Response
#### Success Response (200)
- Content-Type: image/png - The generated barcode image.

#### Error Response (4XX)
- Content-Type: text/plain - An error message indicating the issue.
```

--------------------------------

### Run bwip-js Tests

Source: https://github.com/metafloor/bwip-js/wiki/Development/Code-Coverage

Use this command to run existing test cases for a specific encoder. Ensure you have followed the compilation and setup instructions.

```bash
run  "" ""
```

--------------------------------

### Advanced Barcode Generation with Options

Source: https://github.com/metafloor/bwip-js/wiki/Online-Barcode-API

This example shows how to use additional bwip-js and BWIPP parameters to customize the barcode appearance, such as scaling, rotation, and including text.

```APIDOC
## GET /?bcid={type}&text={value}&scale={factor}&rotate={orientation}&includetext&alttext={text}

### Description
Generates a barcode image with advanced customization options.

### Method
GET

### Endpoint
https://bwipjs-api.metafloor.com/

### Parameters
#### Query Parameters
- **bcid** (string) - Required - The type of barcode to generate (e.g., code128).
- **text** (string) - Required - The value to encode in the barcode.
- **scale** (integer) - Optional - Sets both x-axis and y-axis scaling factors (e.g., 3).
- **scaleX** (integer) - Optional - The x-axis scaling factor.
- **scaleY** (integer) - Optional - The y-axis scaling factor.
- **rotate** (string) - Optional - Allows rotating the image ('N', 'R', 'L', 'I'). Defaults to 'N'.
- **monochrome** (boolean) - Optional - Renders the image in monochrome.
- **includetext** (boolean) - Optional - Displays the human-readable text below the barcode (BWIPP specific).
- **alttext** (string) - Optional - Specifies alternate text to appear below the barcode (BWIPP specific). Value must be URL-encoded.

### Request Example
```
http://bwipjs-api.metafloor.com/?bcid=code128&text=AB1234567890&scale=3&rotate=I&includetext
```

### Response
#### Success Response (200)
- Content-Type: image/png - The generated barcode image.

#### Error Response (4XX)
- Content-Type: text/plain - An error message indicating the issue.
```

--------------------------------

### Verify Ghostscript Version

Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-bwipjs

Verify that the Ghostscript wrapper script is working correctly by checking its version. This confirms the script is executable and points to the correct Ghostscript installation.

```bash
$ gs --version
9.07
```

--------------------------------

### Unused Variables Pattern: Another Example (Original)

Source: https://github.com/metafloor/bwip-js/wiki/Development/Version-1.0-Optimization-Notes

Another example of the unused variables pattern, showing multiple unused variables that can be eliminated.

```javascript
$astore($a($counttomark() - 1)); /*12357*/
var _6y = $k[--$j]; /*12357*/
var _6z = $k[--$j]; /*12357*/
var _70 = $k[--$j]; /*12357*/
$put($1.rowbits, $1.i, _6y); /*12358*/
```

--------------------------------

### Advanced Barcode Generation URL

Source: https://github.com/metafloor/bwip-js/wiki/Online-Barcode-API

This example demonstrates advanced options like scaling, rotation, and including text. Ensure BWIPP-specific options like 'includetext' are supported by the barcode type.

```url
http://bwipjs-api.metafloor.com/?bcid=code128&text=AB1234567890&scale=3&rotate=I&includetext
```

--------------------------------

### Command Line with Custom Font

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

Example of using the '--loadfont' option with the bwip-js command-line utility to specify custom font metrics. The font path must be correct.

```bash
$ bwip-js code128 12345678 includetext textfont=CONS textxalign=center \
  loadfont=CONS,250,100,../fonts/Inconsolata.otf /tmp/code128.png
```

--------------------------------

### React Usage with Canvas

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

Minimal example of bwip-js in a React app using the toCanvas method. Ensure you import the correct package based on your environment.

```tsx
import bwipjs from 'bwip-js';           // If using the main package import
// or
import bwipjs from '@bwip-js/browser';  // Platform-specific package import

export default function App() {
  return (
     {
        if (!canvas) {
          return;
        }

        bwipjs.toCanvas(canvas, {
          bcid:        'code128',               // Barcode type
          text:        '0123456789',            // Text to encode
          scale:       window.devicePixelRatio, // Scaling factor for high-DPI devices
          height:      10,                      // Bar height, in millimeters
          includetext: true,                    // Show human-readable text
          textxalign:  'center',                // Always good to set this
        });
      }}
    />
  );
}
```

--------------------------------

### Get Latest Code from GitHub

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

Clone the repository from GitHub to obtain the latest code. Branches and npm versions are synced with each release.

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

--------------------------------

### Get Static Version Properties

Source: https://github.com/metafloor/bwip-js/wiki/Methods-Reference

Access static properties to retrieve version information for bwip-js and the underlying BWIPP library.

```javascript
bwipjs.BWIPJS_VERSION
```

```javascript
bwipjs.BWIPP_VERSION
```

--------------------------------

### Node.js ES6 Module Import

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

Demonstrates how to import the bwip-js library using ES6 modules in a Node.js environment. Choose the appropriate import based on your setup.

```javascript
import bwipjs from 'bwip-js';           // If using the main package import
  // or
import bwipjs from '@bwip-js/node';     // Platform-specific package import
```

--------------------------------

### Node.js HTTP Server Request Handler

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

A minimal Node.js HTTP server example that uses bwip-js to render barcode images based on URL query parameters.

```javascript
// 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);
```

--------------------------------

### Optimized SVG Import with Specific Barcode Types

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

For reduced bundle size when using tree-shaking, import only the necessary barcode types and the `drawingSVG` interface. This example shows importing the `qrcode` type.

```javascript
import { qrcode, drawingSVG } from 'bwip-js';
  // or  one of : browser, node, react-native, generic
import { qrcode, drawingSVG } from '@bwip-js/'; 

// drawingSVG() returns a bwip-js drawing object.
let svg = qrcode(options, drawingSVG());
```

--------------------------------

### React Native Usage with Data URL

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

Example for React Native using the toDataURL method to generate an image URI for the Image component. Requires the @bwip-js/react-native package.

```tsx
import { useEffect, useState } from 'react';
import { Image, PixelRatio } from 'react-native';
import bwipjs, { type DataURL } from '@bwip-js/react-native';

export default function App() {
  const [source, setSource] = useState();

  useEffect(() => {
    bwipjs.toDataURL({
      bcid:        'code128',        // Barcode type
      text:        '0123456789',     // Text to encode
      scale:       PixelRatio.get(), // Scaling factor for high-DPI devices
      height:      10,               // Bar height, in millimeters
      includetext: true,             // Show human-readable text
      textxalign:  'center',         // Always good to set this
    }).then(setSource);
  }, []);

  if (!source) {
    return null;
  }

  const { height, width, uri } = source;

  return ;
}
```

--------------------------------

### Unused Variables Pattern: Another Example (Optimized)

Source: https://github.com/metafloor/bwip-js/wiki/Development/Version-1.0-Optimization-Notes

Optimized version of the second unused variables example. It eliminates two unused variables by adjusting the index manipulation.

```javascript
$astore($a($counttomark() - 1)); /*12357*/
var _6y = $k[--$j]; /*12357*/
$j-=2;
$put($1.rowbits, $1.i, _6y); /*12358*/
```

--------------------------------

### Compile bwip-js

Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-bwipjs

Compile the bwip-js project using the provided script. This will generate `bwipp.js` and `bwipp-min.js` in the current directory.

```bash
$ ./psc
```

--------------------------------

### Initialize bwip-js Barcode Generator

Source: https://github.com/metafloor/bwip-js/blob/master/demo.html

Sets up the barcode generator by loading symbol data, populating the symbol selection dropdown, and restoring previous settings from local storage. It also configures event listeners for user interactions.

```javascript
const symbols = {};
window.addEventListener('load', function() {
    var lastSymbol, lastBarText, lastAltText, lastOptions, lastRotate, lastScaleX, lastScaleY, lastRenderAs = 'render-canvas';
    try {
        lastSymbol = localStorage.getItem('bwipjsLastSymbol');
        lastBarText = localStorage.getItem('bwipjsLastBarText');
        lastAltText = localStorage.getItem('bwipjsLastAltText');
        lastOptions = localStorage.getItem('bwipjsLastOptions');
        lastRotate = localStorage.getItem('bwipjsLastRotate');
        lastScaleX = +localStorage.getItem('bwipjsLastScaleX');
        lastScaleY = +localStorage.getItem('bwipjsLastScaleY');
        lastRenderAs = localStorage.getItem('bwipjsLastRenderAs');
    } catch (e) { }

    // Set up the select list of barcode types
    var sel = document.getElementById('symbol');
    var opts = bwipjs.symbolList.slice();
    for (let i = 0; i < opts.length; i++) {
        symbols[opts[i].bcid] = opts[i];
    }
    opts.sort(function (a,b) { return a.desc < b.desc ? -1 : 1 });
    for (var i = 0, l = opts.length; i < l; i++) {
        var elt = document.createElement('option');
        elt.textContent = opts[i].desc;
        elt.value = opts[i].bcid;
        sel.appendChild(elt);
    }

    sel.addEventListener('change', function(ev) {
        var desc = symbols[sel.value];
        if (desc) {
            document.getElementById('symtext').value = desc.text;
            document.getElementById('symopts').value = desc.opts;
        } else {
            document.getElementById('symtext').value = '';
            document.getElementById('symopts').value = '';
        }
        document.getElementById('symaltx').value = '';
        document.getElementById('saveas').style.visibility = 'hidden';
        document.getElementById('stats').textContent = '';
        document.getElementById('canvas').style.display = 'none';
        document.getElementById('svgdiv').style.display = 'none';
        document.getElementById('output').textContent = '';
    });

    if (lastSymbol) {
        sel.value = lastSymbol;
    } else {
        sel.selectedIndex = 0;
    }
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    sel.dispatchEvent(evt);

    if (lastBarText) {
        document.getElementById('symtext').value = lastBarText;
        document.getElementById('symaltx').value = lastAltText;
        document.getElementById('symopts').value = lastOptions;
    }
    if (lastRenderAs) {
        document.getElementById(lastRenderAs).checked = true;
    }
    if (lastScaleX && lastScaleY) {
        document.getElementById('scaleX').value = lastScaleX;
        document.getElementById('scaleY').value = lastScaleY;
    }
    if (lastRotate) {
        document.getElementById('rotate' + lastRotate).checked = true;
    }

    document.getElementById('scaleX').addEventListener('change', function(ev) {
        document.getElementById('scaleY').value = ev.target.value;
    });
    document.getElementById('render').addEventListener('click', render);
    document.getElementById('saveas').style.visibility = 'hidden';

    // Allow Enter to render
    document.getElementById('params').addEventListener('keypress', function(ev) {
        if (ev.which == 13) {
            render();
            ev.stopPropagation();
            ev.preventDefault();
            return false;
        }
    });

    document.getElementById('versions').textContent = 'bwip-js ' + bwipjs.BWIPJS_VERSION + ' / BWIPP ' + bwipjs.BWIPP_VERSION;

    // A reasonable match to OCR-B metrics.
    bwipjs.loadFont("Inconsolata", 95, 105, Inconsolata);
});
```

--------------------------------

### Run bwip-js Benchmark

Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-bwipjs

Execute the benchmark script for bwip-js. The `--expose-gc` flag is necessary for manual garbage collection within the benchmark. The script runs warm-up rounds before timing rounds.

```bash
$ node --expose-gc benchmark
```

--------------------------------

### Node.js Request Handler Test URL

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

Example URL to test the Node.js barcode API request handler running locally.

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

--------------------------------

### Create Ghostscript Wrapper Script

Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-bwipjs

Create a bash wrapper script for the Windows console version of Ghostscript if it's not directly available in your PATH. Ensure the path to `gswin64c.exe` is correct for your system.

```bash
#!/bin/bash
"/c/Program Files/gs/gs9.07/bin/gswin64c.exe" "$@"
```

--------------------------------

### bwipjs.fixupOptions()

Source: https://github.com/metafloor/bwip-js/wiki/Methods-Reference

Prepares the options object for drawing by adjusting values like padding and background color. This is a preparatory step before rendering.

```APIDOC
## bwipjs.fixupOptions()

### Description
Call this before passing your options object to a drawing constructor.

### Usage
```javascript
bwipjs.fixupOptions(options)
```

### Parameters
- `options` (object): The options object to be modified.

### Notes
- `fixupOptions()` modifies options values (currently padding and background color) to provide a simplified interface for the drawing code.
```

--------------------------------

### Initialize bwip-js and Render Barcode

Source: https://github.com/metafloor/bwip-js/blob/master/examples/example.html

Sets up event listeners for barcode generation, including loading saved preferences from local storage and rendering the barcode to a canvas element. Handles user input for barcode type, text, options, rotation, and scaling.

```javascript
window.addEventListener('load', function() {
  var lastSymbol, lastBarText, lastAltText, lastOptions, lastRotate, lastScaleX, lastScaleY;
  try {
    lastSymbol = localStorage.getItem('bwipjsLastSymbol');
    lastBarText = localStorage.getItem('bwipjsLastBarText');
    lastAltText = localStorage.getItem('bwipjsLastAltText');
    lastOptions = localStorage.getItem('bwipjsLastOptions');
    lastRotate = localStorage.getItem('bwipjsLastRotate');
    lastScaleX = +localStorage.getItem('bwipjsLastScaleX');
    lastScaleY = +localStorage.getItem('bwipjsLastScaleY');
  } catch (e) { }

  // Set up the select list of barcode types
  var sel = document.getElementById('symbol');
  var opts = [];
  for (var id in symdesc) {
    opts.push(symdesc[id]);
  }
  opts.sort(function (a,b) { return a.desc < b.desc ? -1 : 1 });
  for (var i = 0, l = opts.length; i < l; i++) {
    var elt = document.createElement('option');
    elt.textContent = opts[i].desc;
    elt.value = opts[i].sym;
    sel.appendChild(elt);
  }

  sel.addEventListener('change', function(ev) {
    var desc = symdesc[sel.value];
    if (desc) {
      document.getElementById('symtext').value = desc.text;
      document.getElementById('symopts').value = desc.opts;
    } else {
      document.getElementById('symtext').value = '';
      document.getElementById('symopts').value = '';
    }
    document.getElementById('symaltx').value = '';
    var canvas = document.getElementById('canvas');
    canvas.width = canvas.width;
  });

  if (lastSymbol) {
    sel.value = lastSymbol;
  } else {
    sel.selectedIndex = 0;
  }
  var evt = document.createEvent("HTMLEvents");
  evt.initEvent("change", false, true);
  sel.dispatchEvent(evt);

  if (lastBarText) {
    document.getElementById('symtext').value = lastBarText;
    document.getElementById('symaltx').value = lastAltText;
    document.getElementById('symopts').value = lastOptions;
  }
  if (lastScaleX && lastScaleY) {
    document.getElementById('scaleX').value = lastScaleX;
    document.getElementById('scaleY').value = lastScaleY;
  }
  if (lastRotate) {
    document.getElementById('rotate' + lastRotate).checked = true;
  }

  document.getElementById('scaleX').addEventListener('change', function(ev) {
    document.getElementById('scaleY').value = ev.target.value;
  });
  document.getElementById('scaleX').addEventListener('click', function(ev) {
    document.getElementById('scaleY').value = ev.target.value;
  });

  document.getElementById('render').addEventListener('click', render);

  // Allow Enter to render
  document.getElementById('params').addEventListener('keypress', function(ev) {
    if (ev.which == 13) {
      render();
      ev.stopPropagation();
      ev.preventDefault();
      return false;
    }
  });

  document.getElementById('versions').textContent = 'bwip-js ' + bwipjs.BWIPJS_VERSION + ' / BWIPP ' + bwipjs.BWIPP_VERSION;
});

function render() {
  var elt = symdesc[document.getElementById('symbol').value];
  var text = document.getElementById('symtext').value.trim();
  var alttext = document.getElementById('symaltx').value.trim();
  var options = document.getElementById('symopts').value.trim();
  var rotate = document.querySelector('input[name="rotate"]:checked').value;
  var scaleX = +document.getElementById('scaleX').value || 2;
  var scaleY = +document.getElementById('scaleY').value || 2;

  try {
    localStorage.setItem('bwipjsLastSymbol', elt.sym);
    localStorage.setItem('bwipjsLastBarText', text);
    localStorage.setItem('bwipjsLastAltText', alttext);
    localStorage.setItem('bwipjsLastOptions', options);
    localStorage.setItem('bwipjsLastScaleX', scaleX);
    localStorage.setItem('bwipjsLastScaleY', scaleY);
    localStorage.setItem('bwipjsLastRotate', rotate);
  } catch (e) { }

  // Clear the page
  document.getElementById('output').textContent = '';
  var canvas = document.getElementById('canvas');
  canvas.height = 1;
  canvas.width = 1;
  canvas.style.visibility = 'hidden';
  if (window.devicePixelRatio) {
    canvas.style.zoom = 1 / window.devicePixelRatio;
  } else {
    canvas.style.zoom = 1;
  }

  // Convert the options to an object.
  let opts = {};
  let aopts = options.split(' ');
  for (let i = 0; i < aopts.length; i++) {
    if (!aopts[i]) {
      continue;
    }
    var eq = aopts[i].indexOf('=');
    if (eq == -1) {
      if (aopts[i][0] == '!') {
        // !parameter => false
        opts[aopts[i].substr(1)] = false;
      } else {
        // parameter => true
        opts[aopts[i]] = true;
      }
    } else {
      opts[aopts[i].substr(0, eq)] = aopts[i].substr(eq+1);
    }
  }

  // Finish up the options object.
  opts.text = text;
  opts.bcid = elt.sym;
  opts.scaleX = scaleX;
  opts.scaleY = scaleY;
  opts.rotate = rotate;
  if (alttext) {
    opts.alttext = alttext;
  }

  // Draw the bar code to the canvas using a custom drawing interface.
  try {
    // fixupOptions() modifies options values (currently padding and
    // background color) to provide a simplified interface for the
    // drawing code.
    bwipjs.fixupOptions(opts);
    bwipjs.render(opts, DrawingExample(canvas, opts));
    canvas.style.visibility = 'visible';
  } catch (e) {
    // Watch for BWIPP generated raiseerror's.
    var msg = (''+e).trim();
    if (msg.indexOf("bwipp.") >= 0) {
      document.getElementById('output').textContent = msg;
    } else if (e.stack) {
      // GC includes the message

```

--------------------------------

### File Size Comparison: freetype.js vs. stbtt.js

Source: https://github.com/metafloor/bwip-js/wiki/FreeType-Versus-STBTT

Compares the disk space occupied by the FreeType-based JavaScript library and the STBTT-based library. Note that freetype.js includes embedded OCR fonts, adding to its size.

```bash
$ ls -l freetype.js stbtt.js
-rw-rw-r-x  1 bwip-js users 1394208 Sep 19  2016 freetype.js
-rw-rw-r--  1 bwip-js users   56483 Oct 16 14:51 stbtt.js
```

--------------------------------

### Make Wrapper Script Executable

Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-bwipjs

Make the created Ghostscript wrapper script executable. This command grants execute permissions to the owner of the file.

```bash
$ chmod u+x gs
```

--------------------------------

### Original Forall Pattern

Source: https://github.com/metafloor/bwip-js/wiki/Development/Version-1.0-Optimization-Notes

Illustrates a pattern involving '$forall' and subsequent stack pops for assignment to variables. Safety of optimization depends on stack state after the final pop.

```javascript
$forall($geti($1.tab174, $1.i + 1, 7)); /*6262*/
$1.cte = $k[--$j]; /*6263*/
$1.cto = $k[--$j]; /*6263*/
$1.cmwe = $k[--$j]; /*6264*/
$1.cmwo = $k[--$j]; /*6264*/
$1.cele = $k[--$j]; /*6265*/
$1.celo = $k[--$j]; /*6265*/
$1.cgs = $k[--$j]; /*6266*/
```

--------------------------------

### Load Custom Font in Node.js

Source: https://github.com/metafloor/bwip-js/wiki/Using-Your-Own-Fonts

Demonstrates loading a custom font file in Node.js using `fs.readFileSync`. Ensure the path to the font file is correct. The `100, 100` arguments specify the default size multipliers for height and width.

```javascript
// This shows how to load the Inconsolata font, supplied with bwip-js.
// The path to your fonts will be different.
// 100 (100%) indicates to use the font's default size.
bwipjs.loadFont('INCONS', 100, 100,
      require('fs').readFileSync(__dirname + '/fonts/Inconsolata.otf', 'binary'));
```

--------------------------------

### Barcode Generation with BWIPP Options

Source: https://github.com/metafloor/bwip-js/wiki/Online-Barcode-API

This URL shows how to use BWIPP-specific options like 'parsefnc' and 'alttext'. Remember to URL-encode values for parameters like 'text' and 'alttext' if they contain special characters.

```url
http://bwipjs-api.metafloor.com/?bcid=code128&text=%5EFNC1011234567890&parsefnc&alttext=%2801%291234567890
```

--------------------------------

### Get Raw BWIPP Encoding Data

Source: https://github.com/metafloor/bwip-js/wiki/Methods-Reference

Invokes the low-level BWIPP code to retrieve the raw encoding data for a barcode. This function is synchronous and throws errors. It can be called with either options or encoder/text/opts-string arguments.

```javascript
bwipjs.raw(options)
```

```javascript
bwipjs.raw(encoder, text, opts-string)
```

--------------------------------

### Generate PNG Image with Callback

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

Use this method to generate a PNG image buffer with a callback function for handling results or errors. Ensure the 'bwip-js' module is required.

```javascript
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
    }
});
```

--------------------------------

### Node.js HTTP Barcode Request Handler

Source: https://github.com/metafloor/bwip-js/wiki/README-2.0

This Node.js server handles HTTP requests to generate barcode images. It uses bwip-js's request method and expects barcode parameters in the URL query string, starting with '/?bcid='. Ensure the server is listening on the correct port.

```javascript
// 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);
```

--------------------------------

### Generate PNG Image with Promises

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

This approach uses Promises for asynchronous image generation, which can be more readable than callbacks. Omit the callback function to enable Promise-based behavior.

```javascript
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
});
```

--------------------------------

### Original Aload-to-Vars Pattern

Source: https://github.com/metafloor/bwip-js/wiki/Development/Version-1.0-Optimization-Notes

Demonstrates the 'aload' followed by a series of pops pattern, commonly used to load parameters onto the stack and then into temporary variables.

```javascript
$aload(_5p); /*2699*/
var _5v = $k[--$j]; /*2699*/
var _5w = $k[--$j]; /*2699*/
```

--------------------------------

### Individual Encoder Usage (React Native)

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

Demonstrates how to import and use individual barcode encoders directly from the `@bwip-js/react-native` package. This approach supports tree-shaking and allows for more granular control. Dashes in barcode IDs are replaced with underscores for import names.

```APIDOC
## Individual Encoder Import

### Description
Allows importing and using specific barcode encoders directly, which aids in bundler tree-shaking. The function signature is the same as `toDataURL`, but the `bcid` option is ignored.

### Method
`import { encoder_name } from '@bwip-js/react-native';
await encoder_name(options);`

### Parameters
#### Path Parameters
None

#### Query Parameters
None

#### Request Body
- **options** (object) - Configuration object for the barcode (same as `toDataURL`).

### Request Example
```javascript
import { gs1_128 } from '@bwip-js/react-native';

try {
    let buf = await gs1_128({
        text: '12345',
        scale: 3,
        height: 10,
        includetext: true,
        textxalign: 'center'
    });
    // Use the returned buffer or data URL
} catch (e) {
    console.error(e);
}
```

### Response
- **DataURL** (object) - An object containing barcode image information (similar to `toDataURL`).
  - **height** (number) - The height of the image in pixels.
  - **width** (number) - The width of the image in pixels.
  - **uri** (string) - A data URL string for the generated image.
```

--------------------------------

### Compile bwip-js with Coverage Enabled

Source: https://github.com/metafloor/bwip-js/wiki/Development/Code-Coverage

Compile the bwip-js project with code coverage instrumentation enabled. This will generate a bwipp.js file with embedded logic to record branch coverage at runtime.

```bash
$ ./psc --with-coverage
```

--------------------------------

### Multi-Push Pattern: Proposed Optimization 2

Source: https://github.com/metafloor/bwip-js/wiki/Development/Version-1.0-Optimization-Notes

An alternative proposed optimization for the multi-push pattern using a hypothetical internal method '$kcopy'. This is also a code-size optimization.

```javascript
$kcopy();
```

--------------------------------

### Extracting Raw Data for QRCode

Source: https://github.com/metafloor/bwip-js/wiki/Notes-on-the-Raw-BWIPP-Data

Shows the raw data structure for a qrcode. This includes pixel data (`pixs`), grid dimensions (`pixx`, `pixy`), and symbol dimensions (`height`, `width`).

```bash
$ node raw qrcode "This isQRCode"
0:
  pixs: [ 1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,1, ...snip... 1,0,1,1,1,0,0,0,1,1,0,1,0 ]
  pixx: 21
  pixy: 21
  height: 0.5833333333333334
  width: 0.5833333333333334
```

--------------------------------

### Compile FreeType with Emscripten and main.c

Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-FreeType

Builds the FreeType library using Emscripten, embeds OCR font files, and links the custom `main.c` to create the final `freetype.js` module.

```bash
$ emconfigure ./configure
$ emmake make
$ emcc -I ./include -o main.o main.c
$ emcc -O3 --embed-file OCRA.otf --embed-file OCRB.otf -s NO_EXIT_RUNTIME=1 \
  -s EXPORTED_FUNCTIONS='["_main","_load_font","_find_font","_get_bitmap",
  "_get_left","_get_top","_get_width","_get_height","_get_pitch","_get_advance"]' \
  main.o objs/.libs/libfreetype.so -o freetype.js
```

--------------------------------

### Run Tests and Generate Coverage Map

Source: https://github.com/metafloor/bwip-js/wiki/Development/Code-Coverage

Execute tests for a specific encoder and then generate an updated coverage map. The 'uncover' command updates 'covermap.html' locally.

```bash
$ ./runtests 
$ ./uncover
```

--------------------------------

### Run bwip-js Test Cases

Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-bwipjs

Execute the test suite for bwip-js. Providing an encoder name will run tests only for that specific encoder, otherwise, all tests will be executed.

```bash
$ ./runtests [encoder]
```

--------------------------------

### Disable ZLIB and LZW Compression in FreeType

Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-FreeType

Comments out directives in `include/config/ftoption.h` to disable `zlib` and `LZW` support, which can cause link-time issues with Emscripten.

```c
/* #define FT_CONFIG_OPTION_USE_LZW */
/* #define FT_CONFIG_OPTION_USE_ZLIB */
```

--------------------------------

### Clone bwip-js Repository

Source: https://github.com/metafloor/bwip-js/wiki/Development/Compiling-bwipjs

Clone the 'develop' branch of the bwip-js repository into your desired directory. The `--single-branch` flag optimizes the clone by only fetching the specified branch. The trailing `.` ensures the repository is cloned into the current directory.

```bash
$ cd 
$ git clone -b develop --single-branch git@github.com:metafloor/bwip-js.git .
```

--------------------------------

### Filling Compound Paths with `fill()`

Source: https://github.com/metafloor/bwip-js/wiki/Annotated-Example-Drawing-Object

Fills the accumulated compound path with the specified RGB color using the 'nonzero' fill rule. Resets the compound path after filling.

```javascript
fill(rgb) {
            if (!compound) {
                return;
            }
            ctx.fillStyle = '#' + rgb;
            ctx.fill(compound, 'nonzero');
            compound = undefined;
        }
```

--------------------------------

### Access Local Coverage Map

Source: https://github.com/metafloor/bwip-js/wiki/Development/Code-Coverage

Use a 'file:///' URL in your browser to view the generated coverage map. Replace 'encoder' with the specific encoder name.

```bash
file:///c:/bwip-js/covermap.html#encoder
```

--------------------------------

### Canvas Display and Scaling

Source: https://github.com/metafloor/bwip-js/blob/master/demo.html

Configures the canvas display, sets the save filename, and applies zoom based on device pixel ratio.

```javascript
function showCVS(ts0, ts1) { canvas.style.display = ''; setURL(); document.getElementById('stats').textContent = elt.bcid + ' rendered in ' + (ts1-ts0) + ' msecs.'; document.getElementById('saveas').style.visibility = 'visible'; saveCanvas.basename = elt.bcid + '-' + text.replace(/[^a-zA-Z0-9.\_]+/g, '-'); if (window.devicePixelRatio) { canvas.style.zoom = 1 / window.devicePixelRatio; } else { canvas.style.zoom = 1; } }
```

--------------------------------

### Importing Individual Encoders in React Native

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

Demonstrates importing and using a specific encoder (gs1_128) directly from the @bwip-js/react-native package. Dashes in bcid names are replaced with underscores.

```javascript
import { gs1_128 } from '@bwip-js/react-native';

try {
    let buf = await gs1_128(options);
} catch (e) {
    // `e` may be a string or Error object
}
```

--------------------------------

### Generate Barcode to Buffer (Node.js)

Source: https://github.com/metafloor/bwip-js/wiki/Methods-Reference

Converts barcode options into a PNG image stored in a Node.js Buffer. It can be used with a callback or return a Promise if no callback is provided. Node.js usage only.

```javascript
function callback(err, png)
```

```javascript
bwipjs.toBuffer(options[, callback])
```

--------------------------------

### Importing Specific Barcode Types with SVG Drawing Interface

Source: https://github.com/metafloor/bwip-js/blob/master/README.md

For reduced bundle size, import only necessary barcode types and the built-in SVG drawing interface. This avoids including all BWIPP encoders.

```APIDOC
## Importing Specific Barcode Types with SVG Drawing Interface

### Description
To optimize for tree-shaking and reduce bundle size, import only the barcode types you need along with the `drawingSVG` interface.

### Usage
Import specific barcode generators (e.g., `qrcode`) and the `drawingSVG` function. The `drawingSVG()` function returns a bwip-js drawing object that can be used with barcode generators.

### Example (JavaScript Module Import)
```javascript
import { qrcode, drawingSVG } from 'bwip-js';

// Or from a platform-specific import:
// import { qrcode, drawingSVG } from '@bwip-js/'; // e.g., @bwip-js/browser

let options = { /* barcode options */ };
let svg = qrcode(options, drawingSVG());
```

### Parameters
- **options** (object) - The configuration options for the barcode.
- **drawingSVG()** - A function that returns a bwip-js drawing object configured for SVG output.

### Return Value
A string containing the SVG barcode definition.
```

--------------------------------

### bwipjs.request()

Source: https://github.com/metafloor/bwip-js/wiki/Methods-Reference

Generates a PNG image from the query arguments of a Node.js HTTP request object. This function is asynchronous and intended for Node.js usage only.

```APIDOC
## bwipjs.request()

### Description
Returns a PNG image from the query args of a node.js http request object.

### Usage
```javascript
bwipjs.request(req, res [, overrides])
```

### Notes
- This function is asynchronous.
- Node.js usage only.
```

--------------------------------

### Generate Barcode PNG Buffer with Promises

Source: https://github.com/metafloor/bwip-js/wiki/README-2.0

Generates a barcode as a PNG image buffer in Node.js using Promises. This approach is suitable for asynchronous operations where you prefer to use .then() and .catch() for handling results and errors.

```javascript
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
    });
```