ean13.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * barcode generator - EAN13 (ISBN)
  3. */
  4. var gm = require('gm'),
  5. getCheckDigit = require('./utils/checksums').weight3even10,
  6. Barcode1D = require('./utils/draw1D');
  7. const START = [1,1,1];
  8. const MIDDLE = [1,1,1,1,1];
  9. const END = [1,1,1];
  10. const LEFT = 0;
  11. const RIGHT = 0;
  12. const GCODE = 1;
  13. const BARMAP = [
  14. [
  15. [3,2,1,1], [2,2,2,1], [2,1,2,2], [1,4,1,1], [1,1,3,2], // L/R
  16. [1,2,3,1], [1,1,1,4], [1,3,1,2], [1,2,1,3], [3,1,1,2]
  17. ],
  18. [
  19. [1,1,2,3], [1,2,2,2], [2,2,1,2], [1,1,4,1], [2,3,1,1], // G
  20. [1,3,2,1], [4,1,1,1], [2,1,3,1], [3,1,2,1], [2,1,1,3]
  21. ]
  22. ];
  23. const ENCODE_GROUPS = [
  24. [0,0,0,0,0,0],
  25. [0,0,1,0,1,1],
  26. [0,0,1,1,0,1],
  27. [0,0,1,1,1,0],
  28. [0,1,0,0,1,1],
  29. [0,1,1,0,0,1],
  30. [0,1,1,1,0,0],
  31. [0,1,0,1,0,1],
  32. [0,1,0,1,1,0],
  33. [0,1,1,0,1,0]
  34. ];
  35. /*
  36. EAN13 has the same format, which happens to be the same as UPC.
  37. This is also one of the reasons why EAN13 codes starting with 0 are also valid
  38. UPC codes.
  39. Start - 3 wide
  40. Data (x6) - 7 wide
  41. Middle - 5 wide)
  42. Data (x5) - 7 wide
  43. Check - 7 wide
  44. End - 3 wide
  45. */
  46. const MODULE_WIDTH = 95;
  47. /*
  48. * generate ean13 sequence
  49. *
  50. * @param String seq - sequence
  51. * @param Int|String check - check digit
  52. * @return Array<Number> - array of barwidth
  53. */
  54. function generateSequence(seq, check) {
  55. seq = seq.substr(0,12) + '' + check;
  56. var first = seq.substr(0,1),
  57. group1 = seq.substr(1,6),
  58. group2 = seq.substr(7);
  59. var left = [],
  60. right = [],
  61. enc = ENCODE_GROUPS[parseInt(first)],
  62. dInt;
  63. for (var i = 0; i < 6; i++) {
  64. dInt = parseInt(group1[i]);
  65. left = left.concat( BARMAP[ enc[i] ][ dInt ] );
  66. }
  67. for (var i = 0; i < 6; i++) {
  68. dInt = parseInt(group2[i])
  69. right = right.concat( BARMAP[RIGHT][ dInt ] );
  70. }
  71. return [].concat(START, left, MIDDLE, right, END);
  72. }
  73. function createCode(options, callback) {
  74. if (!options.data) {
  75. return callback(new Error('No data given'), {});
  76. }
  77. if (!options.w || !options.h) {
  78. return callback(new Error('Width and Height must be non-zero'), {});
  79. }
  80. var check = getCheckDigit(options.data.substr(0,12));
  81. var sequence = generateSequence(options.data, check);
  82. new Barcode1D().setWidth(options.w)
  83. .setHeight(options.h)
  84. .setModuleWidth(MODULE_WIDTH)
  85. .draw(sequence, callback);
  86. }
  87. module.exports.generateSequence = generateSequence;
  88. module.exports.createCode = createCode;