事情是这样的,系统有这样一个需求,有一些单子供客户下载打印,作为凭证,而这些单子通常属于word格式的,里面的排版很是固定,只是上面的内容不一样,这就属于word模板的范畴了,目前比较很差的操做word的组件就是aspose了,下面我来讲一下它的使用方法。java
主要使用了word里的域,而后选择“邮件合并”,在“域名”处输入你的word变量名,而后在java代码里为这个变量赋值就能够了app
把组件放到resource/lib目录下测试
<dependency> <groupId>com.bdyh.common</groupId> <artifactId>common</artifactId> <version>0.0.1</version> <scope>system</scope> <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath> </dependency>
aspose组件存在受权问题,没有受权的会有水印出现code
private static InputStream license; private static InputStream fileInput; public static void generateApproveForm(HttpServletResponse response, List<CompanyLawyerEducationAddDTO> counterpartDetails) { // 验证License if (!getLicense("templates/companyLawyerApprove.docx")) { return; } try { long old = System.currentTimeMillis(); Document doc = new Document(fileInput); //主要调用aspose.words的邮件合并接口MailMerge //3.1 填充单个文本域 String[] Flds = new String[]{"Title", "Name", "URL", "Note"}; //文本域 Object[] Vals = new Object[]{"标题", "测试", "http://test.com", word模板导出"}; //值 doc.getMailMerge().execute(Flds, Vals); //调用接口 response.setHeader("Content-Disposition", "attachment; filename=审批单.pdf"); response.setContentType("application/octet-stream;charset=UTF-8"); OutputStream output = response.getOutputStream(); doc.save(output, SaveFormat.PDF); output.flush(); output.close(); } public static boolean getLicense(String templateName) { boolean result = false; try { license = new ClassPathResource("lib/license.xml").getInputStream(); fileInput = new ClassPathResource(templateName).getInputStream(); License aposeLic = new License(); aposeLic.setLicense(license); result = true; } catch (Exception e) { e.printStackTrace(); } return result; }
以上模板是最简单的文本域的,若是有兴趣还能够把表格域也放上去,实现列表的输出等。orm