itext(一)Chunk、Phrase、Paragraph的应用

一,Chunk : 块,PDF文档中描述的最小原子元素
       Phrase : 短语,Chunk的集合
       Paragraph : 段落,一个有序的Phrase集合
二,
实例一:
package lession3;
import java.awt.Color;
import java.io.FileOutputStream;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.pdf.PdfWriter;
public class FirstMain {
public static void main(String[] args) throws Exception {
   Document doc = new Document();
   PdfWriter.getInstance(doc , new FileOutputStream("f:\\target.pdf"));
   doc.open();
  
   //定义一个块
   Chunk chunk = new Chunk("Cat");
   //设置块的背景色
   chunk.setBackground(Color.blue);
  
   //字体
   Font font = FontFactory.getFont(FontFactory.TIMES_BOLD);
   font.setColor(Color.white);
   chunk.setFont(font);
  
   //增加块到文档
   doc.add(chunk);
  
   chunk = new Chunk("DOG");
   doc.add(chunk);
   doc.close();
}
}


实例二:
package lession3;
import java.io.FileOutputStream;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;
public class FirstMain {
public static void main(String[] args) throws Exception {
   Document doc = new Document();
   PdfWriter.getInstance(doc , new FileOutputStream("f:\\target.pdf"));
   doc.open();
  
   //建块
   Chunk chunk1 = new Chunk("Cat");
   Chunk chunk2 = new Chunk("DOG");
  
   //建短语
   Phrase phrase = new Phrase();
   phrase.add(chunk1);
   phrase.add(chunk2);
   phrase.add("Hello world");
  
   doc.add(phrase);
  
   //新建一行
   doc.add(Chunk.NEWLINE);  
   doc.add(new Chunk("new line"));
  
   doc.close();
}
}


实例三
package lession3;
import java.io.FileOutputStream;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;
public class FirstMain {
public static void main(String[] args) throws Exception {
   Document doc = new Document();
   PdfWriter.getInstance(doc , new FileOutputStream("f:\\target.pdf"));
   doc.open();
  
   //建块
   Chunk chunk1 = new Chunk("Cat");
   Chunk chunk2 = new Chunk("DOG");
  
   //建短语
   Phrase phrase = new Phrase();
   phrase.add(chunk1);
   phrase.add(chunk2);
   phrase.add("Hello world");
  
   //建段落
   Paragraph paragraph = new Paragraph();
   paragraph.add(phrase);
   paragraph.add("Hello World");
  
   //设置段落对齐方式
   paragraph.setAlignment(Element.ALIGN_LEFT);
   //设置缩进
   paragraph.setIndentationLeft(100f);
  
   Paragraph paragraph1 = new Paragraph();
   paragraph1.add("AA");
  
   //注意增加段落时会自动换行
   doc.add(paragraph);
   doc.add(paragraph1);
  
   doc.close();
}
}


你可能感兴趣的:(itext(一)Chunk、Phrase、Paragraph的应用)