JS使用jsBarcode生成条形码(一维码)简单实例
作者:最凶残的小海豹
JsBarcode是一个用JavaScript编写的条形码生成器,它支持多种条形码格式,可在浏览器和Node.js中使用,下面这篇文章主要给大家介绍了关于JS使用jsBarcode生成条形码(一维码)的相关资料,需要的朋友可以参考下
一、安装
script 引入
<script src="JsBarcode.all.min.js"></script>
地址:https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js
也可以进官网查看地址。
npm方式
安装:
npm install jsbarcode --save
页面引入:
import JsBarcode from "jsbarcode";
二、使用
HTML部分加入svg容器
<svg id="barcode"></svg>
JS 代码部分
JsBarcode("#barcode", "Hi world!");三、结果

参数设置(options)
| option | 默认值 | 类型 | 说明 |
|---|---|---|---|
| format | “auto” (CODE128) | String | 条形码的类型 |
| width | 2 | Number | 每个条条的宽度,注意这里不是指整个条形码的宽度 |
| height | 100 | Number | 整个条形码的宽度 |
| displayValue | true | Boolean | 是否显示条形码下面的文字 |
| fontOptions | “” | String | 设置条形码文本的粗体和斜体样式 bold / italic / bold italic |
| font | “monospace” | String | 设置条形码显示文本的字体 |
| textAlign | “center” | String | 条形码文本的水平对齐方式,和css中的类似: left / center / right |
| textPosition | “bottom” | String | 条形码文本的位置 bottom / top |
| textMargin | 2 | Number | 条形码文本 和 条形码之间的间隙大小 |
| fontSize | 20 | Number | 设置条形码文本的字体大小 |
| background | “#ffffff” | String (CSS color) | 整个条形码容器的背景颜色 |
| lineColor | “#000000” | String (CSS color) | 条形码和文本的颜色 |
| margin | 10 | Number | 整个条形码的外面距 |
| marginTop | undefined | Number | 整个条形码的上边距 |
| marginBottom | undefined | Number | 整个条形码的下边距 |
| marginLeft | undefined | Number | 整个条形码的左边距 |
| marginRight | undefined | Number | 整个条形码的右边距 |
| valid | function(valid){} | Function | 执行完条形码的一个回调函数,正确true 错误false |
options 使用方法
let options = {
fontSize: 12,
background: "#cccccc"
};
JsBarcode("#barcode", "Hi world!", options);
附:JsBarcode - 生成条形码并打印出来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/JsBarcode.all.min.js"></script>
<script src="js/jQuery.print.js"></script>
</head>
<body>
<input id="code" type="text" placeholder="请输入条形码"><button id="save">生成条形码</button>
<br>
<div id="PrintSection">
<img id="test">
</div>
<br>
<button id="print">打印</button>
<script>
$(function () {
// 生成条形码
$("#save").click(function () {
var requestNo = $("#code").val();
if (requestNo == "") {
return false;
} else {
$("#test").JsBarcode(requestNo);
}
})
// 打印条形码
$("#print").click(function () {
$("#PrintSection").print({
globalStyles: true,
mediaPrint: false,
stylesheet: null,
noPrintSelector: ".btncontainer",
iframe: true,
append: null,
prepend: null,
manuallyCopyFormValues: true,
deferred: $.Deferred(),
timeout: 750,
title: null,
doctype: '<!doctype html>'
});
})
})
</script>
</body>
</html>
总结
到此这篇关于JS使用jsBarcode生成条形码(一维码)的文章就介绍到这了,更多相关jsBarcode生成条形码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
