UNPKG

2.69 kBJavaScriptView Raw
1exports.binaryRepresentationForBarcodeData = function(barcodeData) {
2 var digits = {
3 0: "00110",
4 1: "10001",
5 2: "01001",
6 3: "11000",
7 4: "00101",
8 5: "10100",
9 6: "01100",
10 7: "00011",
11 8: "10010",
12 9: "01010"
13 };
14
15 if (barcodeData.length % 2 != 0) {
16 barcodeData = "0" + barcodeData;
17 }
18
19 var binaryDigits = "0000";
20 // Start of barcode
21 for (var i = 0; i < barcodeData.length; i += 2) {
22 var digit1 = digits[parseInt(barcodeData[i])];
23 var digit2 = digits[parseInt(barcodeData[i + 1])];
24
25 for (var j = 0; j < digit1.length; j++) {
26 binaryDigits += digit1[j] + digit2[j];
27 }
28 }
29
30 // End of barcode
31 binaryDigits += "1000";
32
33 return binaryDigits;
34}
35
36// Convert a value to a little endian hexadecimal value
37exports._getLittleEndianHex = function(value) {
38 var result = [];
39
40 for (var bytes = 4; bytes > 0; bytes--) {
41 result.push(String.fromCharCode(value & 0xff));
42 value >>= 0x8;
43 }
44
45 return result.join('');
46}
47
48exports._bmpHeader = function(width, height) {
49 var numFileBytes = exports._getLittleEndianHex(width * height);
50 width = exports._getLittleEndianHex(width);
51 height = exports._getLittleEndianHex(height);
52
53 return 'BM' + // Signature
54 numFileBytes + // size of the file (bytes)*
55 '\x00\x00' + // reserved
56 '\x00\x00' + // reserved
57 '\x36\x00\x00\x00' + // offset of where BMP data lives (54 bytes)
58 '\x28\x00\x00\x00' + // number of remaining bytes in header from here (40 bytes)
59 width + // the width of the bitmap in pixels*
60 height + // the height of the bitmap in pixels*
61 '\x01\x00' + // the number of color planes (1)
62 '\x20\x00' + // 32 bits / pixel
63 '\x00\x00\x00\x00' + // No compression (0)
64 '\x00\x00\x00\x00' + // size of the BMP data (bytes)*
65 '\x13\x0B\x00\x00' + // 2835 pixels/meter - horizontal resolution
66 '\x13\x0B\x00\x00' + // 2835 pixels/meter - the vertical resolution
67 '\x00\x00\x00\x00' + // Number of colors in the palette (keep 0 for 32-bit)
68 '\x00\x00\x00\x00'; // 0 important colors (means all colors are important)
69}
70
71exports.bmpLineForBarcodeData = function(barcodeData) {
72 var binaryRepresentation = exports.binaryRepresentationForBarcodeData(barcodeData);
73
74 var bmpData = new Array();
75 var black = true;
76 var offset = 0;
77
78 for(var i = 0; i < binaryRepresentation.length; i++) {
79 var digit = binaryRepresentation[i];
80 var color = black ? String.fromCharCode(0, 0, 0, 0) : String.fromCharCode(255, 255, 255, 0);
81 var pixelsToDraw = (digit == "0") ? 1 : 3;
82
83 for(var j = 0; j < pixelsToDraw; j++) {
84 bmpData[offset++] = color;
85 }
86
87 black = !black;
88 }
89
90 var bmpHeader = exports._bmpHeader(offset - 1, 1);
91 var bmpBuffer = new Buffer(bmpHeader + bmpData.join(""), 'binary');
92 return bmpBuffer.toString('base64');
93}