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
      },
相关推荐
计算机魔术师3 小时前
1.4万亿没人接,OpenAI自己把价砍了1500亿
前端
非凡ghost3 小时前
Photo Supreme:专业高效的照片收藏管理专家
服务器·前端·人工智能·电脑·软件需求
zhangminghuan4 小时前
前端动态路由实现方案(Vue3 + VueRouter4)|后台权限路由实战
前端
一切皆是因缘际会4 小时前
大模型应用
前端·人工智能
SCandL1524 小时前
【无标题】
前端
你挚爱的强哥4 小时前
如何设置 Chrome 打开默认页面不要是360的主页https://hao.360.com/?src=lm&ls=n6205869099
前端·chrome·360首页劫持
总要学点什么4 小时前
第75篇:右键菜单控件——把一张会做事的菜单钉在鼠标落下的那点
前端·信息可视化·echarts·cesium·空间分析
计算机魔术师5 小时前
国办说AI要"缓"着上,但你公司可能已经全上完了
前端
IT_陈寒5 小时前
SpringBoot性能优化完全指南
前端·人工智能·后端
溪语流沙5 小时前
【每天一个CSS | Day33】聚焦即弹出的命令面板
前端·css·html5·组件·每日一练