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
      },
相关推荐
Wyc724092 分钟前
HTML:入门
前端·html
Sunny_lxm3 分钟前
自定义列甘特图,原生开发dhtmlxgantt根特图,根据数据生成只读根特图,页面展示html demo
前端·html·甘特图·dhtmlxgantt
熊猫钓鱼>_>1 小时前
建筑IT数字化突围:建筑设计企业的生存法则重塑
前端·javascript·easyui
GISer_Jing3 小时前
前端性能指标及优化策略——从加载、渲染和交互阶段分别解读详解并以Webpack+Vue项目为例进行解读
前端·javascript·vue
不知几秋3 小时前
数字取证-内存取证(volatility)
java·linux·前端
水银嘻嘻4 小时前
08 web 自动化之 PO 设计模式详解
前端·自动化
Zero1017136 小时前
【详解pnpm、npm、yarn区别】
前端·react.js·前端框架
&白帝&7 小时前
vue右键显示菜单
前端·javascript·vue.js
Wannaer7 小时前
从 Vue3 回望 Vue2:事件总线的前世今生
前端·javascript·vue.js
羽球知道7 小时前
在Spark搭建YARN
前端·javascript·ajax