1、itext依賴
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
2、Demo
package com.zdj;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
import java.io.FileOutputStream;
/**
* @author zhangdj
* @date 2019/7/17
*/
public class ItextDemo {
public static void main(String[] args) throws Exception {
// 新建document
Document document = new Document();
// 建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁盤中。
// 創建 PdfWriter 對象 參數是對文檔對象 和 文路徑
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:/test.pdf"));
// 打開文檔
document.open();
//設置字體
// 系統字體 C:/WINDOWS/Fonts/simkai.ttf 目錄下 右鍵字體屬性 SIMFANG.TTF
BaseFont bfChinese = BaseFont.createFont("PingFang-SC-Medium.otf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//字體大小
Font font = new Font(bfChinese, 20);
//段落
Paragraph title = new Paragraph("報告標題", font);
//設置居中
title.setAlignment(Element.ALIGN_CENTER);
//段後間距
title.setSpacingAfter(20f);
//添加到文檔
document.add(title);
// 創建一條線
LineSeparator line = new LineSeparator();
// 設置線的顏色
line.setLineColor(new BaseColor(0, 0, 0));
//加入文檔
document.add(line);
Paragraph paragraph = new Paragraph("段落段落段落段落段落段落段落段落段落段落段落段落段落段落段落段落段落段落段落", font);
//設置段落行距
paragraph.setLeading(30f);
//段落前後間距
paragraph.setSpacingBefore(20f);
paragraph.setSpacingAfter(20f);
//左縮進
paragraph.setIndentationLeft(30f);
//右縮進
paragraph.setIndentationRight(30f);
document.add(paragraph);
//創建一個表格指定表格列數爲3
PdfPTable table = new PdfPTable(3);
for (int i = 0; i < 6; i++) {
//創建單元格
PdfPCell cell = new PdfPCell();
//單元格設置內容 字體
cell.setPhrase(new Phrase("單元格",font));
//單元格不顯示邊框
cell.setBorderWidth(0);
//單元格添加到表格
table.addCell(cell);
}
document.add(table);
// 5.關閉文檔
document.close();
}
}
3、效果圖
4、字體說明
//設置字體
// 系統字體 C:/WINDOWS/Fonts/simkai.ttf 目錄下 右鍵字體屬性 SIMFANG.TTF
BaseFont bfChinese = BaseFont.createFont("C:/WINDOWS/Fonts/simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
字體只要是工程可以訪問到的.ttf .otf的字體文件都是可以的。我工程裏面有一個字體文件。也是可以使用的。
效果圖
5、itext文檔
https://api.itextpdf.com/iText5/5.5.13/