You need to enable JavaScript to run this app. iText7中不同样式Text组成段落的正确连字符功能实现问题
优惠活动
大模型
产品
解决方案
定价
更多

iText7中不同样式Text组成段落的正确连字符功能实现问题

iText 7单字符独立Text场景下连字功能实现方案

失效原因

iText 7的连字逻辑默认以Text对象作为最小文本单元识别单词边界,你将每个字符都封装为独立Text节点后,布局引擎会把每个字符判定为独立单词,无法识别完整单词结构,因此连字规则不会触发。

解决方案

可以通过预计算连字断点+插入软连字符的方式实现需求,无需修改原有单字符样式设置逻辑,代码改动如下:

主逻辑代码

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);

PdfFont helveticaFont = PdfFontFactory.createFont(StandardFonts.HELVETICA);
PdfFont helveticaBoldFont = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);

Paragraph p = new Paragraph();
String s = "all text is written in red, except the letters b and g; they are written in blue and green.";

// 初始化连字器,预计算断字点
Hyphenator hyphenator = new Hyphenator("en", "US", 2, 2);
// 拆分原始文本,保留空格分割符
String[] textFragments = s.split("(?<=\\s)|(?=\\s)");

for (String fragment : textFragments) {
    // 空白字符直接添加
    if (fragment.isBlank()) {
        p.add(new Text(fragment)
                .setFontColor(ColorConstants.RED)
                .setFont(helveticaFont)
                .setFontSize(12));
        continue;
    }
    // 计算当前单词的所有合法断字点
    Hyphenation hyphenation = hyphenator.hyphenate(fragment);
    int[] breakPoints = hyphenation != null ? hyphenation.getHyphenationPoints() : new int[0];
    int breakPointIdx = 0;

    // 遍历字符创建单字符Text节点
    for (int i = 0; i < fragment.length(); i++) {
        char currentChar = fragment.charAt(i);
        p.add(returnCorrectColor(currentChar, helveticaFont, helveticaBoldFont));
        // 当前位置为断字点时插入软连字符
        if (breakPointIdx < breakPoints.length && (i + 1) == breakPoints[breakPointIdx]) {
            Text softHyphen = new Text("\u00ad")
                    .setFontColor(ColorConstants.RED)
                    .setFont(helveticaFont)
                    .setFontSize(12);
            // 标记为辅助元素,不影响内容语义
            softHyphen.getAccessibilityProperties().setRole(StandardRoles.ARTIFACT);
            p.add(softHyphen);
            breakPointIdx++;
        }
    }
}

p.setHyphenation(new HyphenationConfig("en", "US", 2, 2));
doc.add(p);
doc.close();

原有辅助方法无需修改

private static Text returnCorrectColor(char letter, PdfFont helveticaFont, PdfFont helveticaBoldFont) {
    if (letter == 'b') {
        return new Text("b")
                .setFontColor(ColorConstants.BLUE)
                .setFont(helveticaBoldFont)
                .setFontSize(15);
    
    } else {
        return new Text(String.valueOf(letter))
                .setFontColor(ColorConstants.RED)
                .setFont(helveticaFont)
                .setFontSize(12);
    }
}

说明

  • 软连字符\u00ad是标准不可见控制字符,仅在当前位置发生断行时才会显示为连字符,未断行时自动隐藏,符合连字功能的表现要求
  • 如果需要软连字符的样式和前后字符对齐,可以根据相邻字符的属性动态调整软连字符的样式即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 07:36:07