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
      },
相关推荐
飞天狗1117 小时前
零基础JavaWeb入门——第2课:让网页“活”起来 —— JSP是什么?
java·开发语言·前端·后端·web
回忆2012初秋7 小时前
【Nginx】优雅地走进高性能 Web 服务器世界(1)
服务器·前端·nginx
kyriewen7 小时前
Claude Code Token 烧太快?实测 5 招,把月费从 250 美金砍到 50 美金
前端·ai编程·claude
weixin_394758038 小时前
CRMEB Pro 商品字段二开:为什么加一个字段会牵动 SKU、缓存和前端展示?
前端·缓存
IT_陈寒8 小时前
Python的pickle让我半夜加班,这破玩意儿太坑了
前端·人工智能·后端
qq_422152579 小时前
图片格式转换工具怎么选?JPEG、PNG、WebP、AVIF 格式对比与在线转换方案实测
前端
xiaofeichaichai9 小时前
ES 新特性九年速览:从 ES2016 到 ES2024
前端·javascript·es6
2401_834636999 小时前
Keepalived + LVS (DR) + Nginx + NFS 高可用 Web 集群部署实战手册
前端·nginx·lvs
和你看星星9 小时前
我把代码排查流程做成了一个 Codex Skill
前端