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

iText中单元格拼接字符串出现多余空格问题求助

解决iText中Cell文本出现多余空格的问题

问题原因

多余空格并非StringBuilder拼接导致,而是iText的默认文本处理逻辑:直接向Cell添加字符串时,iText会自动将其包装为Paragraph对象,而Paragraph会按单词边界规则(比如非字母数字字符与字母的分界)拆分文本,把星号序列和World识别为两个独立"单词",居中对齐时自动填充空格,最终出现多余空白。

解决方案

方法1:用Text对象包裹文本,避免自动分词

将拼接后的字符串用Text包装,让iText将整个文本视为一个整体,不会拆分:

String cellLine = new StringBuilder()  
    .append("*********")
    .append("World")
    .append("***********")
    .toString();

Text text = new Text(cellLine);
Paragraph paragraph = new Paragraph(text)
    .setBold()
    .setTextAlignment(TextAlignment.CENTER);

Cell cell1 = new Cell(1, 3)
    .add(paragraph);

table.addCell(cell1);

方法2:禁用Paragraph的分词功能

通过配置Paragraph的属性,禁止文本拆分和连字符处理:

String cellLine = new StringBuilder()  
    .append("*********")
    .append("World")
    .append("***********")
    .toString();

Paragraph paragraph = new Paragraph(cellLine)
    .setBold()
    .setTextAlignment(TextAlignment.CENTER)
    .setHyphenation(null) // 禁用连字符拆分
    .setKeepTogether(true); // 强制文本保持为整体

Cell cell1 = new Cell(1, 3)
    .add(paragraph);

table.addCell(cell1);

方法3:直接设置单元格文本(iText 7+)

部分iText版本支持直接通过setText()跳过Paragraph的自动处理:

String cellLine = new StringBuilder()  
    .append("*********")
    .append("World")
    .append("***********")
    .toString();

Cell cell1 = new Cell(1, 3)
    .setText(cellLine)
    .setTextAlignment(TextAlignment.CENTER)
    .setBold();

table.addCell(cell1);

效果验证

使用上述方法后,单元格文本会保持拼接后的原始格式,输出为:

*********World***********

(若需要调整为你期望的******************* World****************,直接修改StringBuilder中星号的数量即可,核心已解决多余空格问题)

内容的提问来源于stack exchange,提问作者Rajshekar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 07:00:59