Generate Code 128 Barcode With Javascript
Generates a Code 128 Bar Code https://dev.to/saulodias/generating-valid-code-128-barcodes-with-javascript-5ana
by dias26
HTML
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Libre+Barcode+128">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Libre+Barcode+128+Text">
<input type="checkbox" id="withtext" name="Show Barcode With Text" checked>
<label for="withtext">Show Barcode With Text</label>
<br /> <br />
<div class="barcode" data-barcode="https://dev.to/saulodias"></div>
<br />
This code contains only digits, and can have a shorter barcode when using Set C
<div class="barcode" data-barcode="012345678999"></div>
<br />
Same data as the barcode above but with a shorter barcode.
<div class="barcode" data-barcode="012345678999" data-set="C"></div>
<br />
<a href="https://jsfiddle.net/dias26/ktn2hz1d/" target="_blank">Bar Code With Dynamic Optimization</a>
CSS
.barcode {
font-family: "Libre Barcode 128", "Courier New", Courier, monospace;
font-weight: normal;
font-size: 52px;
white-space: nowrap;
}
.with-text {
font-family: "Libre Barcode 128 Text";
}
JavaScript
const checkbox = document.getElementById('withtext')
function toSetC(text) {
return text.match(/\d{2}/g).map((ascii, index) => {
var codeC = Number(ascii);
var charCode = codeC > 94 ? codeC + 100 : codeC + 32;
return String.fromCharCode(charCode)
}).join('');
}
function checkSum128(data, startCode) {
var sum = startCode;
for (var i = 0; i < data.length; i++) {
var code = data.charCodeAt(i);
var value = code > 199 ? code - 100 : code - 32;
sum += (i + 1) * (value);
}
var checksum = (sum % 103) + 32;
if (checksum > 126) checksum = checksum + 68 ;
return String.fromCharCode(checksum);
}
function encodeToCode128(text, codeABC = "B") {
var startCode = String.fromCharCode(codeABC.toUpperCase().charCodeAt() + 138);
var stop = String.fromCharCode(206);
text = codeABC == 'C' && toSetC(text) || text;
var check = checkSum128(text, startCode.charCodeAt(0) - 100);
text = text.replaceAll(" ", String.fromCharCode(194));
return startCode + text + check + stop;
}
function renderBarcodes(withText = true) {
var barcodeElements = document.querySelectorAll(".barcode");
var codes = [];
barcodeElements.forEach((e) => {
var code = e.attributes["data-barcode"]?.value;
if (!code) return;
var set = e.attributes["data-set"]?.value;
e.innerHTML = encodeToCode128(code, set);
e.classList.toggle('with-text', withText)
});
}
renderBarcodes();
checkbox.addEventListener('change', (event) => {
renderBarcodes(event.currentTarget.checked)
});