Skip to main content
Skip table of contents

How to hyphenate text?

I generate an PDF file with iText in Java. My table columns have fixed widths. Text that 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
My code where I use hyphenation:

final PdfPTable table = new PdfPTable(sumCols);
final Phrase result = new Phrase(text, font);
result.setHyphenation(new HyphenationAuto("de", "DE", 2,2));
final PdfPCell cell = new PdfPCell(table.getDefaultCell());
Hyphenation 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");
Posted on StackOverflow on Nov 21, 2013 by user3017202

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.

Note: for this example to work, you need to add the itext-hyph-xml.jar to your CLASSPATH. This jar contains the hyphenation rules for a wide array of languages.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.