You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jsPDF设置非零字符间距后文本居中对齐失效的问题求助

jsPDF设置非零字符间距后文本居中对齐失效的问题求助

各位好,我在项目里用jsPDF做导出功能,大部分场景都正常,但碰到个挺头疼的问题:一旦把默认字符间距改成非零值,文本居中对齐就完全乱套了,要是间距设得大一点,文本甚至会直接溢出页面右边缘。

我想请教下,是不是有什么我没留意到的方法,能让setCharSpace和对齐属性正常配合工作?如果没有现成的解决方案,有没有办法自己写个计算逻辑,把字符间距带来的影响抵消掉呀?

我的代码如下:

const lineHeight = 1.35;
const doc = new jsPDF({
    unit: "mm",
    lineHeight: lineHeight,
});

const margin = 24;
const fontSize = 10;
const pageWidth = Math.round(doc.internal.pageSize.width);
const pageHeight = Math.round(doc.internal.pageSize.height);
const maxLineWidth = pageWidth - 2 * margin;
const charSpace = 0.3; // Default = 0
const para = 'This is my repeating text. '.repeat(100);

let textLines = doc
    .setFont("Helvetica", "normal") //
    .setFontSize(fontSize)
    .setCharSpace(charSpace)
    .splitTextToSize(para, maxLineWidth);

备注:内容来源于stack exchange,提问作者denkom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 09:09:29