jsbarcode 添加 Code93 条码

分类:JavaScript     发布时间:2024-03-12     最后更新:2024-04-15     浏览数:295
由于 jsbarcode 不支持 Code93 条码,所以只能自己动手,参考了另外的仓库实现了这个需求。

由于 jsbarcode 不支持 Code93 条码,所以只能自己动手。

之前有想过用 bwip-js 替换 jsbarcode,但由于需求要支持更改条码内文字的字体,bwip-js 虽然也能修改字体,但是还要加载字体文件,这个方案需要修改的文件太多,也怕引入其它 bug,最终没有采取这个方案。

首先,需要了解一下 Code 93

Code 93

1982 年 Intermec 公司设计;主要被加拿大邮政使用。参考

允许的字符

0-9A-Z-.$/+%空格

结构

实战

1 克隆 github 仓库

git clone https://github.com/lindell/JsBarcode.git

2 添加 Code93 代码,参考Code 93

src/barcodes 下新建 CODE93 目录,新建 index.js 文件

// index.js
// Encoding documentation:
// https://en.wikipedia.org/wiki/Code_93#Encoding

import Barcode from "../Barcode.js";

const encoding = [
  "100010100",
  ...
];

class CODE93 extends Barcode {
  constructor(data, options) {
    data = data.toUpperCase();

    super(data, options);
  }

  encode() {
    const data = this.data;
    const table = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%____*"; // _ => ($), (%), (/) et (+)
    const dataToEncode = data.toUpperCase();
    const dataToEncodeLength = dataToEncode.length;
    let digit = "";

    // start :  *
    digit += encoding[47];

    // digits
    for (let i = 0; i < dataToEncodeLength; i += 1) {
      digit += encoding[table.indexOf(dataToEncode.charAt(i))];
    }

    // checksum
    let weightC = 0;
    let weightSumC = 0;
    let weightK = 1; // start at 1 because the right-most character is 'C' checksum
    let weightSumK = 0;

    for (let i = dataToEncodeLength - 1; i >= 0; i -= 1) {
      weightC = weightC === 20 ? 1 : weightC + 1;
      weightK = weightK === 15 ? 1 : weightK + 1;

      const index = table.indexOf(dataToEncode.charAt(i));

      weightSumC += weightC * index;
      weightSumK += weightK * index;
    }

    const c = weightSumC % 47;
    weightSumK += c;
    const k = weightSumK % 47;

    digit += encoding[c];
    digit += encoding[k];

    // stop : *
    digit += encoding[47];

    // terminaison bar
    digit += "1";

    const encodedData = {
      data: digit,
      text: dataToEncode,
    };

    return encodedData;
  }

  valid() {
    return /^[0-9a-zA-Z-. $/+%]+$/.test(this.data);
  }
}

export { CODE93 };

3 编译打包

jsbarcode 仓库根目录执行 npm run build

4 本地调试

  1. jsbarcode 仓库根目录执行 npm link
  2. 在使用 jsbarcode 的仓库执行 npm link jsbarcode
  3. 使用
    JsBarcode("#barcode", "1234", {
    format: "CODE93",
    width: 4,
    height: 40,
    displayValue: false,
    });
  4. 显示结果

参考

维基百科 Code 93

Code 93

上一篇: Windows 11 搭建 Rust USB 开发环境之 MSVC 版 下一篇: 没有了