1、引入依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.16</version>
</dependency>
2、具体实现
public static void main(String[] args) {
Path path = Path.of("./files/" + UUID.randomUUID() + ".pdf");
PdfWriter pdfWriter;
try {
pdfWriter = new PdfWriter(path.toString());
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
PdfDocument pdfDocument = new PdfDocument(pdfWriter);
Document document = new Document(pdfDocument);
PdfFont chineseFont;
try {
chineseFont = PdfFontFactory.createFont("./files/simsun.ttf", PdfEncodings.IDENTITY_H, true);
} catch (IOException e) {
throw new RuntimeException("Font simsun.ttf not found", e);
}
Table table = new Table(UnitValue.createPercentArray(4));
table.setWidth(UnitValue.createPercentValue(100));
table.addCell(createCell("列1", chineseFont));
table.addCell(createCell("列2", chineseFont));
table.addCell(createCell("列3", chineseFont));
table.addCell(createCell("列4", chineseFont));
for (int i = 0; i < 10; i++) {
table.addCell(createCell(STR."数据1-\{i}", chineseFont));
table.addCell(createCell(STR."数据2-\{i}", chineseFont));
table.addCell(createCell(STR."数据3-\{i}", chineseFont));
table.addCell(createCell(STR."数据4-\{i}", chineseFont));
}
document.add(table);
document.close();
}
private static Cell createCell(String text, PdfFont font) {
Paragraph paragraph = new Paragraph(text).setFont(font).setTextAlignment(TextAlignment.CENTER);
return new Cell().add(paragraph).setBorder(new SolidBorder(new DeviceRgb(0, 0, 0), 1));
}
3、结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/f83d97cbc713402fb2d36a1294cdcdc9.png)