在itext的com.lowagie.text包中有Chunk,Phrase,Paragraph这三种text编辑单元
其中Chunk是最小的单元
也就是说Paragraph可以包含多个Phrase,Phrase可以包含多个Chunk
下面是Chunk的例子
public class Chunk_Example {
public Chunk_Example() throws Exception{
Document document = new Document();
PdfWriter.getInstance(document,
new FileOutputStream("chunk_example.pdf"));
document.open();
Font font = new Font(Font.COURIER, 10, Font.BOLD); // 设置font
font.setColor(new Color(0x92, 0x90, 0x83));
Chunk chunk =
new Chunk("testing text element", font); // 初始化Chunk
chunk.setBackground(new Color(0xff, 0xe4, 0x00)); // 设置背景
document.add(chunk); // 添加chunk到文档
document.close();
}
public static void main(String[] args) {
try{
Chunk_Example textExample = new Chunk_Example();
}catch(Exception e){
System.out.println(e);
}
}
}
我们一般不使用Chunk生成文本,因为Chunk不能自动换行,而是使用Phrase代替
public class Phrase_Example {
public Phrase_Example() throws Exception{
Document document = new Document();
PdfWriter.getInstance(document,
new FileOutputStream("phrase_example.pdf"));
document.open();
Font font = new Font(Font.COURIER, 10, Font.BOLD);
font.setColor(new Color(0x92, 0x90, 0x83));
Chunk chunk = new Chunk("testing text element ", font);
chunk.setBackground(new Color(0xff, 0xe4, 0x00));
Phrase phrase =
new Phrase(20, "This is initial text. ");
//初始化Phrase,有20像素的间距
for(int i=0; i < 10; i++)
{
phrase.add(chunk); // 添加110个Chunk到Phrase
}
document.add(phrase);
document.close();
}
public static void main(String[] args) {
try{
Phrase_Example textExample = new Phrase_Example();
}catch(Exception e){
System.out.println(e);
}
}
}
Phrase已经满足大部分需求,但是如果我们想要一个分成几段来显示文本,可以使用
phrase.add("\n");
也可以通过Paragraph来实现
public class Paragraph_Example {
public Paragraph_Example() throws Exception{
Document document = new Document();
PdfWriter.getInstance(document,
new FileOutputStream("paragraph_example.pdf"));
document.open();
Font font = new Font(Font.COURIER, 10, Font.BOLD);
font.setColor(new Color(0x92, 0x90, 0x83));
Chunk chunk = new Chunk("testing text element ", font);
chunk.setBackground(new Color(0xff, 0xe4, 0x00));
Phrase phrase = new Phrase(20, "This is initial text. ");
for(int i=0; i < 10; i++)
{
phrase.add(chunk);
}
Paragraph paragraph = new Paragraph();
paragraph.add(phrase);//添加phrase对象
document.add(paragraph); //添加 paragraph
document.add(paragraph); //添加 paragraph
document.close();
}
public static void main(String[] args) {
try{
Paragraph_Example textExample =
new Paragraph_Example();
}catch(Exception e){
System.out.println(e);
}
}
}
引用
http://www.geek-tutorials.com/java/itext/insert_control_text.php