Text hyphenation

This is a code example of iText PDF, discover more.

5th November 2015
admin-marketing

Switch code for this example

HyphenationExample.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to:
  3.  * http://stackoverflow.com/questions/20119709/itext-hyphen-in-table-cell
  4.  * 
  5.  * We create a table with and we add a word that needs to be hyphenated.
  6.  */
  7. package sandbox.tables;
  8.  
  9. import com.itextpdf.text.Chunk;
  10. import com.itextpdf.text.Document;
  11. import com.itextpdf.text.DocumentException;
  12. import com.itextpdf.text.PageSize;
  13. import com.itextpdf.text.Phrase;
  14. import com.itextpdf.text.pdf.HyphenationAuto;
  15. import com.itextpdf.text.pdf.PdfPTable;
  16. import com.itextpdf.text.pdf.PdfWriter;
  17. import com.itextpdf.text.pdf.hyphenation.Hyphenation;
  18. import com.itextpdf.text.pdf.hyphenation.Hyphenator;
  19.  
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23.  
  24. import sandbox.WrapToTest;
  25.  
  26. @WrapToTest
  27. public class HyphenationExample {
  28.  
  29.     public static final String DEST = "results/tables/hyphenation_table.pdf";
  30.  
  31.     public static void main(String[] args) throws IOException,
  32.             DocumentException {
  33.         File file = new File(DEST);
  34.         file.getParentFile().mkdirs();
  35.         new HyphenationExample().createPdf(DEST);
  36.     }
  37.  
  38.     public void createPdf(String dest) throws IOException, DocumentException {
  39.         Hyphenator h = new Hyphenator("de", "DE", 2, 2);
  40.         Hyphenation s = h.hyphenate("Leistungsscheinziffer"); 
  41.         System.out.println(s);
  42.  
  43.         Document document = new Document(PageSize.A4, 0, 0, 0, 0);
  44.         PdfWriter.getInstance(document, new FileOutputStream(dest));
  45.         document.open();
  46.  
  47.         PdfPTable table = new PdfPTable(1);
  48.         table.setWidthPercentage(10);
  49.         Chunk chunk = new Chunk("Leistungsscheinziffer");
  50.         chunk.setHyphenation(new HyphenationAuto("de", "DE", 2,2));
  51.         table.addCell(new Phrase(chunk));
  52.         Phrase phrase = new Phrase();
  53.         phrase.setHyphenation(new HyphenationAuto("de", "DE", 2,2));
  54.         phrase.add(new Chunk("Leistungsscheinziffer"));
  55.         table.addCell(phrase);
  56.         document.add(table);
  57.         document.close();
  58.     }
  59. }
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