Skip to content

Using Your Own Fonts

metafloor edited this page Dec 14, 2019 · 7 revisions

Consider this is an experimental feature as stb_truetype.js has not been tested extensively with fonts other than those provided in this project. Definitely do not use a font that contains codepoints outside the Unicode BMP.

From the Methods Reference:

Usage

bwipjs.loadFont(font-name, font-data)
bwipjs.loadFont(font-name, size-mult, font-data)
bwipjs.loadFont(font-name, height-mult, width-mult, font-data)
  • font-name : The name of the font.
  • size-mult : Sets the height-mult and width-mult to the same value.
  • height-mult :
  • width-mult : Used to adjust the height and width of the font to better match BWIPP font metrics. A value of 100 means no adjustment. A value less than 100 will decrease the dimension. A value greater than 100 will increase the dimension.
  • font-data : Can be a node.js Buffer, a Uint8Array, or a base64 encoded string that contains the font file data.

If the *-mult values are omitted, the font is rendered at its natural size.

To use a custom loaded font in your barcode images, set the font-name on the following BWIPP options:

  • textfont
  • addontextfont

addontextfont is only used for ISBN, ISMN, and ISSN barcodes. By default, they are rendered with OCR-A.

You can adjust the size of the font that BWIPP uses via the options:

  • textsize
  • addontextsize

The size values are in points.

Example Code

Sample node.js code to load a font:

// 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'));

In a browser, how you get the binary font file is dependent on your web framework. loadFont() supports base64-encoded strings, which should simplify either embedding the font directly in your document or retrieving via XHR.

Once you have a font loaded, call it out using the BWIPP option textfont:

try {
  let cvs = bwipjs.toCanvas('mycanvas', {
		bcid:        'code128',
		text:        '0123456789',
		scale:       3,
		height:      10,
                textfont:    'INCONS',    // Use the custom font
              //textsize:    10,          // Adjust if necessary
		includetext: true,        // Must always set to display text
		textxalign:  'center',    // Provides the best formatting
	});
} catch (e) {
	// `e` may be a string or Error object
}
You can’t perform that action at this time.