1、pom.xml
<!-- 导出PDF -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<!--语言包-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2、Controller 层
/**
* 导出用户评价的pdf
* @param selfEvaluationId
*
* @param request
* @param response
* @ @author tannc
* @create-time 2018-06-22 14:47:24
*/
@GetMapping("pdf")
public void exportPDF(@RequestParam(value = "selfEvaluationId",required = false) Integer selfEvaluationId,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 下载本地文件
String fileName = "evaluation.pdf".toString(); // 文件的默认保存名
String path = request.getSession().getServletContext().getRealPath(Constants.UPLOAD_PDF);// 定义临时文件存放地址
File pathFile = new File(path);
if(!pathFile.exists()){
// 创建多级文件夹
pathFile.mkdirs();
}
//文件存放
String pdfPath= exportFileService.exportEvaluationPDF(selfEvaluationId,path);
// 读到流中
// 文件的存放路径
InputStream inStream = null;
// 设置输出的格式
response.reset();
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 循环取出流中的数据
byte[] b = new byte[100];
int len =0;
try {
inStream =new FileInputStream(pdfPath);
while ((len = inStream.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
File file =new File(pdfPath); // 删除临时文件
// 如果文件存在 删除。
if(file.exists()){
file.delete();
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3、Service 层
/**
* @param selfEvaluationId
* -- 评估id
*
* @description: 导出老师的评估表
* @author:tannc
* @createTime: 2018/6/22 15:21
*/
@Override
public String exportEvaluationPDF(Integer selfEvaluationId, String path) {
// 全局id
String uuid = UUID.randomUUID().toString();
String filePath =path.concat(File.separator).concat(uuid).concat(".pdf");
try {
// 第一步,实例化一个document对象
Document document = new Document();
File file = new File(filePath);
file.createNewFile();
// 第二步,设置要到出的路径
FileOutputStream out = new FileOutputStream(filePath);
// 业务数据
SelfEvaluationDetailDTO dto = selfEvaluationService.getSelfEvaluationDetail(selfEvaluationId);
// 第三步,设置字符
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
Font fontZH = new Font(bfChinese, 12.0F, 0);
// 第四步,将pdf文件输出到磁盘
PdfWriter writer = PdfWriter.getInstance(document, out);
// 设置页码
applyFooter(writer);
// 第五步,打开生成的pdf文件
document.open();
// 第六步,设置内容
pdfHome(document, dto,bfChinese);
// 换页
document.newPage();
// 导出checkList 表格
checklist(document,dto,bfChinese);
// 第七步,关闭document
document.close();
}catch ( Exception e){
e.printStackTrace();
}
return filePath;
}
/**
* 导出 check list
* @param document
* @param dto
* 导出的对象
* @param bfChinese
*/
private void checklist(Document document, SelfEvaluationDetailDTO dto, BaseFont bfChinese) throws DocumentException {
Font firstfont = new Font(bfChinese, 18, 0);
Font secondfont = new Font(bfChinese, 14, 0);
Font thirdfont = new Font(bfChinese, 12, 0);
Paragraph titleParagraph =null;
PdfPTable table =null;
Paragraph tempParagraph =null;
PdfPCell baseTableCell =null;
String suminfo = "Total score :%s Average score:%s" ;
if(!CollectionUtils.isEmpty(dto.getSkillList())){
for(SelfEvaluationSkillDTO skillDto : dto.getSkillList()){
if(CollectionUtils.isEmpty(skillDto.getChild()) ){
continue;
}
// 一级设置成标题
String title =skillDto.getName();
titleParagraph = new Paragraph(new Chunk(title, firstfont).setLocalDestination(title));
document.add(titleParagraph);
// 换行
document.add(new Paragraph("\n"));
table = new PdfPTable(2);
table.setWidthPercentage(100.0F);
table.setHeaderRows(1);
table.getDefaultCell().setHorizontalAlignment(1);
if(!CollectionUtils.isEmpty(skillDto.getChild())){
int count = 0;
int preCount =0 ;
//全局计数器
int globalCount =0;
int len = skillDto.getChild().size();
// 第二层
for(SelfEvaluationSkillDTO secondDto : skillDto.getChild()){
int sum = 0;
float avg = 0.0f;
int childCount =0;
globalCount ++;
if(secondDto.getDepth().equals(2)) {
sum =0 ;
avg=0.0f;
childCount =0;
// 设置表头
baseTableCell = new PdfPCell(new Paragraph(secondDto.getName(), secondfont));
baseTableCell.setBackgroundColor(new BaseColor(236, 236, 236));
table.addCell(baseTableCell);
if (count == 0) {
baseTableCell = new PdfPCell(new Paragraph("Rating", secondfont));
baseTableCell.setBackgroundColor(new BaseColor(236, 236, 236));
table.addCell(baseTableCell);
} else {
baseTableCell = new PdfPCell(new Paragraph("", secondfont));
baseTableCell.setBackgroundColor(new BaseColor(236, 236, 236));
table.addCell(baseTableCell);
}
// 计数器
count = count +1;
}
if(secondDto.getDepth().equals(3)) {
// 遍历第三层
baseTableCell = new PdfPCell(new Paragraph(secondDto.getName(), thirdfont));
baseTableCell.setVerticalAlignment(Element.ALIGN_LEFT);
table.addCell(baseTableCell);
// 分数
table.addCell(new Paragraph(String.valueOf(secondDto.getRaing()), thirdfont));
sum = sum + secondDto.getRaing();
childCount = childCount+1;
}
boolean isRight =(globalCount<len && skillDto.getChild().get(globalCount).getDepth()==2) || globalCount==skillDto.getChild().size();
//如果当前是2 下一个页面
if(isRight){
// 平均分
avg = sum / (childCount==0?1:childCount);
BigDecimal b = new BigDecimal(avg);
float f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
avg = f1;
// 汇总信息
tempParagraph = new Paragraph(String.format(suminfo, sum, avg), thirdfont);
// 居右
baseTableCell = new PdfPCell(tempParagraph);
tempParagraph.setAlignment(Element.ALIGN_RIGHT);
baseTableCell.setColspan(2);
baseTableCell.setPaddingRight(15.0f);
baseTableCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
baseTableCell.setBackgroundColor(new BaseColor(100, 100, 100));
table.addCell(baseTableCell);
}
}
}
//第一层就一张表
document.add(table);
document.add(new Paragraph("\n"));
}
}
// 换页
document.newPage();
}
/**
* 设置页眉、页脚
* @param writer
*/
private void applyFooter(PdfWriter writer) {
writer.setPageEvent(new PdfPageEventHelper() {
@Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
cb.beginText();
BaseFont bf = null;
try {
bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
}
cb.setFontAndSize(bf, 10);
//Header
float x = document.top(-20);
// //左
// cb.showTextAligned(PdfContentByte.ALIGN_LEFT,
// "H-Left",
// document.left(), x, 0);
// //中
// cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
// writer.getPageNumber()+ " page",
// (document.right() + document.left())/2,
// x, 0);
// //右
// cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,
// "H-Right",
// document.right(), x, 0);
//Footer
float y = document.bottom(-20);
// //左
// cb.showTextAligned(PdfContentByte.ALIGN_LEFT,
// "F-Left",
// document.left(), y, 0);
//中
cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
writer.getPageNumber()+"",
(document.right() + document.left())/2,
y, 0);
//右
// cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,
// "F-Right",
// document.right(), y, 0);
cb.endText();
cb.restoreState();
}
});
}
/**
* 设置主页
* @param document
* @param dto
* @param bfChinese
* @throws DocumentException
*/
private void pdfHome(Document document, SelfEvaluationDetailDTO dto, BaseFont bfChinese) throws DocumentException {
Font titlefont = new Font(bfChinese, 28F, 0);
String title =dto.getPeriod()+ Constants.PRE_TITLE;
Paragraph titleParagraph = new Paragraph(new Chunk(title, titlefont).setLocalDestination(title));
//文本居中
titleParagraph.setAlignment(Paragraph.ALIGN_CENTER);
document.add(new Paragraph("\n\n"));
document.add(new Paragraph("\n\n"));
document.add(new Paragraph("\n\n"));
document.add(new Paragraph("\n\n"));
document.add(titleParagraph);
document.add(new Paragraph("\n\n"));
String teacherName = Constants.PRE_NAME +dto.getUserName();
Font namefont = new Font(bfChinese, 14F, 0);
Paragraph nameParagraph = new Paragraph(new Chunk(teacherName, namefont).setLocalDestination(teacherName));
//文本居中
nameParagraph.setAlignment(Paragraph.ALIGN_CENTER);
document.add(nameParagraph);
document.add(new Paragraph("\n"));
String level =Constants.PRE_LEVEL+ dto.getDutyLevelName();
Font levelfont = new Font(bfChinese, 14.0F, 0);
// setLocalDestination 设置目录
Paragraph levelParagraph = new Paragraph(new Chunk(level, levelfont).setLocalDestination(level));
//文本居中
levelParagraph.setAlignment(Paragraph.ALIGN_CENTER);
document.add(levelParagraph);
document.add(new Paragraph("\n"));
String time =Constants.PRE_LASTAPPRAISAL + dto.getLastUpdate();
Font timefont = new Font(bfChinese, 14.0F, 0);
// setLocalDestination 设置目录
Paragraph timeParagraph = new Paragraph(new Chunk(time, levelfont).setLocalDestination(level));
//文本居中
timeParagraph.setAlignment(Paragraph.ALIGN_CENTER);
document.add(timeParagraph);
// 换行
document.add(new Paragraph("\n"));
}
4、完成