用Canvas编写一个条形码面单,并支持下载存储为图片。
//生成条形码
var canvas1 = document.getElementById('barcode1');
JsBarcode(canvas1, res.data.barcode, {
format: "CODE128", // 指定条形码的格式
lineColor: "#000", // 条形码颜色
width: 3, // 条的宽度
height: 60, // 条形码的高度
displayValue: true, // 是否在条形码下方显示文本
textMargin: 5,
fontSize: 28
});
//生成字符串
var canvas2 = document.getElementById('barcode2');
var ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = "#fff";
ctx2.fillRect(0, 0, canvas2.width, canvas2.height);
ctx2.font = '24px Arial';
ctx2.fillStyle = "#000";
wrapText(ctx2, string1, 50,30, 500, 35);
wrapText(ctx2, string2, 50,120, 500, 35);
//合并成图片
var canvas3 = document.getElementById('barcode3');
var ctx3 = canvas3.getContext('2d');
ctx3.fillStyle = "#fff";
ctx3.fillRect(0, 0, 600, 400);
ctx3.drawImage(canvas1, 0, 0, canvas1.width, canvas1.height, (canvas3.width - canvas1.width) / 2, 20, canvas1.width, canvas1.height);
ctx3.drawImage(canvas2, 0, 0, canvas2.width, canvas2.height, 0, canvas1.height + 50, canvas2.width, canvas2.height);
//图片立即下载
canvas3.toBlob(function (blob) {
let a = document.createElement('a');
a.download = res.data.barcode + '.png';
a.href = window.URL.createObjectURL(blob);
a.click();
console.log(blob)
}, 'image/png');
在以上的代码中,string1和string2代表需要增加在条形码下面的字符串。
wrapText()函数是封装了一个支持添加文字的方法。
function wrapText(context, text, x, y, maxWidth, lineHeight) {
let totalWidth = context.measureText(text).width;
if(totalWidth >= maxWidth){
var line = '';
for(var n = 0; n < text.length; n++) {
var testLine = line + text[n];
var metrics = context.measureText(testLine);
var testWidth = parseInt(metrics.width);
if (parseInt(testWidth) > parseInt(maxWidth) && n > 0) {
context.fillText(line, x, y);
line = text[n];
y += lineHeight;
} else {
line = testLine;
}
}
context.fillText(line, x, y);
} else {
context.fillText(text, (600 - totalWidth) / 2, y);
}
}
下面补一下生成图片和PDF的代码
//转换PDF格式
let imgurl = canvas3.toDataURL('image/png');
let imgWidth = canvas3.width
let imgHeight = canvas3.height
let pdf = new jsPDF(imgWidth > imgHeight ? 'l' : 'p', 'pt', [imgWidth, imgHeight])
pdf.addImage(imgurl, 'PNG', 0, 0, imgWidth, imgHeight)
pdf.save('demo.pdf');
//设定面单大小
let doc = new jsPDF({
unit: "mm", // 单位,本示例为mm
width: 60,
height: 40,
format: "a4", // 页面大小
orientation: "landscape", // 页面方向,portrait: 纵向,landscape: 横向
putOnlyUsedFonts: true, // 只包含使用的字体
compress: true, // 压缩文档
precision: 16, // 浮点数的精度
});
//保存PNG格式
canvas3.toBlob(function (blob) {
let a = document.createElement('a');
a.download = res.data.barcode + '.png';
a.href = window.URL.createObjectURL(blob);
a.click();
}, 'image/png');
以上代码可以自行取用,不一一讲解。