Java 实现word模板转为pdf
1.pom相关依赖
工具poi-tl(操作word文档模板)+jacob(将操作后的word模板转为pdf)
com.deepoove poi-tl 1.9.1
com.jacob jacob 1.17 system ${project.basedir}/src/main/resources/lib/jacob.jar
2.对word模板进行插入数据操作
使用poi-tl操作word需要创建一个用于向word插入数据的Map
//项目根路径 StringabPath=newFile("").getAbsolutePath()+"/src/main/resources"; //创建用于插入数据的Map Mapmap=newHashMap<>(); map.put( , ); ... //填充word文档 XWPFTemplatetemplate=XWPFTemplate.compile(abPath+"<模板路径>").render(map); //输出文档 template.writeAndClose(newFileOutPutStream("<输出路径>"));
3.对word模板的表格执行插入数据操作(动态表格)
使用poi-tl操作word的表格,动态的插入数据,需要用到poi-tl的可选插件进行自定义渲染策略,首先在word需要操作的表格中的任意单元格添加标签“{{标签}}”
自定义渲染策略
/** *自定义渲染策略 * *@author */ publicclassDetailTablePolicyextendsDynamicTableRenderPolicy{ //表格起始行行数 inttableStartRow=1; /** *自定义渲染策略 * *@data传入的封装好的数据 */ @Override publicvoidrender(XWPFTabletable,Objectdata)throwsException{ //如果数据为空,直接返回 if(null==data)return; //封装数据List的数据封装对象 NdrwhkhzbDatadetailData=(NdrwhkhzbData)data; //获取当前列表行高 intheight=table.getRow(2).getHeight(); //从封装对象中获取数据集合 Listdatas=detailData.getNdrwhkhzbs(); if(null!=datas){ //循环移除空白表格中数据数量的空白行 for(inti=1;i 把自定义渲染策略当做工具类,在主逻辑中直接配置使用
/** *操作年度任务和考核指标表 * *@throwsIOException输入输出流异常 */ privatevoidcreateNdrwhkhzb(Integeruid,StringdirPath)throwsIOException{ PageDatadatas=newPageData(); NdrwhkhzbDatadetailTable=newNdrwhkhzbData(); Listnds=newArrayList<>(); //根据uid查询年度任务和考核指标数据 List list=ndrwhkhzbService.selectNdrwhkhzbByUid(uid); for(NdrwhkhzbEntityndrwhkhzbEntity:list){ RowRenderDatarrd=Rows.of(ndrwhkhzbEntity.getNd(),ndrwhkhzbEntity.getNdrw(),ndrwhkhzbEntity.getNdkhzb() ,ndrwhkhzbEntity.getZyrwdsjjd()).center().create(); nds.add(rrd); } detailTable.setNdrwhkhzbs(nds); datas.setNdrwhkhzbData(detailTable); //配置表格 Configureconfig=Configure.builder().bind("detail_table",newDetailTablePolicy()).build(); //调用渲染策略进行填充 XWPFTemplatetemplate= XWPFTemplate.compile(dirPath+"/"+uid+"_Complete.docx",config).render(datas); //写入表格中 template.writeToFile(dirPath+"/"+uid+"_Complete.docx"); } 用到的一些实体类
//PageData publicclassPageData{ @Name("detail_table") privateNdrwhkhzbDatandrwhkhzbData; publicNdrwhkhzbDatagetNdrwhkhzbData(){ returnndrwhkhzbData; } publicvoidsetNdrwhkhzbData(NdrwhkhzbDatandrwhkhzbData){ this.ndrwhkhzbData=ndrwhkhzbData; } } //NdrwhkhzbData publicclassNdrwhkhzbData{ privateListndrwhkhzbs; publicList getNdrwhkhzbs(){ returnndrwhkhzbs; } publicvoidsetNdrwhkhzbs(List ndrwhkhzbs){ this.ndrwhkhzbs=ndrwhkhzbs; } } 4.将编辑好的Word转为pdf格式(jacob)
这里将word转为pdf时需要用到jacob,这里需要将jacob的dll文件放到jdk和jre的bin目录下,下载的jacob中dll文件一般为两个版本,X86为32位,X64为64位,根据自己安装的jdk版本添加所对应的dll文件
/* *将.docx转换为.pdf */ ActiveXComponentapp=null; StringwordFile=dirPath+"/"+uid+"_Complete.docx"; StringpdfFile=dirPath+"/"+dirName+".pdf"; System.out.println("开始转换..."); //开始时间 longstart=System.currentTimeMillis(); try{ //打开word app=newActiveXComponent("Word.Application"); //设置word不可见,很多博客下面这里都写了这一句话,其实是没有必要的,因为默认就是不可见的,如果设置可见就是会打开一个word文档,对于转化为pdf明显是没有必要的 //app.setProperty("Visible",false); //获得word中所有打开的文档 Dispatchdocuments=app.getProperty("Documents").toDispatch(); System.out.println("打开文件:"+wordFile); //打开文档 DispatchdocumentP=Dispatch.call(documents,"Open",wordFile,false,true).toDispatch(); //如果文件存在的话,不会覆盖,会直接报错,所以我们需要判断文件是否存在 Filetarget=newFile(pdfFile); if(target.exists()){ target.delete(); } System.out.println("另存为:"+pdfFile); //另存为,将文档报错为pdf,其中word保存为pdf的格式宏的值是17 Dispatch.call(documentP,"SaveAs",pdfFile,17); //关闭文档 Dispatch.call(documentP,"Close",false); //结束时间 longend=System.currentTimeMillis(); System.out.println("转换成功,用时:"+(end-start)+"ms"); }catch(Exceptione){ e.getMessage(); System.out.println("转换失败"+e.getMessage()); }finally{ //关闭office app.invoke("Quit",0); }5.通过lo流将生成好的文件传到浏览器下载
/* *下载pdf */ StringfileName=dirName+".pdf"; Filefile=newFile(dirPath+"/"+fileName); if(file.exists()){ BufferedInputStreambis=null; FileInputStreamfis=null; try{ response.setHeader("Content-disposition","attachment;filename="+fileName); byte[]buff=newbyte[2048]; fis=newFileInputStream(file); bis=newBufferedInputStream(fis); OutputStreamos=response.getOutputStream(); inti=bis.read(buff); while(i!=-1){ os.write(buff,0,i); i=bis.read(buff); } os.close(); }catch(Exceptione){ e.printStackTrace(); }finally{ assertfis!=null; fis.close(); assertbis!=null; bis.close(); } }6.最后的Controller整体代码
packageorg.example.controller; importcom.deepoove.poi.XWPFTemplate; importcom.deepoove.poi.config.Configure; importcom.deepoove.poi.data.Includes; importcom.deepoove.poi.data.RowRenderData; importcom.deepoove.poi.data.Rows; importcom.jacob.activeX.ActiveXComponent; importcom.jacob.com.Dispatch; importorg.example.entity.*; importorg.example.service.*; importorg.example.utils.DetailTablePolicy; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.context.annotation.Scope; importorg.springframework.stereotype.Controller; importorg.springframework.util.DigestUtils; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.ResponseBody; importjavax.servlet.http.HttpServletResponse; importjavax.servlet.http.HttpSession; importjava.io.*; importjava.util.ArrayList; importjava.util.HashMap; importjava.util.List; importjava.util.Map; /** *创建pdf控制器 * *@author:yoojyn *@data:2021/1/11 */ @Controller @RequestMapping("/createPdfController") publicclassCreatePdfController{ @Autowired privateIKtfmServicektfmService; @Autowired privateIKtjbxxServicektjbxxService; @Autowired privateIKtbyxfxServicektbyxfxService; @Autowired privateIZtmbhkhzbServiceztmbhkhzbService; @Autowired privateINdrwhkhzbServicendrwhkhzbService; @Autowired privateIKtjfysjsmServicektjfysjsmService; @Autowired privateIXjxhkxxfxServicexjxhkxxfxService; /** *生成word文件 * *@paramsession作用域 */ @Scope("prototype") @ResponseBody @RequestMapping("/createPdf") publicvoidcreatePdf(HttpSessionsession,HttpServletResponseresponse){ //获取当前用户id UserinfologinedUser=(Userinfo)session.getAttribute("loginedUser"); Integeruid=loginedUser.getUid(); StringdirName=DigestUtils.md5DigestAsHex((uid+"_国家重大专项任务合同申报").getBytes()); StringdirPath="D:/"+dirName; StringabPath=newFile("").getAbsolutePath()+"/src/main/resources"; try{ //创建用于存储中间文件的文件夹 newFile(dirPath).mkdirs(); //创建用于存储数据的map集合 Mapmap=newHashMap<>(); //获取封面数据 createKtfm(uid,map); //获取基本信息数据 createJbxx(uid,map); //获取必要性分析 createByxfx(uid,map); //获取总体目标和考核指标 createZtmbhkhzb(uid,map); //获取经费预算及说明 createJfysjsm(uid,map); //查询附件 XjxhkxxfxEntityxjxhkxxfxEntity=xjxhkxxfxService.selectXjxhkxxfxByUid(uid); //设置下一步处理表格要用到的标签 map.put("page9", Includes.ofLocal(abPath+"/static/file/upload/"+xjxhkxxfxEntity.getFilename()).create()); map.put("detail_table","{{detail_table}}"); //填充文档 XWPFTemplatetemplate=XWPFTemplate.compile(abPath+"/static/file/moban/moban.docx").render(map); //输出文档 template.writeAndClose(newFileOutputStream(dirPath+"/"+uid+"_Complete.docx")); //操作年度任务和考核指标表 createNdrwhkhzb(uid,dirPath); }catch(IOExceptione){ e.printStackTrace(); } try{ /* *将.docx转换为.pdf */ ActiveXComponentapp=null; StringwordFile=dirPath+"/"+uid+"_Complete.docx"; StringpdfFile=dirPath+"/"+dirName+".pdf"; System.out.println("开始转换..."); //开始时间 longstart=System.currentTimeMillis(); try{ //打开word app=newActiveXComponent("Word.Application"); //设置word不可见,很多博客下面这里都写了这一句话,其实是没有必要的,因为默认就是不可见的,如果设置可见就是会打开一个word文档,对于转化为pdf明显是没有必要的 //app.setProperty("Visible",false); //获得word中所有打开的文档 Dispatchdocuments=app.getProperty("Documents").toDispatch(); System.out.println("打开文件:"+wordFile); //打开文档 DispatchdocumentP=Dispatch.call(documents,"Open",wordFile,false,true).toDispatch(); //如果文件存在的话,不会覆盖,会直接报错,所以我们需要判断文件是否存在 Filetarget=newFile(pdfFile); if(target.exists()){ target.delete(); } System.out.println("另存为:"+pdfFile); //另存为,将文档报错为pdf,其中word保存为pdf的格式宏的值是17 Dispatch.call(documentP,"SaveAs",pdfFile,17); //关闭文档 Dispatch.call(documentP,"Close",false); //结束时间 longend=System.currentTimeMillis(); System.out.println("转换成功,用时:"+(end-start)+"ms"); }catch(Exceptione){ e.getMessage(); System.out.println("转换失败"+e.getMessage()); }finally{ //关闭office app.invoke("Quit",0); } /* *下载pdf */ StringfileName=dirName+".pdf"; Filefile=newFile(dirPath+"/"+fileName); if(file.exists()){ BufferedInputStreambis=null; FileInputStreamfis=null; try{ response.setHeader("Content-disposition","attachment;filename="+fileName); byte[]buff=newbyte[2048]; fis=newFileInputStream(file); bis=newBufferedInputStream(fis); OutputStreamos=response.getOutputStream(); inti=bis.read(buff); while(i!=-1){ os.write(buff,0,i); i=bis.read(buff); } os.close(); }catch(Exceptione){ e.printStackTrace(); }finally{ assertfis!=null; fis.close(); assertbis!=null; bis.close(); } } }catch(Exceptione){ e.printStackTrace(); }finally{ delDir(newFile(dirPath)); } } /** *删除文件夹 * *@paramfile文件夹对象 */ privatevoiddelDir(Filefile){ if(file.isFile()){ file.delete(); } if(file.isDirectory()){ File[]files=file.listFiles(); for(Filef:files){ f.delete(); } file.delete(); } } /** *储存经费预算及说明 * *@paramuid用户id *@parammap储存数据的map集合 */ privatevoidcreateJfysjsm(Integeruid,Map map){ //根据用户编号查询经费预算及说明 KtjfysjsmEntityktjfysjsmEntity=ktjfysjsmService.getDatesByUid(uid); //添加到map集合 map.put("zjzyczzj",ktjfysjsmEntity.getZjzyczzj()); map.put("zjdfczzj",ktjfysjsmEntity.getZjdfczzj()); map.put("zjdwzczj",ktjfysjsmEntity.getZjdwzczj()); map.put("zjqt",ktjfysjsmEntity.getZjqt()); } /** *操作年度任务和考核指标表 * *@throwsIOException输入输出流异常 */ privatevoidcreateNdrwhkhzb(Integeruid,StringdirPath)throwsIOException{ PageDatadatas=newPageData(); NdrwhkhzbDatadetailTable=newNdrwhkhzbData(); List nds=newArrayList<>(); //根据uid查询年度任务和考核指标数据 List list=ndrwhkhzbService.selectNdrwhkhzbByUid(uid); for(NdrwhkhzbEntityndrwhkhzbEntity:list){ RowRenderDatarrd=Rows.of(ndrwhkhzbEntity.getNd(),ndrwhkhzbEntity.getNdrw(),ndrwhkhzbEntity.getNdkhzb() ,ndrwhkhzbEntity.getZyrwdsjjd()).center().create(); nds.add(rrd); } detailTable.setNdrwhkhzbs(nds); datas.setNdrwhkhzbData(detailTable); Configureconfig=Configure.builder().bind("detail_table",newDetailTablePolicy()).build(); XWPFTemplatetemplate= XWPFTemplate.compile(dirPath+"/"+uid+"_Complete.docx",config).render(datas); template.writeToFile(dirPath+"/"+uid+"_Complete.docx"); } /** *储存总体目标和考核指标 * *@paramuid用户id *@parammap储存数据的map集合 */ privatevoidcreateZtmbhkhzb(Integeruid,Map map){ //根据用户编号查询总体目标和考核指标 ZtmbhkhzbEntityztmbhkhzbEntity=ztmbhkhzbService.selectZtmbhkhzbByUid(uid); //添加到map集合 map.put("page6",ztmbhkhzbEntity.getZtmbhkhzb()); } /** *储存必要性分析数据 * *@paramuid用户id *@parammap储存数据的map集合 */ privatevoidcreateByxfx(Integeruid,Map map){ //根据用户编号查询必要性分析数据 KtbyxfxEntityWithBLOBsktbyxfxEntity=ktbyxfxService.selectKtbyxfxByUid(uid); //添加到map集合 map.put("page5_ktyzx",ktbyxfxEntity.getKtyzx()); map.put("page5_ktysfgc",ktbyxfxEntity.getKtysf()); map.put("page5_ktyq",ktbyxfxEntity.getKtyq()); } /** *储存基本信息数据 * *@paramuid用户编号 *@parammap储存数据的map集合 */ privatevoidcreateJbxx(Integeruid,Map map){ //根据用户编号查询基本信息数据 KcjbxxEntitykcjbxxEntity=ktjbxxService.selectKtjbxxByUid(uid); //添加到map集合 map.put("page3_ktmc",kcjbxxEntity.getKtmc()); map.put("page3_ktmj",kcjbxxEntity.getKtmj()); map.put("page3_yjwcsj",kcjbxxEntity.getYjwcsj()); map.put("page3_kyhdlx",kcjbxxEntity.getKthdlx()); map.put("page3_yqcglx",kcjbxxEntity.getYqcglx()); map.put("page3_dwmc",kcjbxxEntity.getDwmc()); map.put("page3_dwxz",kcjbxxEntity.getDwxz()); map.put("page3_txdz",kcjbxxEntity.getTxdz()); map.put("page3_yzbm",kcjbxxEntity.getYzbm()); map.put("page3_szdq",kcjbxxEntity.getSzdq()); map.put("page3_dwzgbm",kcjbxxEntity.getDwzgbm()); map.put("page3_lxdh",kcjbxxEntity.getLxdh()); map.put("page3_zzjgdm",kcjbxxEntity.getZzjgdm()); map.put("page3_czhm",kcjbxxEntity.getCzhm()); map.put("page3_dwclsj",kcjbxxEntity.getDwclsj()); map.put("page3_dzxx",kcjbxxEntity.getDzxx()); } /** *储存课题封面数据 * *@paramuid用户编号 *@parammap储存数据的map集合 */ privatevoidcreateKtfm(Integeruid,Map map){ //根据用户编号查询封面数据 KtfmEntityktfmEntity=ktfmService.selectKtfmByUid(uid); //添加到map集合 map.put("page1_zxmc","5G总体及关键器件"); map.put("page1_xmbh","2016ZX03001_001"); map.put("page1_xmmc","新一代宽带无线移动通信网"); map.put("page1_ktbh","2016ZX03001_001_002"); map.put("page1_ktmc","5G高性能基站A/D、D/A转换器试验样片研发"); map.put("page1_zrdw","program_test"); map.put("page1_ktzz",ktfmEntity.getKtfzr()); map.put("page1_ktnx1","2016-01-01"); map.put("page1_ktnx2","2017-12-31"); map.put("page1_tbrq","2020-12-28"); map.put("page1_nian","二一"); map.put("page1_yue","一"); } } 以上就是Java实现word模板转为pdf的详细内容,更多关于Javaword模板转为pdf的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。