Java IText:短语
时间:2020-01-09 10:36:10 来源:igfitidea点击:
IText中的com.itextpdf.text.Phrase类表示文本的"短语"。 Phrase类知道如何在行之间增加间距。
这是一个简单的代码示例:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
public class DocumentExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Phrase.pdf"));
document.open();
document.add(new Phrase("This is sentence 1. "));
document.add(new Phrase("This is sentence 2. "));
document.add(new Phrase("This is sentence 3. "));
document.add(new Phrase("This is sentence 4. "));
document.add(new Phrase("This is sentence 5. "));
document.add(new Phrase("This is sentence 6. "));
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
行间距
短语对象知道如果添加的短语超过文档的右边缘,如何增加行距。但是,它不会在段落之间添加额外的空间。为此,我们需要使用一个"段落"对象。
行距以用户单位度量。每英寸有72个单位。默认间距是字体高度的1.5倍。我们可以通过将间距作为参数传递给Phrase构造函数来更改行距,如下所示:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
public class DocumentExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Phrase2.pdf"));
document.open();
Chunk chunk = new Chunk("This is a sentence ");
Phrase phrase = new Phrase(50);
phrase.add(chunk);
phrase.add(chunk);
phrase.add(chunk);
phrase.add(chunk);
phrase.add(chunk);
phrase.add(chunk);
document.add(phrase);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

