使用itext7-core来生成pdf文档

之前使用itext5来生成pdf文档,最近又学习了itext7生成文档,感觉itext7用来生成pdf文件还不错。下面介绍一下使用方法。

首先在pom.xml文件中引入需要的依赖:


<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext7-core</artifactId>
    <version>7.1.8</version>
    <type>pom</type>
</dependency>
这个是itext7目前最新的依赖。


以下是生成pdf文档的java代码:


public String createPdf(List<TableVo> tables) {
 
	try {
		PdfDocument pdfDoc = new PdfDocument(
				new PdfWriter(System.getProperty("user.dir") + "\\DatabaseDesign.pdf"));
		Document doc = new Document(pdfDoc);// 构建文档对象
		TextFooterEventHandler eh = new TextFooterEventHandler(doc);
		pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, eh);
		// 中文字体
		PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
		Paragraph paragraph = new Paragraph();
		paragraph.add("数据库设计文档").setFont(sysFont).setBold().setFontSize(20).setTextAlignment(TextAlignment.CENTER);
		doc.add(paragraph);
		int num = 0;
		for (TableVo vo : tables) {
			num++;
			doc.add(new Paragraph(""));
			String title = num +"  表名:" + vo.getTableName() + "   表注释:" + vo.getTableComment();
			doc.add(new Paragraph(title).setFont(sysFont).setBold());
			// 构建表格以100%的宽度
			Table table = new Table(5).setWidth(UnitValue.createPercentValue(100));
 
			table.addCell(new Cell().add(new Paragraph("列名")).setFont(sysFont)
					.setBackgroundColor(new DeviceRgb(221, 234, 238)));
			table.addCell(new Cell().add(new Paragraph("数据类型")).setFont(sysFont)
					.setBackgroundColor(new DeviceRgb(221, 234, 238)));
			table.addCell(new Cell().add(new Paragraph("约束")).setFont(sysFont)
					.setBackgroundColor(new DeviceRgb(221, 234, 238)));
			table.addCell(new Cell().add(new Paragraph("允许空")).setFont(sysFont)
					.setBackgroundColor(new DeviceRgb(221, 234, 238)));
			table.addCell(new Cell().add(new Paragraph("备注")).setFont(sysFont)
					.setBackgroundColor(new DeviceRgb(221, 234, 238)));
			for (ColumnVo col : vo.getColumns()) {
				table.addCell(new Cell().add(new Paragraph(col.getColumnName())).setFont(sysFont));
				table.addCell(new Cell().add(new Paragraph(col.getColumnType())).setFont(sysFont));
				table.addCell(new Cell().add(new Paragraph(col.getColumnKey())).setFont(sysFont));
				table.addCell(new Cell().add(new Paragraph(col.getIsNullable())).setFont(sysFont));
				table.addCell(new Cell().add(new Paragraph(col.getColumnComment())).setFont(sysFont));
			}
			// 将表格添加入文档并页面居中
			doc.add(table.setHorizontalAlignment(HorizontalAlignment.CENTER));
		}
		doc.close();
		return "文件路径-" + System.getProperty("user.dir") + "\\DatabaseDesign.pdf";
	} catch (Exception e) {
		e.printStackTrace();
	}
	return "导出失败!请检查配置。";
}
这里生成的是含有表格的PDF文件,我给大家看一下效果:


您可能还会对下面的文章感兴趣: