2015-06-16 48 views
2

我想將文本對齊設置爲對齊,但我不希望iText在字符之間添加任何額外空間(請參見圖1)。我更喜歡詞之間空間,如圖2所示。如何更改單詞和字符之間的間距?

image

有了這個代碼,我得到如圖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所示?

回答

0

請大家看看SpaceCharRatioExample找出如何創建一個PDF,看起來像space_char_ratio.pdf

enter image description here

當你證明一個段落,iText的將添加單詞之間之間的額外空間字符。默認情況下,iText將在單詞之間增加2.5倍的空間比字符之間的空間。

您可以更改此默認就像使用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的不添加字符之間的任何空間,只有一行字之間:PdfWriter.NO_SPACE_CHAR_RATIO。那麼,事實上,我們告訴iText在單詞之間增加10,000,000多空間,而不是在角色之間,這幾乎是一回事。

+0

這是一個恥辱,沒有人似乎在設計iText時諮詢過印刷工。印刷工會想分別控制它們。 – EJP

+0

@EJP那麼你會有兩個值,但是這兩個值不會相互獨立。你總是能夠從另一箇中獲得一個價值,因此一個價值就足夠了,不是嗎? –

相關問題