How to change the spacing between words and characters?
I don't want extra space between the characters (see figure 1). I prefer space between words as shown in figure 2.
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
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
document.open();
// step 4
writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
Paragraph paragraph = new Paragraph();
paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
paragraph.setIndentationLeft(20);
paragraph.setIndentationRight(20);
paragraph.add("HelloWorld HelloWorld HelloWorld HelloWorld HelloWorld"+
"HelloWorld HelloWorldHelloWorldHelloWorldHelloWorld"+
"HelloWorld HelloWorld HelloWorld HelloWorldHelloWorldHelloWorld");
document.add(paragraph);
// step 5
document.close();
}
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.