Java如何使用iText短语类?

该com.itextpdf.text.Phrase代表在文本的短语Document对象。该Phrase对象知道如何在文本行之间增加间距。因此,如果我们在文档中添加一些短语,则在到达文档的右边缘时,它将从新行开始。对象的默认前导/行距Phrase是16。

package org.nhooo.example.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class PhraseDemo {
    public static void main(String[] args) {
        // 创建一个Document实例。
        Document document = new Document();
        try {
            // 使用PdfWriter将pdf文档写入文件
            // 并传递文档对象和FileOutputStream。
            PdfWriter.getInstance(document, new FileOutputStream("PhraseDemo.pdf"));
            document.open();

            // 在文档中添加一些短语元素。
            document.add(new Phrase("This is the first text "));
            document.add(new Phrase("This is the second text "));
            document.add(new Phrase("This is the third text "));
            document.add(new Phrase("This is the fourth text "));
            document.add(new Phrase("This is the fifth text "));
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}

Maven依赖

<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>