How to change the spacing between words and characters?

I want to set the text alignment to justified, but I don't want iText to add any extra space between the characters.

5th November 2015

I don't want extra space between the characters (see figure 1). I prefer space between words as shown in figure 2.

Different spacing when justifying text

With this code, I get the result shown in figure 1.


public static void main(String[] args) throws DocumentException, IOException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("abc.pdf"));
    BaseFont bf1 = BaseFont.createFont(
        BaseFont.TIMES_ROMAN, "iso-8859-9", BaseFont.EMBEDDED);
    Font font1 = new Font(bf1);;
    Paragraph paragraph2 = new Paragraph();
    paragraph2.add("HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld"+
        "HelloWorld HelloWorldHelloWorldHelloWorldHelloWorld"+
        "HelloWorld HelloWorld HelloWorld HelloWorldHelloWorldHelloWorld");

How can I change this code to get a result like in figure 2?

Posted on StackOverflow on Jun 16, 2015 by Osman Yilmaz

Please take a look at the SpaceCharRatioExample to find out how to create a PDF that looks like space_char_ratio.pdf:

Spacing between words

Spacing between words

When you justify a paragraph, iText will add extra space between the words and between the characters. By default, iText will add 2.5 times more space between words than between characters.

You can change this default like using the setSpaceCharRatio() method:

public void createPdf(String dest) throws IOException, DocumentException {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    // step 3;
    // step 4
    Paragraph paragraph = new Paragraph();
    paragraph.add("HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld"+
        "HelloWorld HelloWorldHelloWorldHelloWorldHelloWorld"+
        "HelloWorld HelloWorld HelloWorld HelloWorldHelloWorldHelloWorld");
    // step 5

In this case, we tell iText not to add any space between the characters, only between the words: PdfWriter.NO_SPACE_CHAR_RATIO. Well, as a matter of fact we tell iText to add 10,000,000 times more space between the words than between the characters, which is almost the same thing.


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