C-Lodop打印文字超长自动缩小(文字按固定宽度缩放、js计算文本宽度)

javascript 复制代码
LODOP=getLodop();
var str = '<svg><text x="0mm" y="5mm" textLength="300px" lengthAdjust="spacingAndGlyphs" style="width: 300px;height:50px word-break: break-all;font-size:25px">测试文本测试文本测试文本测试文本测试文本11</text></svg>';  
LODOP.PRINT_INITA(10,10,762,533,"打印控件功能演示_Lodop功能");
LODOP.SET_PRINT_STYLE("FontColor","#0000FF");
LODOP.ADD_PRINT_IMAGE(0,0,300,50,str);
LODOP.PRINT_DESIGN();

以上代码固定宽度300px,文字短了会拉长,长了会压缩。如果短的时候不想让他拉长,那么可以先计算一下文本的宽度,如果宽度长于300,那textLength就设置300,如果小于300,那textLength就设置为这个文本宽度。

javascript 复制代码
textSize(text) {
        const span = document.createElement('span')
        const result = {}
        result.width = span.offsetWidth
        result.height = span.offsetHeight
        span.style.visibility = 'hidden'
        span.style.fontSize = '11px'
        span.style.fontFamily = 'Avenir, Helvetica, Arial, sans-serif'
        span.style.display = 'inline-block'
        span.style.whiteSpace = 'nowrap'
        document.body.appendChild(span)
        if (typeof span.textContent != 'undefined') {
          span.textContent = text
        } else {
          span.innerText = text
        }
        result.width =
          parseFloat(window.getComputedStyle(span).width) - result.width
        // result.height = parseFloat(window.getComputedStyle(span).height) - result.height;
        return result.width
      },
相关推荐
Carry34510 分钟前
不清楚的 .gitignore
前端·git
张鑫旭17 分钟前
AI时代2025年下半年学的这些Web前端特性有没有用?
前端·ai编程
pinkQQx18 分钟前
H5唤醒APP技术方案入门级介绍
前端
Lefan21 分钟前
UniApp 隐私合规神器!一键搞定应用市场审核难题 - lf-auth 隐私合规助手
前端
Null15521 分钟前
浏览器唤起桌面端应用(进阶篇)
前端·浏览器
Jing_Rainbow24 分钟前
【Vue-2/Lesson62(2025-12-10)】模块化与 Node.js HTTP 服务器开发详解🧩
前端·vue.js·node.js
风度前端1 小时前
用了都说好的 uniapp 路由框架
前端
冴羽1 小时前
2026 年 Web 前端开发的 8 个趋势!
前端·javascript·vue.js
码银1 小时前
ruoyi的前端(vue)新增的时候给字典设置默认值 但不能正常
前端
fengbizhe2 小时前
bootstrapTable转DataTables,并给有着tfoot的DataTables加滚动条
javascript·bootstrap