微信小程序-芝柯打印机CPCL文本指令不能自动换行问题

702 阅读1分钟

用js进行处理换行问题,处理完成后拼接打印指令让打印机去打印。 问了chatGpt得到的答案,手动截取字符串进行换行,成功应用在标签打印上面。

/**
 * 处理字符串自动换行问题。超过 intLenMax 就进行换行。
 * @param {string} strOldText 原字符串
 * @param {number} intLenMax 最长字符宽度
 * @returns {string[]}
 */
function automaticLine(strOldText, intLenMax) {
    let chunks = [];
    let currentLine = '';
    let currentWidth = 0;

    // 遍历原字符串的每个字符
    for (let i = 0; i < strOldText.length; i++) {
        let char = strOldText[i];
        let charWidth = char.charCodeAt(0) > 255 ? 2 : 1; // 判断字符宽度,中文字符宽度为2,英文字符宽度为1

        // 如果当前字符加上当前行已有字符宽度超过最大字符宽度,需要另起一行
        if (currentWidth + charWidth > intLenMax) {
            chunks.push(currentLine); // 将当前行添加到结果中
            currentLine = ''; // 重置当前行
            currentWidth = 0; // 重置当前字符宽度
        }

        currentLine += char;
        currentWidth += charWidth;
    }

    // 添加最后一行
    chunks.push(currentLine);

    return chunks;
}

// 示例
const strOldText = "这是一个包含中文和English的示例字符串,测试automaticLine函数是否能够正确处理中英文混合的情况。";
const intLenMax = 16;

const result = automaticLine(strOldText, intLenMax);
result.forEach(line => {
    console.log(line);
});