EAN.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { SIDE_BIN, MIDDLE_BIN } from './constants';
  2. import encode from './encoder';
  3. import Barcode from '../Barcode';
  4. // Base class for EAN8 & EAN13
  5. class EAN extends Barcode {
  6. constructor(data, options) {
  7. super(data, options);
  8. // Make sure the font is not bigger than the space between the guard bars
  9. this.fontSize = !options.flat && options.fontSize > options.width * 10
  10. ? options.width * 10
  11. : options.fontSize;
  12. // Make the guard bars go down half the way of the text
  13. this.guardHeight = options.height + this.fontSize / 2 + options.textMargin;
  14. }
  15. encode() {
  16. return this.options.flat
  17. ? this.encodeFlat()
  18. : this.encodeGuarded();
  19. }
  20. leftText(from, to) {
  21. return this.text.substr(from, to);
  22. }
  23. leftEncode(data, structure) {
  24. return encode(data, structure);
  25. }
  26. rightText(from, to) {
  27. return this.text.substr(from, to);
  28. }
  29. rightEncode(data, structure) {
  30. return encode(data, structure);
  31. }
  32. encodeGuarded() {
  33. const textOptions = { fontSize: this.fontSize };
  34. const guardOptions = { height: this.guardHeight };
  35. return [
  36. { data: SIDE_BIN, options: guardOptions },
  37. { data: this.leftEncode(), text: this.leftText(), options: textOptions },
  38. { data: MIDDLE_BIN, options: guardOptions },
  39. { data: this.rightEncode(), text: this.rightText(), options: textOptions },
  40. { data: SIDE_BIN, options: guardOptions },
  41. ];
  42. }
  43. encodeFlat() {
  44. const data = [
  45. SIDE_BIN,
  46. this.leftEncode(),
  47. MIDDLE_BIN,
  48. this.rightEncode(),
  49. SIDE_BIN
  50. ];
  51. return {
  52. data: data.join(''),
  53. text: this.text
  54. };
  55. }
  56. }
  57. export default EAN;