第一步 安装JsBarcode包并在页面中引入使用
1.1利用npm下载JsBarcode包
npm i jsbarcode
1.2条形码生成的容器
<canvas id="canvas"></canvas>
<img id="barcode"/>
<svg id="barcode"></svg>
//这三个容器都可以使用 我自己的项目中使用的<svg id="barcode"></svg>
1.3安装成功后引入页面使用
import JsBarcode from 'jsbarcode'
1.4我们要生成条形码的话直接使用
const options = {
text: '12313',
displayValue: true,
fontSize: 12,
height: 60
}
// text 的数据是生成条形码后条形码下面可显示的文字
// displayValue: true, 是否在条形码下面显示文字
// fontSize 设置条形码文本的字体大小
// height 整个条形码的宽度
JsBarcode('#barcode', '123456789', options)
// 这样我们的条形码就生成了
其中 下面那个笔记本文字是我后期添加进去的 具体的作法可以参考我下面写的内容
第二步 利用window.print()打印条形码
由于window.print()打印是将整个页面打印 所以想打印指定区域的内容 我们可以新开一个页面并将条形码放进去 打印新页面 我们就可以实现打印指定内容了,具体做法如下
2.1 获取到条形码的标签信息 然后添加到新页面打印
// 这段是我往条形码下 多增加文字笔记的 写法 不需要的可以去掉 start----
const svg = document.querySelector('.barcodeBox svg')
const text = document.createElementNS(
'http://www.w3.org/2000/svg',
'text'
)
text.textContent = '笔记本'
text.setAttribute('x', '50%')
text.setAttribute('y', '100')
text.setAttribute('style', 'font: 14px monospace')
text.setAttribute('text-anchor', 'middle')
svg.appendChild(text)
svg.style.height = '120px'
// end----
const str = document.querySelector('.barcodeBox').innerHTML
// 打开新的页面 并且宽度500 高度700, 不需要的可以不用设置
const printWindow = window.open('', '_blank', 'height=500,width=700')
// 写入条形码标签
printWindow.document.write(`
<html>
<head>
<title>打印条形码</title>
</head>
<body>
${str}
</body>
</html>
`)
printWindow.document.close()
printWindow.print()
这样 我们就成功的打印出来我们指定的条形码内容了