Spacing between words and characters

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

5th November 2015
admin-marketing

Switch code for this example

SpaceCharRatioExample.java
  1. /*
  2.  * Example written by Bruno Lowagie in answer to:
  3.  * http://stackoverflow.com/questions/30869268/java-itext-alignment
  4.  */
  5. package sandbox.objects;
  6.  
  7. import com.itextpdf.text.Document;
  8. import com.itextpdf.text.DocumentException;
  9. import com.itextpdf.text.Element;
  10. import com.itextpdf.text.Paragraph;
  11. import com.itextpdf.text.pdf.PdfWriter;
  12.  
  13. import java.io.File;
  14. import java.io.FileOutputStream;
  15. import java.io.IOException;
  16. import sandbox.WrapToTest;
  17.  
  18. /**
  19.  * @author Bruno Lowagie (iText Software)
  20.  */
  21. @WrapToTest
  22. public class SpaceCharRatioExample {
  23.    
  24.     public static final String DEST = "results/objects/space_char_ratio.pdf";
  25.    
  26.     public static void main(String[] args) throws IOException, DocumentException {
  27.         File file = new File(DEST);
  28.         file.getParentFile().mkdirs();
  29.         new SpaceCharRatioExample().createPdf(DEST);
  30.     }
  31.    
  32.     public void createPdf(String dest) throws IOException, DocumentException {
  33.         // step 1
  34.         Document document = new Document();
  35.         // step 2
  36.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
  37.         // step 3
  38.         document.open();
  39.         // step 4
  40.         writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
  41.         Paragraph paragraph = new Paragraph();
  42.         paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
  43.         paragraph.setIndentationLeft(20);
  44.         paragraph.setIndentationRight(20);
  45.         paragraph.add("HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld"+
  46.             "HelloWorld HelloWorldHelloWorldHelloWorldHelloWorld"+
  47.             "HelloWorld HelloWorld HelloWorld HelloWorldHelloWorldHelloWorld");
  48.         document.add(paragraph);
  49.         // step 5
  50.         document.close();
  51.     }
  52. }
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