通過iText可以動態創建PDF文件,並對創建的文件進行各種設置。在itext中的文本內容基本可以分爲Chunk、Phrase、Anchor、Paragraph、Chapter、Section等幾種類型。
Chunk:一段字符串,好比文本的原子;
Phrase:Phrase 是chunk集合;
Chapter:好比文章的大標題;
Paragraph:好比一個文本快,就是一個段落;
Section:創建文章的小標題。
一.創建一個帶有目錄的PDF:
Document document = new Document();//創建一個文檔對象
try {
//文檔對象輸出流
PdfWriter.getInstance(document, new FileOutputStream("01.pdf"));
document.open();//打開文檔
Chunk chunk = new Chunk("xu yan");//文章的序言
Phrase chunkPhrase = new Phrase(chunk);
String content = "yi yi yi yi yi";
Phrase textPhrase = new Phrase(content);
Phrase text = new Phrase("er er er er er");
Font font = new Font(Font.HELVETICA,14,Font.BOLD);
Chapter chapter1 = new Chapter(new Paragraph("da biao ti",font),1);//文章的大標題
Paragraph paragraph = new Paragraph();
paragraph.add(chunkPhrase);
chapter1.add(paragraph);
Section section0 = chapter1.addSection("xiao biao ti yi",2);//文章的小標題1
section0.add(textPhrase);
Section section = chapter1.addSection("xiao biao ti er",2);//文章的小標題2
section.add(text);
document.add(chapter1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
document.close();//關閉文檔
效果圖:
二.向PDF中插入靜態圖片:
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream("02.pdf"));
document.open();
//參數:目標圖片、X方向的偏移量、Y方向的偏移量
Chunk chunk = new Chunk(Image.getInstance("src/123.jpg"),0,-750);
Paragraph paragraph = new Paragraph();
paragraph.add(chunk);
paragraph.setAlignment(Element.ALIGN_RIGHT);
document.add(paragraph);
} catch (Exception e) {
e.printStackTrace();
}
document.close();
三.PDF中創建表格:
Document document = new Document();//創建一個文檔對象
try {
PdfWriter.getInstance(document, new FileOutputStream("03.pdf"));
document.open();
//創建一個三列的表格
PdfPTable table = new PdfPTable(3);
//設置各列的寬度
float[] widths = {1.3f,2.5f,1.0f};
table.setWidths(widths);
PdfPCell cell = new PdfPCell(new Paragraph("yiyi"));
cell.setColspan(3);//設置一個單元格跨的列數
table.addCell(cell);
table.addCell("1.1");
table.addCell("1.2");
table.addCell("1.3");
//設置單元格背景顏色
cell = new PdfPCell(new Paragraph("is red"));
cell.setColspan(3);
cell.setBackgroundColor(Color.red);
table.addCell(cell);
//設置單元格邊框顏色
cell = new PdfPCell(new Paragraph("border is blue"));
cell.setColspan(3);
cell.setBorderColor(Color.BLUE);
table.addCell(cell);
//cell.setHorizontalAlignment(Element.ALIGN_RIGHT);//設置單元格內容對齊方式
document.add(table);
} catch (Exception e) {
e.printStackTrace();
}
document.close();