Skip to main content
Skip table of contents

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.

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);
    document.open();
    Paragraph paragraph2 = new Paragraph();
    paragraph2.setAlignment(Element.ALIGN_JUSTIFIED);
    paragraph2.setFont(font1);
    paragraph2.setIndentationLeft(20);
    paragraph2.setIndentationRight(20);
    paragraph2.add("HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld"+
        "HelloWorld HelloWorldHelloWorldHelloWorldHelloWorld"+
        "HelloWorld HelloWorld HelloWorld HelloWorldHelloWorldHelloWorld");
    document.add(paragraph2);
    document.close();
}

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. You can change this default like using the setSpacingRatio() method:

public void manipulatePdf(String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);
    Paragraph p = new Paragraph().
            .setSpacingRatio(1)
            .setTextAlignment(TextAlignment.JUSTIFIED)
            .setMarginLeft(20)
            .setMarginRight(20)
            .add("HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld" +
                    "HelloWorld HelloWorldHelloWorldHelloWorldHelloWorld" +
                    "HelloWorld HelloWorld HelloWorld HelloWorldHelloWorldHelloWorld");
    doc.add(p);
    doc.close();
}

Click How to change the spacing between words and characters? if you want to see how to answer this question in iText 5.

JavaScript errors detected

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

If this problem persists, please contact our support.