读书人

Itext 学习札记(三) Phrase(短句)的

发布时间: 2012-08-13 13:21:53 作者: rapoo

Itext 学习笔记(三) Phrase(短句)的用法
Itext的com.itextpdf.text.Phrase类的作用是添加一个短句。短语类知道如何添加行与行之间的间距。
例子一代码如下:

import java.io.FileNotFoundException;import java.io.FileOutputStream;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Phrase;import com.itextpdf.text.pdf.PdfWriter;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();         }    }}


运行结果如下


请注意它与块不同的是它如果写到一行的尾部会自动换行。

例子二设置行间距
代码如下
import java.io.FileNotFoundException;import java.io.FileOutputStream;import com.itextpdf.text.Chunk;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Phrase;import com.itextpdf.text.pdf.PdfWriter;public class DocumentExample {    public static void main(String[] args) {        //创建文本        Document document = new Document();         try {         //写入到输出流中             PdfWriter.getInstance(document, new FileOutputStream("Phrase.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();         }    }}


运行结果如下


注意两行之间的距离。

小宝制造。

读书人网 >开源软件

热点推荐