使用iText7生成pdf文件

      在写自动生成数据库设计Word文档文章后,朋友建议再实现生成pdf格式,并推荐的iText7,我花了点时间学习了一下itext,实现了这个功能。

首先引入依赖

 
    	com.itextpdf
    	itext7-core
    	7.0.2
    	pom
    

生成PDF的方法

public String createPdf(List 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文件,我给大家看一下效果

使用iText7生成pdf文件_第1张图片

 详细代码可以到github上下载:https://github.com/daiwenlong/mindoc

你可能感兴趣的:(Java基础,工具)