城市直播房产教育博客汽车
投稿投诉
汽车报价
买车新车
博客专栏
专题精品
教育留学
高考读书
房产家居
彩票视频
直播黑猫
投资微博
城市上海
政务旅游

Java根据Freemarker模板生成Word文件

5月21日 渡缘祠投稿
  1。准备模板
  模板数据模型
  1、将准备好的Word模板文件另存为。xml文件(PS:建议使用WPS来创建Word文件,不建议用Office)
  2、将。xml文件重命名为。ftl文件
  3、用文本编辑器打开。ftl文件,将内容复制出来,格式化一下,再覆盖原来的内容
  (PS:格式化一下是为了方便查找并设置变量占位符,当然设置好模板参数变量以后可以再压缩后再写会。ftl文件)
  另外,强烈不建议在word文件中去编辑设置模板变量,因为。docx文件在另存为。xml文件后,原先好好的一个变量可能就被拆开了,建议另存为之后再用文本编辑器打开去编辑。
  4、设置模板参数(变量占位符)
  2。代码实现
  pom。?xmlversion1。0encodingUTF8?projectxmlnshttp:maven。apache。orgPOM4。0。0xmlns:xsihttp:www。w3。org2001XMLSchemainstancexsi:schemaLocationhttp:maven。apache。orgPOM4。0。0https:maven。apache。orgxsdmaven4。0。0。xsdmodelVersion4。0。0modelVersionparentgroupIdorg。springframework。bootgroupIdspringbootstarterparentartifactIdversion2。7。3versionrelativePath!lookupparentfromrepositoryparentgroupIdcom。examplegroupIddemo920artifactIdversion0。0。1SNAPSHOTversionnamedemo920namedescriptiondemo920descriptionpropertiesjava。version1。8java。versionpropertiesdependenciesdependencygroupIdorg。springframework。bootgroupIdspringbootstarterfreemarkerartifactIddependencydependencygroupIdorg。springframework。bootgroupIdspringbootstarterwebartifactIddependencydependencygroupIdcn。hutoolgroupIdhutoolcoreartifactIdversion5。8。7versiondependencydependencygroupIdcom。itextpdfgroupIditextpdfartifactIdversion5。5。13。3versiondependency!dependencygroupIdcom。asposegroupIdasposewordsartifactIdversion22。9versionclassifierjdk17classifierdependencydependencygroupIdorg。projectlombokgroupIdlombokartifactIdoptionaltrueoptionaldependencydependencygroupIdorg。springframework。bootgroupIdspringbootstartertestartifactIdscopetestscopedependencydependenciesbuildpluginsplugingroupIdorg。springframework。bootgroupIdspringbootmavenpluginartifactIdconfigurationexcludesexcludegroupIdorg。projectlombokgroupIdlombokartifactIdexcludeexcludesconfigurationpluginpluginsbuildproject
  写个类测试一下packagecom。example。demo920;importcom。example。demo920。domain。LoanRimportfreemarker。template。Cimportfreemarker。template。Timportorg。junit。jupiter。api。Timportorg。springframework。boot。test。context。SpringBootTimportjava。io。BufferedWimportjava。io。Fimportjava。io。FileOutputSimportjava。io。OutputStreamWimportjava。math。BigDimportjava。nio。file。Pimportjava。nio。file。Pimportjava。time。LocalDateTimportjava。time。format。DateTimeFimportjava。util。HashMimportjava。util。Limportjava。util。MSpringBootTestclassDemo920ApplicationTests{privateDateTimeFormatterDTFDateTimeFormatter。ofPattern(yyyyMMddHHmmss,Locale。CHINA);TestvoidcontextLoads(){}TestvoidtestGenerateWord()throwsException{ConfigurationconfigurationnewConfiguration(Configuration。VERSION2331);configuration。setDefaultEncoding(UTF8);configuration。setClassForTemplateLoading(this。getClass(),templates);Templatetemplateconfiguration。getTemplate(借条。ftl);PathpathPaths。get(tmp,contract);FilefileDirpath。toFile();if(!fileDir。exists()){fileDir。mkdirs();}Stringfilename借条LocalDateTime。now()。format(DTF)。filenamepath。toFile()File。BufferedWriterwriternewBufferedWriter(newOutputStreamWriter(newFileOutputStream(filename)));template。process(getDataMap(),writer);template。process(getData(),writer);writer。flush();writer。close();}MapString,ObjectgetDataMap(){MapString,ObjectdataMapnewHashMap();dataMap。put(borrowerName,李白);dataMap。put(borrowerIdCard,421302199001012426);dataMap。put(lenderName,杜甫);dataMap。put(amount,100);dataMap。put(amountInWords,壹佰);dataMap。put(startDate,2022年8月15日);dataMap。put(endDate,2022年11月11日);dataMap。put(borrowingMonths,3);dataMap。put(interestRate,1。23);dataMap。put(guarantorName,白居易);dataMap。put(guarantorIdCard,421302199203152412);returndataM}LoanReceiptgetData(){LoanReceiptreceiptnewLoanReceipt();receipt。setBorrowerName(狄仁杰);receipt。setBorrowerIdCard(421302198710121234);receipt。setBorrowingMonths(6);receipt。setLenderName(李元芳);receipt。setAmount(newBigDecimal(101));receipt。setAmountInWords(壹佰零壹);receipt。setInterestRate(newBigDecimal(0。6));receipt。setStartDate(2022年1月1日);receipt。setEndDate(2022年6月30日);receipt。setGuarantorName(武则天);receipt。setGuarantorIdCard(421302199101014567);}}
  最主要的是下面两行加载模板Templatetemplateconfiguration。getTemplate(借条。ftl);填充数据template。process(getData(),writer);
  数据可以是Map也可以是一个对象
  改进一下,将生成文件的操作单独写成一个工具方法packagecom。example。demo920。importcn。hutool。core。io。IoUimportfreemarker。template。Cimportfreemarker。template。Timportfreemarker。template。TemplateEimportjava。io。;publicclassFreemarkerUtils{生成WordparamtemplateDir模板所在的目录paramtemplateName模板文件名称paramfilename生成的文件(含路径)paramdataModel模板参数数据publicstaticvoidgenerateWord(FiletemplateDir,StringtemplateName,Stringfilename,ObjectdataModel){BufferedWConfigurationconfigurationnewConfiguration(Configuration。VERSION2331);configuration。setDefaultEncoding(UTF8);try{configuration。setDirectoryForTemplateLoading(templateDir);Templatetemplateconfiguration。getTemplate(templateName);writernewBufferedWriter(newOutputStreamWriter(newFileOutputStream(filename)));template。process(dataModel,writer);writer。flush();}catch(IOExceptione){thrownewRuntimeException(e);}catch(TemplateExceptione){thrownewRuntimeException(e);}finally{IoUtil。close(writer);}}}
  再测试一下packagecom。example。demo920;importcn。hutool。core。io。IoUimportcom。example。demo920。util。FreemarkerUimportcom。example。demo920。util。PdfUimportorg。junit。jupiter。api。Timportorg。springframework。util。ResourceUimportjava。io。;importjava。nio。file。Fimportjava。nio。file。Pimportjava。nio。file。Pimportjava。time。LocalDateTimportjava。util。HashMimportjava。util。MpublicclassWordTest{1、从文件服务器下载模板文件2、根据业务类型获取需要填充模板的数据3、模板数据再经过处理生成新的文件4、将生成后的文件上传到文件服务器,并返回一个文件ID5、业务可以保存这个文件ID或者文件的路径TestvoidtestGenerateWordV1()throwsException{PathtempPathPaths。get(tmp,contract2);FilepathtempPath。toFile();if(!path。exists()){path。mkdirs();}FiletempFileFiles。createTempFile(tempPath,qiantiao,。docx)。toFile();System。out。println(tempFile。getParent());System。out。println(tempFile。getName());FileOutputStreamfosnewFileOutputStream(tempFile);FiletemplateFileResourceUtils。getFile(classpath:templates借条。ftl);FileInputStreamfisnewFileInputStream(templateFile);IoUtil。copy(fis,fos);Stringfilename借条System。currentTimeMillis()。filenametmpcontractFile。FreemarkerUtils。generateWord(newFile(tempFile。getParent()),tempFile。getName(),filename,getDataMap());}获取数据MapString,ObjectgetDataMap(){MapString,ObjectdataMapnewHashMap();dataMap。put(borrowerName,李白2);dataMap。put(borrowerIdCard,421302199001012426);dataMap。put(lenderName,杜甫);dataMap。put(amount,100);dataMap。put(amountInWords,壹佰);dataMap。put(startDate,2022年8月15日);dataMap。put(endDate,2022年11月11日);dataMap。put(borrowingMonths,3);dataMap。put(interestRate,1。23);dataMap。put(guarantorName,白居易);dataMap。put(guarantorIdCard,421302199203152412);returndataM}TestvoidtestGenerateWord2()throwsException{FiletemplateDirResourceUtils。getFile(ResourceUtils。CLASSPATHURLPREFIXtemplates);StringtemplateName借条。StringdestFilename借条System。currentTimeMillis()。MapString,ObjectdatagetDataMap();FreemarkerUtils。generateWord(templateDir,templateName,destFilename,data);}}
  3。PDF文件加水印
  有时候,生成或者从服务器下载的文件是需要加水印的,比如标识这个文件是谁下载的之类的
  pdf加水印还是比较方便的,用itext组件可以轻松实现
  另外,如果最终需要pdf文件,建议直接生成pdf文件,跳过word转pdf的步骤packagecom。example。demo920。importcn。hutool。core。io。IoUimportcom。aspose。words。Dimportcom。aspose。words。SaveFimportcom。itextpdf。text。BaseCimportcom。itextpdf。text。DocumentEimportcom。itextpdf。text。Eimportcom。itextpdf。text。Iimportcom。itextpdf。text。pdf。;importjava。io。Fimportjava。io。FileInputSimportjava。io。FileOutputSimportjava。io。IOEimportjava。time。LocalDateTauthorchengjianshengdate20220921publicclassPdfUtils{Word转PDFhttps:www。aspose。com注意:Aspose。Words这个组件是收费的,如果购买的话生成的PDF会有水印。可以去找相应的破解版本,但是我感觉完全可以跳过Word直接生成PDF。比如,可以通过Freemarker直接生成PDF,或者利用iText通过模板生成PDFparamsrcparamdestpublicstaticvoidwordToPdf(Stringsrc,Stringdest){FilefilenewFile(src);if(!file。exists()){thrownewRuntimeException(文件不存在);}FileInputStry{fisnewFileInputStream(file);DocumentwpdnewDocument(fis);wpd。save(dest,SaveFormat。PDF);}catch(Exceptione){thrownewRuntimeException(e);}finally{IoUtil。close(fis);}}加水印paramsrc源文件paramdest目标文件paramtext文字paramimagePath图片地址publicstaticvoidaddWatermark(Stringsrc,Stringdest,Stringtext,StringimagePath){try{待加水印的文件PdfReaderreadernewPdfReader(src);加完水印的文件PdfStamperstampernewPdfStamper(reader,newFileOutputStream(dest));字体BaseFontbaseFontBaseFont。createFont(STSongLight,UniGBUCS2H,BaseFont。NOTEMBEDDED);透明度PdfGStategsnewPdfGState();gs。setFillOpacity(0。4f);PDF文件总页数inttotalreader。getNumberOfPages()1;循环对每一页都加水印PdfContentBfor(inti1;i){水印在文本之上contentstamper。getOverContent(i);content。setGState(gs);if(null!imagePath){ImageimageImage。getInstance(imagePath);image。setAbsolutePosition(150,150);image。scaleToFit(300,300);content。addImage(image);for(intx0;x700;xx300){for(inty0;y900;yy200){image。setAbsolutePosition(x50,y50);image。scaleToFit(100,100);content。addImage(image);}}}if(null!text){content。beginText();content。setColorFill(BaseColor。RED);content。setFontAndSize(baseFont,20);content。showTextAligned(Element。ALIGNCENTER,text,50,50,45);for(intx0;x700;xx300){for(inty0;y900;yy200){水印内容和水印位置content。showTextAligned(Element。ALIGNCENTER,哈哈哈哈哈,x20,y10,30);content。showTextAligned(Element。ALIGNCENTER,LocalDateTime。now()。toString(),x,y,30);}}content。endText();}}stamper。close();reader。close();}catch(IOExceptione){thrownewRuntimeException(e);}catch(DocumentExceptione){thrownewRuntimeException(e);}}}
  跑一下TestvoidtestWatermark(){Stringsrc2D:借条2。Stringdest2D:借条3。StringimagePathD:1。PdfUtils。addWatermark(src2,dest2,哈哈哈哈哈,imagePath);}
  加完水印后效果如图
  最后,示例项目结构如图
  原文链接:https:www。cnblogs。comcjsblogp16715294。html?utmsourcetuicoolutmmediumreferral
