java通过Itext导出pdf
需要的POM文件
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.11</version>
</dependency>
代码
/**
* 设置字体
*
* @param fontsize
* @param color
* @param isBold
* @return
*/
public static Font setFont(Float fontsize, BaseColor color, Boolean isBold) {
Font font = new Font();
try {
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
font = new Font(baseFont, fontsize, isBold ? Font.BOLD : Font.NORMAL, color);
} catch (Exception e) {
e.printStackTrace();
}
return font;
}
public static Font setFont(Float fontsize) {
Font font = new Font();
try {
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
font = new Font(baseFont, fontsize,Font.NORMAL, BaseColor.BLACK);
} catch (Exception e) {
e.printStackTrace();
}
return font;
}
public static Font setFont(Float fontsize, Boolean isBold) {
Font font = new Font();
try {
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
font = new Font(baseFont, fontsize, isBold ? Font.BOLD : Font.NORMAL, BaseColor.BLACK);
} catch (Exception e) {
e.printStackTrace();
}
return font;
}
private static BaseFont baseFont;
private static Font font10;
private static Font font10Bold;
private static Font font11;
private static Font font11Bold;
private static Font font12;
private static Font font12Bold;
private static Font font14Bold;
private static Font font16Bold;
static {
try {
//使用iTextAsian.jar中的字体、并设置编码
baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
font10 = PdfUtils.setFont(10f);
font10Bold = PdfUtils.setFont(10f,true);
font11 = PdfUtils.setFont(11f);
font11Bold = PdfUtils.setFont(11f,true);
font12 = PdfUtils.setFont(12f);
font12Bold = PdfUtils.setFont(12f,true);
font14Bold = PdfUtils.setFont(14f,true);
font16Bold = PdfUtils.setFont(16f,true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void courseRankInfoToPdf(Long courseId) {
//---初始化数据
CourseBaseScoreInfoBO baseScoreInfo = customVrTrainScoreMapper.getBaseScoreInfo(courseId);//获取课程基本信息
String courseName = baseScoreInfo.getCourseName();//课程名称
Integer totalPerson = baseScoreInfo.getTotalPerson();//参与人数
if(totalPerson == 0){//当参与人数为0,说明该课程暂无成绩,不进行导出
throw new CustomException("该课程暂无成绩,不支持导出");
}
String pdfName = courseName + "-成绩排名";
float[] widths = {10, 15, 15, 15, 15, 15, 15};//百分比
CourseRankInfoPdfModel scorePdfModel = new CourseRankInfoPdfModel();
scorePdfModel.setCourseBaseScoreInfoBO(baseScoreInfo);
scorePdfModel.setColumn(7);
scorePdfModel.setWidths(widths);
String title2 = "总分: "+baseScoreInfo.getTotalScore()+" 参与人数: "+totalPerson+"人";
scorePdfModel.setTitle2(title2);
scorePdfModel.setTitleSuffix("成绩排名");
List<CourseScoreRankInfoBO> rankInfo = customVrTrainScoreMapper.getRankInfo(courseId);
scorePdfModel.setCourseScoreRankInfoBOList(rankInfo);
Document document = new Document(PageSize.A4);
setPdfCommon(pdfName,document);
try {
addCourseRankInfoInfos(document,scorePdfModel);
} catch (DocumentException e) {
e.printStackTrace();
}
document.close();
}
void setPdfCommon(String pdfName,Document document){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = requestAttributes.getResponse();
try {
response.setHeader("Content-Disposition", "attachment;filename=" + new String(pdfName.getBytes(), "ISO-8859-1") + ".pdf");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
ServletOutputStream os = response.getOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, os);
writer.setPageEvent(new HeaderFooter());// 页眉/页脚
//writer.setPageEvent(new Watermark("捷安高科"));//水印,所有页面
document.open();
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
/**
* 添加课程排名信息
*
* @param document
* @throws DocumentException
*/
private void addCourseRankInfoInfos(Document document, CourseRankInfoPdfModel scorePdfModel) throws DocumentException {
CourseBaseScoreInfoBO courseBaseScoreInfoBO = scorePdfModel.getCourseBaseScoreInfoBO();
float[] widths = scorePdfModel.getWidths();
String titleSuffix = scorePdfModel.getTitleSuffix();//标题后缀
String courseName = courseBaseScoreInfoBO.getCourseName();//课程名称
String title2S = scorePdfModel.getTitle2();//小标题
//空行
Paragraph blankLine = new Paragraph("\n", font12);
document.add(blankLine);
PdfPTable table = new PdfPTable(scorePdfModel.getColumn());
addDocumentBaseInfos(table,widths,titleSuffix,courseName,title2S);
setCell(table, "课程及格率", 2, font10Bold, true);//第二行第一列
setCell(table, "任务总数", 1, font10Bold, true);//第二行第二列
setCell(table, "平均分", 1, font10Bold, true);//第二行第三列
setCell(table, "最高分", 1, font10Bold, true);//第二行第四列
setCell(table, "最低分", 1, font10Bold, true);//第二行第五列
setCell(table, "平均操作时长", 1, font10Bold, true);//第二行第六列
setCell(table, courseBaseScoreInfoBO.getPassRate() + "%", 2, font14Bold);
setCell(table, courseBaseScoreInfoBO.getTaskNum() + "个", 1, font11);
setCell(table, courseBaseScoreInfoBO.getAvgScore() + "分", 1, font11);
setCell(table, courseBaseScoreInfoBO.getMaxScore() + "分", 1, font11);
setCell(table, courseBaseScoreInfoBO.getMinScore() + "分", 1, font11);
String avgSeconds = courseBaseScoreInfoBO.getAvgSeconds();
if(avgSeconds != null && avgSeconds.indexOf(".")>0){//操作时长单位是秒,保留两位小数,转换int需要截取后面小数
avgSeconds = avgSeconds.substring(0,avgSeconds.indexOf("."));
}else{
avgSeconds = "0";
}
setCell(table, DateUtil.secondToTime(Integer.parseInt(avgSeconds)), 1, font11);
setCell(table, "成绩排名", 7, font11Bold);
setCell(table, "排名", 1, font10Bold, true);
setCell(table, "账号", 2, font10Bold, true);
setCell(table, "姓名", 1, font10Bold, true);
setCell(table, "最高分", 1, font10Bold, true);
setCell(table, "累计实训次数", 1, font10Bold, true);
setCell(table, "累计实训时长", 1, font10Bold, true);
List<CourseScoreRankInfoBO> courseScoreRankInfoBOList = scorePdfModel.getCourseScoreRankInfoBOList();
for (CourseScoreRankInfoBO courseScoreRankInfoBO : courseScoreRankInfoBOList) {
setCell(table, courseScoreRankInfoBO.getRankNo() + "", 1, font10);
setCell(table, courseScoreRankInfoBO.getUserName(), 2, font10);
setCell(table, courseScoreRankInfoBO.getRealName(), 1, font10);
setCell(table, courseScoreRankInfoBO.getHighestScore() + "", 1, font10);
setCell(table, courseScoreRankInfoBO.getTrainNum() + "", 1, font10);
setCell(table, DateUtil.secondToTime(courseScoreRankInfoBO.getTotalSeconds()), 1, font10);
}
document.add(table);
}
实体类代码
@Data
@ApiModel
public class CourseBaseScoreInfoBO {
/**
* 课程名称
*/
@ApiModelProperty(value = "课程名称")
private String courseName;
/**
* 总分
*/
@ApiModelProperty(value = "总分")
private Double totalScore;
/**
* 参与人数
*/
@ApiModelProperty(value = "参与人数")
private Integer totalPerson;
/**
* 及格率
*/
@ApiModelProperty(value = "及格率")
private Double passRate;
/**
* 任务总数
*/
@ApiModelProperty(value = "任务总数")
private Integer taskNum;
/**
* 平均分
*/
@ApiModelProperty(value = "平均分")
private Double avgScore;
/**
* 最高分
*/
@ApiModelProperty(value = "最高分")
private Double maxScore;
/**
* 最低分
*/
@ApiModelProperty(value = "最低分")
private Double minScore;
/**
* 平均操作时长
*/
@ApiModelProperty(value = "平均操作时长")
private String avgSeconds;
}
@Data
@ApiModel
public class CourseScoreRankInfoBO {
/**
* 排名
*/
@ApiModelProperty(value = "排名")
private Long rankNo;
/**
* 课程id
*/
@ApiModelProperty(value = "用户id")
private Long userId;
/**
* 账号
*/
@ApiModelProperty(value = "账号")
private String userName;
/**
* 总分
*/
@ApiModelProperty(value = "姓名")
private String realName;
/**
* 最高分
*/
@ApiModelProperty(value = "最高分")
private Double highestScore;
/**
* 累计实训次数
*/
@ApiModelProperty(value = "累计实训次数")
private Integer trainNum;
/**
* 累计实训时长
*/
@ApiModelProperty(value = "累计实训时长")
private Integer totalSeconds;
}
@Data
public class CourseRankInfoPdfModel {
int column;//表格列数
String titleSuffix;//表名后缀
float[] widths;//表格列百分比
String title2;//表格小标题
CourseBaseScoreInfoBO courseBaseScoreInfoBO;//课程排名基本信息
List<CourseScoreRankInfoBO> courseScoreRankInfoBOList;//课程排名信息数据
}
设置页眉页脚
public class HeaderFooter extends PdfPageEventHelper{
// 总页数
PdfTemplate totalPage;
Font font11= PdfUtils.setFont(11f, BaseColor.BLACK, false);
// 打开文档时,创建一个总页数的模版
public void onOpenDocument(PdfWriter writer, Document document) {
PdfContentByte cb =writer.getDirectContent();
totalPage = cb.createTemplate(30, 16);
}
// 一页加载完成触发,写入页眉和页脚
public void onEndPage(PdfWriter writer, Document document) {
PdfPTable table = new PdfPTable(1);
try {
table.setTotalWidth(PageSize.A4.getWidth() - 80);
table.setWidths(new int[] { 24});
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(-10);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(new Paragraph("导出时间: "+ DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS_), font11));// 可以直接使用addCell(str),不过不能指定字体,中文无法显示
// 将页眉写到document中,位置可以指定,指定到下面就是页脚
table.writeSelectedRows(0, -1, 70, PageSize.A4.getHeight() - 20, writer.getDirectContent());
} catch (Exception de) {
throw new ExceptionConverter(de);
}
PdfPTable table2 = new PdfPTable(1);
try {
table2.setTotalWidth(PageSize.A4.getWidth() - 80);
table2.setWidths(new int[] { 24});
table2.setLockedWidth(true);
table2.getDefaultCell().setFixedHeight(-10);
table2.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table2.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table2.addCell(new Paragraph("第 " + writer.getPageNumber() + " 页", font11));
// 将页眉写到document中,位置可以指定,指定到下面就是页脚
table2.writeSelectedRows(0, -1, 40, 40, writer.getDirectContent());
} catch (Exception de) {
throw new ExceptionConverter(de);
}
}
}
导出效果图