How to hyphenate text?

只谈情不闲聊 提交于 2019-12-12 12:24:30

问题


I generate an PDF file with iText in Java. My table columns have fixed widths and text, which is too long for one line is wrapped in the cell. But hyphenation is not used. The word "Leistungsscheinziffer" is shown as: Leistungssc //Break here heinziffer

My code where I use hyphenation:

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);
...

Hyphen is activated and the following test results "Lei-stungs-schein-zif-fer "

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

Is there anything I forgot to set to the table that hyphen is working there? Thanks for your help. If you need more information about my code, I will tell you.


回答1:


First a remark that is irrelevant to the problem: you create a PdfPCell object, but you don't use it. You add the phrase to the table instead of using the cell object.

Now for your question: normally hyphenation is set on the Chunk level:

Chunk chunk = new Chunk("Leistungsscheinziffer");
chunk.setHyphenation(new HyphenationAuto("de", "DE", 2,2));
table.addCell(new Phrase(chunk));

If you want to set the hyphenation on the Phrase level, you can do so, but this will only work for all subsequent Chunks that are added. It won't work for the content that is already stored inside the Phrase. In other words: you need to create an empty Phrase object and then add one or more Chunk objects:

Phrase phrase = new Phrase();
phrase.setHyphenation(new HyphenationAuto("de", "DE", 2,2));
phrase.add(new Chunk("Leistungsscheinziffer"));

I've made an example based on your code (HyphenationExample); the word "Leistungsscheinziffer" is hyphenated in the resulting PDF: hyphenation_table.pdf.



来源:https://stackoverflow.com/questions/20119709/how-to-hyphenate-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!