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
      },
相关推荐
默默学前端21 分钟前
ES6模板语法与字符串处理详解
前端·ecmascript·es6
lxh011330 分钟前
记忆函数 II 题解
前端·javascript
我不吃饼干37 分钟前
TypeScript 类型体操练习笔记(三)
前端·typescript
华仔啊40 分钟前
除了防抖和节流,还有哪些 JS 性能优化手段?
前端·javascript·vue.js
CHU7290351 小时前
随时随地学新知——线上网课教学小程序前端功能详解
前端·小程序
清粥油条可乐炸鸡1 小时前
motion入门教程
前端·css·react.js
这是个栗子1 小时前
【Vue3项目】电商前台项目(四)
前端·vue.js·pinia·表单校验·面包屑导航
前端Hardy1 小时前
Electrobun 正式登场:仅 12MB,JS 桌面开发迎来轻量化新方案!
前端·javascript·electron
树上有只程序猿1 小时前
新世界的入场券,不再只发给程序员
前端·人工智能
confiself1 小时前
deer-flow前端分析
前端