背景:一个pdf模板,一个模板里能只能记录三条数据,但是导出时记录条数不确定,这是就需要合并多个模板了,然后把数据导出到合并后的模板
一 首先我们是maven项目,引入需要用到的包:
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.3</version> </dependency>
由于不支持中文,还需要导入中文包(注意:语言包和itext包是对应的,版本不兼容会报错)
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
二 贴代码
Controller层
@RequestMapping("/downLoadElecOrderDetails") public R downLoadElecOrderDetails(@RequestParam Map<String,Object> map,HttpServletResponse response)throws Exception{ OrderinfoEntity entity = orderinfoService.queryElecOrderDetails(map); try{ if(entity!=null){ ServletOutputStream out; out = response.getOutputStream(); response.setContentType("application/octet-stream; charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;fileName="+"order_detail("+ DateUtils.format(new Date())+").pdf"); map.put("callId",entity.getId()); List<CallDetailEntity> callDetailEntityList = callDetailService.queryList(map); entity.setCallDetailEntityList(callDetailEntityList); exportOrderDetailPdf(entity,out);//导出文件 out.flush(); out.close(); }else{ return R.error("工单编号输入错误!"); } }catch (IOException e){ e.printStackTrace(); } return R.ok(); }
先根据数据条数,生成对应页数的pdf模板文件,然后用模板文件贴上对应的数据
第一个模板,需要依次移动每个字段到对应位置,后面的直接循环搞定
//导出核心代码,
private boolean exportOrderDetailPdf(OrderinfoEntity entity, OutputStream out)throws Exception{ if(entity ==null){ return false; } // String tempFile = "D:\\upload\\serviceOrderDetailTemp.pdf"; String tempFile =filePath+"serviceOrderDetailTemp.pdf";//临时文件路径 int pageSize = (int)Math.ceil(Double.valueOf(entity.getCallDetailEntityList().size())/3.0);//向上取整 checkTempPdf(pageSize,tempFile);//生成对应大小的模板 PdfReader reader = new PdfReader(tempFile); PdfStamper stamper = new PdfStamper(reader, out); BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); try{ long minReachTime=entity.getCallDetailEntityList().get(0).getReachTime().getTime(); long maxLeaveTime=entity.getCallDetailEntityList().get(0).getLeaveTime().getTime(); for(int k=0;k<pageSize;k++){ PdfContentByte overContent = stamper.getOverContent(k+1); overContent.beginText(); overContent.setFontAndSize(font, 12); overContent.setTextMatrix(300, 200); overContent.showTextAligned(Element.ALIGN_LEFT,entity.getOrdernumber(),445,755,0);//工单编号 overContent.showTextAligned(Element.ALIGN_LEFT,entity.getServiceCompanyName(),95,733,0);//客户名称 overContent.showTextAligned(Element.ALIGN_LEFT,entity.getServiceAddress(),320,733,0);//服务地点 overContent.showTextAligned(Element.ALIGN_LEFT,entity.getDealTypeName(),95,685,0);//服务方式 //子单 for(int i=k*3;i<entity.getCallDetailEntityList().size()&&i<(k+1)*3;i++){ CallDetailEntity callDetailEntity = entity.getCallDetailEntityList().get(i); overContent.showTextAligned(Element.ALIGN_LEFT,callDetailEntity.getCustomerPersonName(),85,660-(192*(i%3)),0);//用户 overContent.showTextAligned(Element.ALIGN_LEFT,callDetailEntity.getEquipmentName(),172,660-(192*(i%3)),0);//设备 overContent.showTextAligned(Element.ALIGN_LEFT,DateUtils.format(callDetailEntity.getStartTime(),DateUtils.DATE_TIME_PATTERN),290,660-(192*(i%3)),0);//开始时间 overContent.showTextAligned(Element.ALIGN_LEFT,DateUtils.format(callDetailEntity.getFinishTime(),DateUtils.DATE_TIME_PATTERN),445,660-(192*(i%3)),0);//结束时间 //循环换行 for(int m=0;m<callDetailEntity.getFaultDesc().length();m=m+38){ String lineDescContent=""; if(m+38<callDetailEntity.getFaultDesc().length()){ lineDescContent= callDetailEntity.getFaultDesc().substring(m,m+38); }else{ lineDescContent=callDetailEntity.getFaultDesc().substring(m); } overContent.showTextAligned(Element.ALIGN_LEFT,lineDescContent,95,645-(192*(i%3))-(m/38)*14,0);//故障现象 } //循环换行 for(int n=0;n<callDetailEntity.getFaultSolve().length();n=n+38){ String lineSolveContent = ""; if(n+38<callDetailEntity.getFaultSolve().length()){ lineSolveContent=callDetailEntity.getFaultSolve().substring(n,n+38); }else{ lineSolveContent=callDetailEntity.getFaultSolve().substring(n); } overContent.showTextAligned(Element.ALIGN_LEFT,lineSolveContent,95,602-(192*(i%3))-(n/38)*14,0);//故障处理过程 } overContent.showTextAligned(Element.ALIGN_LEFT,callDetailEntity.getFinishStateName(),95,518-(192*(i%3)),0);//处理结果 overContent.showTextAligned(Element.ALIGN_LEFT,callDetailEntity.getTrace(),213,518-(192*(i%3)),0);//后续跟进 overContent.showTextAligned(Element.ALIGN_LEFT,callDetailEntity.getScore()==null?"-":String.valueOf(callDetailEntity.getScore()),148,493-(192*(i%3)),0);//评分 //签名 PdfDictionary pdfDictionary = reader.getPageN(1); PdfObject pdfObject = pdfDictionary.get(new PdfName("MediaBox")); PdfArray pdfArray = (PdfArray) pdfObject; String signPath = callDetailEntity.getSignPath(); if(signPath!=null&&!"".equals(signPath.trim())){ // String realPath = "/usr/project/upload/"+signPath; // String realPath = "D:\\upload\\"+signPath; String realPath = filePath+signPath; Image image = Image.getInstance(realPath); image.scalePercent(15); // image.setAbsolutePosition(370,80); 第三个子单 // image.setAbsolutePosition(370,280);第二个子单 image.setAbsolutePosition(370,480-((i%3)*192)); overContent.addImage(image); } if( callDetailEntity.getReachTime().getTime()<minReachTime){ minReachTime =callDetailEntity.getReachTime().getTime(); } if(callDetailEntity.getLeaveTime().getTime()>maxLeaveTime){ maxLeaveTime= callDetailEntity.getLeaveTime().getTime(); } } overContent.showTextAligned(Element.ALIGN_LEFT,DateUtils.format(new Date(minReachTime),DateUtils.DATE_TIME_PATTERN),95,700,0);//工单到达时间 overContent.showTextAligned(Element.ALIGN_LEFT,DateUtils.format(new Date(maxLeaveTime),DateUtils.DATE_TIME_PATTERN),260,700,0);//工单离开时间 overContent.endText(); } }catch (Exception e){ e.printStackTrace(); }finally { stamper.close(); reader.close(); File tempEnd = new File(tempFile);//删除生成的临时模板 if(tempEnd.exists()){ tempEnd.delete(); } return true; } }
//生成对应页数的pdf临时文件
private void checkTempPdf(int n,String tempFile) throws Exception{ File isExistTempFile = new File(tempFile); if(isExistTempFile.exists()){ isExistTempFile.delete(); } Document document = new Document(); try{ PdfWriter pdfWriter = PdfWriter.getInstance(document,new FileOutputStream(tempFile)); pdfWriter.setPdfVersion(PdfWriter.PDF_VERSION_1_2); document.open(); PdfReader reader = new PdfReader(filePath+"serviceOrderDetail.pdf"); PdfImportedPage page; page = pdfWriter.getImportedPage(reader,1); Image imagePage = Image.getInstance(page); imagePage.setAbsolutePosition(0,0); for(int l=0;l<n;l++){ document.add(imagePage); document.newPage(); } }catch(Exception e){ e.printStackTrace(); }finally{ if(document!=null){ document.close(); } } }