1
|
|
|
// Encoding documentation: |
2
|
|
|
// https://en.wikipedia.org/wiki/International_Article_Number_(EAN)#Binary_encoding_of_data_digits_into_EAN-13_barcode |
3
|
|
|
|
4
|
|
|
import { EAN13_STRUCTURE } from './constants'; |
5
|
|
|
import EAN from './EAN'; |
6
|
|
|
|
7
|
|
|
// Calculate the checksum digit |
8
|
|
|
// https://en.wikipedia.org/wiki/International_Article_Number_(EAN)#Calculation_of_checksum_digit |
9
|
|
|
const checksum = (number) => { |
10
|
|
|
const res = number |
11
|
|
|
.substr(0, 12) |
12
|
|
|
.split('') |
13
|
|
|
.map((n) => +n) |
14
|
|
|
.reduce((sum, a, idx) => ( |
15
|
|
|
idx % 2 ? sum + a * 3 : sum + a |
16
|
|
|
), 0); |
17
|
|
|
|
18
|
|
|
return (10 - (res % 10)) % 10; |
19
|
|
|
}; |
20
|
|
|
|
21
|
|
|
class EAN13 extends EAN { |
22
|
|
|
|
23
|
|
|
constructor(data, options) { |
24
|
|
|
// Add checksum if it does not exist |
25
|
|
|
if (data.search(/^[0-9]{12}$/) !== -1) { |
26
|
|
|
data += checksum(data); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
super(data, options); |
30
|
|
|
|
31
|
|
|
// Adds a last character to the end of the barcode |
32
|
|
|
this.lastChar = options.lastChar; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
valid() { |
36
|
|
|
return ( |
37
|
|
|
this.data.search(/^[0-9]{13}$/) !== -1 && |
38
|
|
|
+this.data[12] === checksum(this.data) |
39
|
|
|
); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
leftText() { |
43
|
|
|
return super.leftText(1, 6); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
leftEncode() { |
47
|
|
|
const data = this.data.substr(1, 6); |
48
|
|
|
const structure = EAN13_STRUCTURE[this.data[0]]; |
49
|
|
|
return super.leftEncode(data, structure); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
rightText() { |
53
|
|
|
return super.rightText(7, 6); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
rightEncode() { |
57
|
|
|
const data = this.data.substr(7, 6); |
58
|
|
|
return super.rightEncode(data, 'RRRRRR'); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
// The "standard" way of printing EAN13 barcodes with guard bars |
62
|
|
|
encodeGuarded() { |
63
|
|
|
const data = super.encodeGuarded(); |
64
|
|
|
|
65
|
|
|
// Extend data with left digit & last character |
66
|
|
|
if (this.options.displayValue) { |
67
|
|
|
data.unshift({ |
68
|
|
|
data: '000000000000', |
69
|
|
|
text: this.text.substr(0, 1), |
70
|
|
|
options: { textAlign: 'left', fontSize: this.fontSize } |
71
|
|
|
}); |
72
|
|
|
|
73
|
|
|
if (this.options.lastChar) { |
74
|
|
|
data.push({ |
75
|
|
|
data: '00' |
76
|
|
|
}); |
77
|
|
|
data.push({ |
78
|
|
|
data: '00000', |
79
|
|
|
text: this.options.lastChar, |
80
|
|
|
options: { fontSize: this.fontSize } |
81
|
|
|
}); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return data; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
export default EAN13; |
91
|
|
|
|