如何对文字进行连字?

use*_*202 4 java itext hyphen

我使用Java中的iText生成PDF文件。我的表格列具有固定的宽度和文本,对于单元格中的一行换行而言,这太长了。但是不使用连字符。单词“ Leistungsscheinziffer”显示为:Leistungssc //在此处断裂heinziffer

我使用连字符的代码:

final PdfPTable table = new PdfPTable(sumCols);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.getDefaultCell().setPadding(4f);
table.setWidths(widthsCols);
table.setWidthPercentage(100);
table.setSpacingBefore(0);
table.setSpacingAfter(5);

final Phrase result = new Phrase(text, font);
result.setHyphenation(new HyphenationAuto("de", "DE", 2,2));
final PdfPCell cell = new PdfPCell(table.getDefaultCell());
cell.setPhrase(result);
table.addCell(cell);
...
Run Code Online (Sandbox Code Playgroud)

连字符被激活,以下测试结果为“ Lei-stungs-schein-zif-fer”

Hyphenator h = new Hyphenator("de", "DE", 2, 2);
Hyphenation s = h.hyphenate("Leistungsscheinziffer"); 
System.out.println(s);
Run Code Online (Sandbox Code Playgroud)

我忘记设置连字符在该表上工作了吗?谢谢你的帮助。如果您需要有关我的代码的更多信息,我会告诉您。

Bru*_*gie 5

首先,与该问题无关的评论:创建PdfPCell对象,但不使用它。您将短语添加到表中而不是使用cell对象。

现在您的问题是:通常在Chunk级别上设置断字:

Chunk chunk = new Chunk("Leistungsscheinziffer");
chunk.setHyphenation(new HyphenationAuto("de", "DE", 2,2));
table.addCell(new Phrase(chunk));
Run Code Online (Sandbox Code Playgroud)

如果要在Phrase级别上设置连字符,可以这样做,但这仅适用于所有后续Chunk添加的。不适用于已存储在中的内容Phrase。换句话说:您需要创建一个空Phrase对象,然后添加一个或多个Chunk对象:

Phrase phrase = new Phrase();
phrase.setHyphenation(new HyphenationAuto("de", "DE", 2,2));
phrase.add(new Chunk("Leistungsscheinziffer"));
Run Code Online (Sandbox Code Playgroud)

我已经根据您的代码制作了一个示例(HyphenationExample); 单词“ Leistungsscheinziffer”在生成的PDF中带有连字符hyphenation_table.pdf