printTools.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // 获取文本字节总数
  2. export const getBytesCount = function(str){
  3. var bytesCount = 0;
  4. if (str != null) {
  5. for (var i = 0; i < str.length; i++) {
  6. var c = str.charAt(i);
  7. if (c.match(/[^\x00-\xff]/ig) != null) //全角
  8. {
  9. bytesCount += 2;
  10. } else {
  11. bytesCount += 1;
  12. }
  13. }
  14. }
  15. return bytesCount;
  16. }
  17. // JS 包含中文的字符串按固定长度拆分换行算法
  18. export const getTextRows = function(str,iPageSize){
  19. var strArray = [];
  20. var tempStr = "";
  21. var iTotalLength = getBytesCount(str);
  22. for (var i = 0; i < str.length; i++) {
  23. var iCount = getBytesCount(str[i]);
  24. var iCountTemp = getBytesCount(tempStr);
  25. //iCountTemp + iCount >= iPageSize 这里可能出现两种情况:
  26. //长度等于 iPageSize 或 等于 iPageSize + 1(最后一个为中文字符就等于 9 + 2 情况)
  27. if (iCountTemp + iCount >= iPageSize) {
  28. tempStr += str[i];
  29. strArray.push(tempStr);
  30. tempStr = "";
  31. } else {
  32. tempStr += str[i];
  33. }
  34. }
  35. // //最后一次尾巴
  36. if (tempStr.length > 0){
  37. strArray.push(tempStr)
  38. }
  39. return strArray
  40. }
  41. // 格式化打印文本
  42. export const textFormat = function(command,text,maxFontNums,left,top,lightHeight,align,fontSize){
  43. let rowTop = top
  44. const textArr = getTextRows(text.replace(/\s+/g, ' '),maxFontNums*2)
  45. const rows = textArr.length
  46. for(let i=0;i<rows;i++){
  47. if(align=="center"){
  48. const ltxt = textArr[i]
  49. const ltlen = ltxt.replace(/[^x00-xFF]/g,'**').length/2
  50. command.setText(left+((maxFontNums-ltlen)/2)*lightHeight, rowTop, "TSS24.BF2", fontSize, fontSize, ltxt)
  51. }
  52. else{
  53. command.setText(left, rowTop, "TSS24.BF2", fontSize, fontSize, textArr[i])
  54. }
  55. rowTop = rowTop+lightHeight
  56. }
  57. return rowTop
  58. }