投诉 评论 转载

Java根据Freemarker模板生成Word文件1。准备模板模板数据模型1、将准备好的Word模板文件另存为。xml文件(PS:建议使用WPS来创建Word文件,不建议用Office)2、将。xml文件重命……库房造句用库房造句大全91。仓库管理人员说,由于地基下沉湿气上升,不仅库房受损,还影响到了储存物资的安全,安装去湿机后,每天能接半桶水。92。未料三种模式都不简单,颜君年说,西裔快餐车移动迅速……NBA大锤又秀恩爱,娶极品花魁!进族谱换中国名,满足归化3条北京时间9月16日,NBA球星大锤凯尔安德森更新了个人INS状态,晒出自己与娇妻一起参加朋友婚礼派对的照片,只见,安德森与娇妻恩爱出席,非常般配,妻子一身白色连体高叉裙,性感妩……平潭,距离台湾到底有多近?文江湖小舞今天在福建平潭旅游的人,这票真值!由于众所周知的原因,平潭突然以势不可挡的速度冲上了热搜,让很多人第一次知晓了这个地处海峡最前线的海岛县。游客拍下的……10条观人术,看清身边的妖魔鬼怪人性商战,一针见血!乡下老家那群人啊,哪里都好,就是人心不正,恨你有,笑你无,嫌你穷又怕你富。35成群,闲言碎语。如果你给对方一颗糖,他立马还你一颗枣,说明他是一个……摇滚小天后艾薇儿百变时尚彩妆盘点深邃烟熏妆狂放不自然烟熏妆mix半框眼镜如今的艾薇儿不但在音乐事业上如日中天,更是投身时尚界做起了自己的时装品牌。而我们也发现眼镜似乎成为了艾薇儿很爱的元素之一,眼镜妹可以模仿她的妆容,……全网最全抓包攻略丨傻瓜式Fiddler教程大全丨手把手从安装前言在我们做接口测试的时候,经常需要验证发送的消息是否正确,或者在出现问题的时候,查看手机客户端发送给server端的包内容是否正确,就需要用到抓包工具。今天,给大……朋友合伙创业的四点建议朋友合伙做生意易伤感情,甚至生意失败了连朋友都做不成。那么,兄弟间创业应该注意哪些事项呢?本文给一起创业的兄弟提了四点建议:1、先小人后君子。2、利益明晰。3、情账分离。4、财……论农村信用社电子银行业务发展策略摘要:在信息化时代,作为信息技术与银行业务紧密结合的产物,电子银行获得了快速的发展,而巨大的农村市场潜力为信用社发展电子银行业务提供了广泛的平台。本文从电子银行业务的认识出发,……防潮层的材料及优缺点外墙受潮后,经盐碱和冻融作用,年久后,砖墙表皮逐层酥松剥落,影响居住环境卫生和结构承载力,因此需要做防潮层。制作防潮层的位置及标高如下:(1)当室内地面垫层为不透水……胸闷气短四肢无力是怎么回事呢胸闷气短四肢无力,是很多人在生活当中会发现的一个现象,但是由于不太了解原因的话,所以对于治疗问题也无从下手,这样可能对自己健康造成的伤害就更大了,所以下面我们来为大家具体介绍一……小学体育课堂上的安全措施有哪些在近些年的小学体育课开展过程中,教师加大了对学生安全问题的关注,不仅广泛地加强了对学生的基础安全教育,而且也督促学生迅速转变当前的体育开展思路,注重安全与健康同时发展。但是现阶……
太科幻,中国打造太空核反应堆,比美国先进,未来可供月球基地用春天孩子们长得快,多给孩子吃这八种高钙菜,助力长个EA仍然认为单人游戏非常非常重要芥末到底是什么制作的为什么叫芥末?吃了20多年总算明白了大朋E3P定位版VR眼镜体验优良但内容是软肋为什么在酒店住宿不要关厕所灯?是你想的这样吗解禁欧菲光,支持中芯国际?老美这波操作不简单47岁林志玲罕见晒私照!淡妆出镜穿居家服,高调做宣传少女感太不要只知道聊天!教你清除WhatsApp,WeChat和Te洱源西湖一片琼瑶水,千重翡翠山爸爸姓氏尴尬,不愿女儿跟自己姓,爷爷随口取名让一家人点赞索尼电视固件更新2021年和2022年电视即将支持VRR局部

友情链接:中准网聚热点快百科快传网快生活快软网快好知文好找江西南阳嘉兴昆明铜陵滨州广东西昌常德梅州兰州阳江运城金华广西萍乡大理重庆诸暨泉州安庆南充武汉辽宁