本文主要是介绍aspose.word实现word模板填充转换PDF,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、使用poi-tl实现word模板填充
poi-tl官网:https://deepoove.com/poi-tl/1.6.x/
1.制作word模板,插入图片使用语法{{@urlPicture}}
2.添加pom依赖
<!--生成word--><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.10.0</version></dependency><!-- hutool --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.5.2</version></dependency>
3.word模板填充本地下载
package com.example.mybatismysql8demo.controller;import com.aspose.words.License;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RestController;import java.io.*;
import java.util.*;public class PDFCreateUtil {public static void createWord(){Map<String,Object> map = new HashMap<>();map.put("name","张三");map.put("sex","男");map.put("tel","13255555555");//插入头像图片map.put("urlPicture",Pictures.ofUrl("https://gimg2.baidu.com/image_search/7283743.png").size(100, 100).create());//集合信息//获取物品信息列表List<Map<String,Object>> list = new ArrayList<>();for (int i=1; i <= 3; i++){Map<String,Object> info = new HashMap<>();info.put("name","王" + i);info.put("relation","姐" + i);info.put("tel","1523647634" + i);list.add(info);}map.put("info",list);// 插件列表,可以去官网查看,有列循环,还有行循环,这里是行循环实例LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();//这里可以指定一个config类,用来指定一些规则,也可以改变模板中{{}}的这种格式Configure config = Configure.builder().bind("info", policy).build();//多个list//Configure config = Configure.builder().bind("goods", policy).bind("labors", policy).build();//模板路径String wordTemplate = "E:\\新建文件夹\\info.docx";//模板填充XWPFTemplate template = XWPFTemplate.compile(wordTemplate, config).render(map);//文件夹String directory = "E:\\新建文件夹\\下载\\" + System.currentTimeMillis();//判断文件夹是否存在File filePath = new File(directory);if (!filePath.exists()) {filePath.mkdir();}try {//下载路径String downloadPath = directory + "\\word.docx";template.writeToFile(downloadPath);template.close();} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {createWord();}
}
4.word模板填充浏览器下载
package com.example.mybatismysql8demo.controller;import com.aspose.words.License;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;@RestController
public class PDFCreateController {@RequestMapping("/createWord")public static void createWord(HttpServletResponse response){Map<String,Object> map = new HashMap<>();map.put("name","张三");map.put("sex","男");map.put("tel","13255555555");//插入头像图片map.put("urlPicture",Pictures.ofUrl("https://gimg2.baidu.com/image_search/7283743.png").size(100, 100).create());//集合信息//获取物品信息列表List<Map<String,Object>> list = new ArrayList<>();for (int i=1; i <= 3; i++){Map<String,Object> info = new HashMap<>();info.put("name","王" + i);info.put("relation","姐" + i);info.put("tel","1523647634" + i);list.add(info);}map.put("info",list);// 插件列表,可以去官网查看,有列循环,还有行循环,这里是行循环实例LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();//这里可以指定一个config类,用来指定一些规则,也可以改变模板中{{}}的这种格式Configure config = Configure.builder().bind("info", policy).build();//多个list//Configure config = Configure.builder().bind("goods", policy).bind("labors", policy).build();//模板路径String wordTemplate = "E:\\新建文件夹\\info.docx";//模板填充XWPFTemplate template = XWPFTemplate.compile(wordTemplate, config).render(map);try {//浏览器下载response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("报价报表.docx", StandardCharsets.UTF_8))));template.write(response.getOutputStream());} catch (IOException e) {e.printStackTrace();}}
}
5.word文件生成结果
二、aspose实现word转换为PDF
首先下载aspose-words-15.8.0-jdk16.jar,然后maven手动添加jar包
1.添加pom依赖
<!--word转换为pdf--><dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>15.8.0</version></dependency>
2.破解生成的水印
创建license.xml文件存放在资源文件目录下
<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
3.实现word转换pdf本地下载
package com.example.mybatismysql8demo.controller;import cn.hutool.core.io.FileUtil;
import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;public class PDFCreateUtil {/*** 获取aspose证书 去除水印以及页数限制*/private static boolean getLicense() {boolean result = false;InputStream is = null;try {Resource resource = new ClassPathResource("license.xml");is = resource.getInputStream();License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {throw new IllegalArgumentException("文件转换失败!");}finally {if (is != null) {try {is.close();} catch (IOException e) {throw new IllegalArgumentException("文件转换失败!");}}}return result;}public static void createWord(){Map<String,Object> map = new HashMap<>();map.put("name","张三");map.put("sex","男");map.put("tel","13255555555");//插入头像图片map.put("urlPicture",Pictures.ofUrl("https://gimg2.baidu.com/image_search/7283743.png").size(100, 100).create());//集合信息//获取物品信息列表List<Map<String,Object>> list = new ArrayList<>();for (int i=1; i <= 3; i++){Map<String,Object> info = new HashMap<>();info.put("name","王" + i);info.put("relation","姐" + i);info.put("tel","1523647634" + i);list.add(info);}map.put("info",list);// 插件列表,可以去官网查看,有列循环,还有行循环,这里是行循环实例LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();//这里可以指定一个config类,用来指定一些规则,也可以改变模板中{{}}的这种格式Configure config = Configure.builder().bind("info", policy).build();//多个list//Configure config = Configure.builder().bind("goods", policy).bind("labors", policy).build();//模板路径String wordTemplate = "E:\\新建文件夹\\info.docx";//模板填充XWPFTemplate template = XWPFTemplate.compile(wordTemplate, config).render(map);//文件夹String directory = "";try {directory = "E:\\新建文件夹\\下载\\" + System.currentTimeMillis();//判断文件夹是否存在File filePath = new File(directory);if (!filePath.exists()) {filePath.mkdir();}//下载路径String downloadPath = directory + "\\word.docx";template.writeToFile(downloadPath);//word转换为PDFif (getLicense()) {try (ByteArrayOutputStream fos = new ByteArrayOutputStream()) {//解决乱码String osName = System.getProperty("os.name", "");if (osName.startsWith("Mac OS")) {} else if (osName.startsWith("Windows")) {} else {//如果是linux执行,需要添加这个 ,如果还有乱码,可以把/usr/share/fonts路径下的所有文件拷贝到有问题的环境。并且再执行:source /etc/profileFontSettings.setFontsFolder("/usr/share/fonts",true);}Document document = new Document(downloadPath);//本地下载document.save("E:\\新建文件夹\\word.pdf",SaveFormat.PDF);}}} catch (Exception e) {e.printStackTrace();}finally {//删除文件夹if (StringUtils.isNotEmpty(directory)){FileUtil.del(new File(directory));}}}public static void main(String[] args) {createWord();}
}
4.实现word转换pdf浏览器下载
package com.example.mybatismysql8demo.controller;import cn.hutool.core.io.FileUtil;
import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;@RestController
public class PDFCreateController {/*** 获取aspose证书 去除水印以及页数限制*/private static boolean getLicense() {boolean result = false;InputStream is = null;try {Resource resource = new ClassPathResource("license.xml");is = resource.getInputStream();License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {throw new IllegalArgumentException("文件转换失败!");}finally {if (is != null) {try {is.close();} catch (IOException e) {throw new IllegalArgumentException("文件转换失败!");}}}return result;}@RequestMapping("/createWord")public static void createWord(HttpServletResponse response){Map<String,Object> map = new HashMap<>();map.put("name","张三");map.put("sex","男");map.put("tel","13255555555");//插入头像图片map.put("urlPicture",Pictures.ofUrl("https://gimg2.baidu.com/image_search/7283743.png").size(100, 100).create());//集合信息//获取物品信息列表List<Map<String,Object>> list = new ArrayList<>();for (int i=1; i <= 3; i++){Map<String,Object> info = new HashMap<>();info.put("name","王" + i);info.put("relation","姐" + i);info.put("tel","1523647634" + i);list.add(info);}map.put("info",list);// 插件列表,可以去官网查看,有列循环,还有行循环,这里是行循环实例LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();//这里可以指定一个config类,用来指定一些规则,也可以改变模板中{{}}的这种格式Configure config = Configure.builder().bind("info", policy).build();//多个list//Configure config = Configure.builder().bind("goods", policy).bind("labors", policy).build();//模板路径String wordTemplate = "E:\\新建文件夹\\info.docx";//模板填充XWPFTemplate template = XWPFTemplate.compile(wordTemplate, config).render(map);//文件夹String directory = "";try {directory = "E:\\新建文件夹\\下载\\" + System.currentTimeMillis();//判断文件夹是否存在File filePath = new File(directory);if (!filePath.exists()) {filePath.mkdir();}//下载路径String downloadPath = directory + "\\word.docx";template.writeToFile(downloadPath);//word转换为PDFif (getLicense()) {try (ByteArrayOutputStream fos = new ByteArrayOutputStream()) {//解决乱码String osName = System.getProperty("os.name", "");if (osName.startsWith("Mac OS")) {} else if (osName.startsWith("Windows")) {} else {//如果是linux执行,需要添加这个 ,如果还有乱码,可以把/usr/share/fonts路径下的所有文件拷贝到有问题的环境。并且再执行:source /etc/profileFontSettings.setFontsFolder("/usr/share/fonts",true);}Document document = new Document(downloadPath);document.save(fos, SaveFormat.PDF);//浏览器端下载response.setContentType("application/pdf");response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("报价报表.pdf", StandardCharsets.UTF_8))));byte[] buffer = fos.toByteArray();InputStream arrayInputStream = new ByteArrayInputStream(buffer);byte[] buf = new byte[4096];int len = -1;while ((len = arrayInputStream.read(buf)) != -1) {response.getOutputStream().write(buf, 0, len);}}}} catch (Exception e) {e.printStackTrace();}finally {//删除文件夹if (StringUtils.isNotEmpty(directory)){FileUtil.del(new File(directory));}}}}
这篇关于aspose.word实现word模板填充转换PDF的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!