-
Notifications
You must be signed in to change notification settings - Fork 312
Using Your Own Fonts
Consider this is an experimental feature as stb_truetype.js
has not been tested extensively with fonts outside of the OCR-A, OCR-B and Inconsolata fonts provided in this project. Definitely do not use a font with codepoints outside of the Unicode BMP or with UTF-16 surrogate pairs.
From the Methods Reference:
Usage
bwipjs.loadFont(font-name, width-mult, height-mult, buffer)
-
font-name
: The name of the font. -
width-mult
: -
height-mult
: Used to adjust the width and height 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. -
buffer
: Can be a node.js Buffer, a Uint8Array, or a base64 encoded string that contains the font file data.
To use a custom loaded font in your barcode images, you must 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.
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 {
bwipjs.toCanvas('mycanvas', {
bcid: 'code128',
text: '0123456789',
scale: 3,
height: 10,
textfont: 'INCONS', // Use the custom font
includetext: true, // Must always set to display text
textxalign: 'center', // Provides the best formatting
});
} catch (e) {
// `e` may be a string or Error object
}