先上效果图吧。
转行空了一格,后来又改进了点,图就不贴了。
聚宝盆记账易小程序版要加蓝牙打印,别的倒简单,就是这个小票格式打来不好看,网上查了下只有java版的,我来搞个javascipt版吧。
关键的几个函数贴上来。
//按英文长度分割成数组
function mystrSubString (str,len,strtab=[]){
let N = getBytesLength(str);
if(N > len){
let mystr = formatStringLen(str,len);
str = str.replace(mystr,""); //替换掉已有的,相当于删除已截取的
strtab.push(mystr);
return mystrSubString(str,len,strtab);
}else{
let mystr = formatStringLen(str,len);
strtab.push(mystr);
return strtab;
}
}
function getBytesLength(val) {
var str = new String(val);
var bytesCount = 0;
for (var i = 0, n = str.length; i < n; i++) {
var c = str.charCodeAt(i);
if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
bytesCount += 1;
} else {
bytesCount += 2;
}
}
return bytesCount;
}
//4列打印,销售单模版(名称,数量,单价,合计,字符最大长度,名称长度,数量长度,单价长度,合计长度)
function printFourData(goods_name,num, goods_price, total_price,maxLen = 46) {
let sb = '';
let name = "";
let leftLength = (maxLen==32) ? 12 : 24 ; //商品名称的宽窄
maxLen = maxLen - leftLength;
let leftText = num;
let centerText = goods_price;
let rightText = total_price;
let leftTextLength = getBytesLength(leftText);
let centerTextLength = getBytesLength(centerText);
let rightTextLength = getBytesLength(rightText);
let centspacelenght = maxLen - leftTextLength - rightTextLength;
let spaceLeft = Math.floor((centspacelenght-centerTextLength)/2); //空格不整除时,左边少一个,右边加一个,好对齐
let spaceRight = Math.ceil((centspacelenght-centerTextLength)/2);
//隔单位的空格重调下
if(leftLength==22){
spaceLeft = (spaceLeft > 8) ? 8 : spaceLeft
}else{
spaceLeft = (spaceLeft > 6) ? 6 : spaceLeft
}
if(spaceRight <= 0){ //右边的空格缺了就往左边挤一下
spaceLeft = spaceLeft + spaceRight;
spaceRight = 1 ;
}
if(spaceLeft <=0){
leftLength = leftLength +spaceLeft ;
}
centerText = "".padEnd(spaceLeft) + centerText + "".padEnd(spaceRight);
sb = sb.concat(leftText,centerText,rightText,'\n') ;
//注意,这还只是取了右边的,如果左边超宽,则自动转行
let nameTextLength = getBytesLength(goods_name);
if(leftLength >= nameTextLength){
name = goods_name+"".padEnd(leftLength-nameTextLength);
sb = name + sb;
}else{
let stringtab = mystrSubString (goods_name,leftLength);
for (let index = 0; index < stringtab.length; index++) {
name = stringtab[index];
sb =(index==0)? (name + sb):(sb + name + '\n');
}
}
return sb.toString();
}
调试
let str = "笔记本电源IC2589";
console.log(printFourData("商品名称","数量","单价",'合计',46));
console.log(printFourData(str,'1条','4500.00','4500.00',46));
console.log(printFourData("商品名称","数量","单价",'合计',32));
console.log(printFourData(str,'1','5.00','5.00',32));
console.log(printFourData("笔记本",'1对','5.00','5.00',32));