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

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
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);
...
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");
System.out.println(s);
Posted on StackOverflow on Nov 21, 2013 by user3017202

There are no Chunks in iText 7, we now use Text instances as atomic parts of Paragraphs. I've made an example based on your code (HyphenationExample); the word "Leistungsscheinziffer" is hyphenated in the resulting PDF: hyphenation_table.pdf.

Normally hyphenation is set on the Text level:

Text text = new Text("Leistungsscheinziffer")
        .setHyphenation(new HyphenationConfig("de", "DE", 2, 2));
table.addCell(new Cell().add(new Paragraph(text)));

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

Paragraph paragraph = new Paragraph()
        .setHyphenation(new HyphenationConfig("de", "DE", 2, 2))
        .add(new Text("Leistungsscheinziffer"));
table.addCell(new Cell().add(paragraph));

Click this link if you want to see how to answer this question in iText 5.



Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now