如何改变单词和字符之间的间距?

How to change the spacing between words and characters?

我想将文本对齐设置为两端对齐,但我不希望 iText 在字符之间添加任何额外的 space(见图 1)。如图2所示,我更喜欢space之间的单词。

使用这段代码,我得到了图 1 所示的结果。

public static void main(String[] args) throws DocumentException, IOException {

    Document document = new Document();
    String path = System.getProperty("user.home") + "\Desktop";
    PdfWriter.getInstance(document,new FileOutputStream(path+"\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();
}

如何更改此代码以获得如图 2 所示的结果?

请看一下SpaceCharRatioExample to find out how to create a PDF that looks like space_char_ratio.pdf:

当您对齐段落时,iText 会在单词之间和字符之间添加额外的 space。默认情况下,iText 将在单词之间添加比字符之间多 2.5 倍的 space。

您可以像使用 setSpaceCharRatio() 方法一样更改此默认值:

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();
}

在这种情况下,我们告诉 iText 不要在字符之间添加任何 space,只在单词之间添加:PdfWriter.NO_SPACE_CHAR_RATIO。好吧,事实上我们告诉 iText 在单词之间添加的 space 是字符之间的 10,000,000 倍,这几乎是一回事。