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
      },
相关推荐
令狐少侠20113 分钟前
python后端程序部署到服务器 Ubuntu并配合 Vue 前端页面运行
服务器·前端·python
前端Hardy7 分钟前
第8课:JavaScript实战-简易计算器——入门阶段成果验收
前端·javascript
前端Hardy8 分钟前
第7课:JavaScript事件处理——JS的“感官系统”
前端·javascript
独立开阀者_FwtCoder10 分钟前
Trae + 设计 MCP :实现 UI 到网页自动化
前端·javascript·人工智能
拖孩16 分钟前
【Nova UI】十二、打造组件库之按钮组件(上):迈向功能构建的关键一步
前端·javascript·vue.js
独立开阀者_FwtCoder18 分钟前
用 pnpm + workspace + changesets 打造monorepo工程,【前端er必看!】
前端·javascript·面试
想回家的一天32 分钟前
雪花算法生成int64,在前端js的精度问题
开发语言·前端·javascript
.又是新的一天.34 分钟前
03_JavaScript
开发语言·javascript·ecmascript
yinzhiqing1 小时前
ubuntu24设置拼音输入法,解决chrome不能输入中文
前端·数据库·chrome
知识分享小能手1 小时前
JavaScript学习教程,从入门到精通,XMLHttpRequest 与 Ajax 请求详解(25)
开发语言·javascript·学习·ajax·前端框架·css3·html5