aspose.word实现word模板填充转换PDF

2024-03-19 12:50

本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/826051

相关文章

C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)

《C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)》本文主要介绍了C#集成DeepSeek模型实现AI私有化的方法,包括搭建基础环境,如安装Ollama和下载DeepS... 目录前言搭建基础环境1、安装 Ollama2、下载 DeepSeek R1 模型客户端 ChatBo

Qt实现发送HTTP请求的示例详解

《Qt实现发送HTTP请求的示例详解》这篇文章主要为大家详细介绍了如何通过Qt实现发送HTTP请求,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、添加network模块2、包含改头文件3、创建网络访问管理器4、创建接口5、创建网络请求对象6、创建一个回复对

C++实现回文串判断的两种高效方法

《C++实现回文串判断的两种高效方法》文章介绍了两种判断回文串的方法:解法一通过创建新字符串来处理,解法二在原字符串上直接筛选判断,两种方法都使用了双指针法,文中通过代码示例讲解的非常详细,需要的朋友... 目录一、问题描述示例二、解法一:将字母数字连接到新的 string思路代码实现代码解释复杂度分析三、

grom设置全局日志实现执行并打印sql语句

《grom设置全局日志实现执行并打印sql语句》本文主要介绍了grom设置全局日志实现执行并打印sql语句,包括设置日志级别、实现自定义Logger接口以及如何使用GORM的默认logger,通过这些... 目录gorm中的自定义日志gorm中日志的其他操作日志级别Debug自定义 Loggergorm中的

Spring Boot整合消息队列RabbitMQ的实现示例

《SpringBoot整合消息队列RabbitMQ的实现示例》本文主要介绍了SpringBoot整合消息队列RabbitMQ的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的... 目录RabbitMQ 简介与安装1. RabbitMQ 简介2. RabbitMQ 安装Spring

Gin框架中的GET和POST表单处理的实现

《Gin框架中的GET和POST表单处理的实现》Gin框架提供了简单而强大的机制来处理GET和POST表单提交的数据,通过c.Query、c.PostForm、c.Bind和c.Request.For... 目录一、GET表单处理二、POST表单处理1. 使用c.PostForm获取表单字段:2. 绑定到结

springMVC返回Http响应的实现

《springMVC返回Http响应的实现》本文主要介绍了在SpringBoot中使用@Controller、@ResponseBody和@RestController注解进行HTTP响应返回的方法,... 目录一、返回页面二、@Controller和@ResponseBody与RestController

nginx中重定向的实现

《nginx中重定向的实现》本文主要介绍了Nginx中location匹配和rewrite重定向的规则与应用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下... 目录一、location1、 location匹配2、 location匹配的分类2.1 精确匹配2

Nginx之upstream被动式重试机制的实现

《Nginx之upstream被动式重试机制的实现》本文主要介绍了Nginx之upstream被动式重试机制的实现,可以通过proxy_next_upstream来自定义配置,具有一定的参考价值,感兴... 目录默认错误选择定义错误指令配置proxy_next_upstreamproxy_next_upst

nginx生成自签名SSL证书配置HTTPS的实现

《nginx生成自签名SSL证书配置HTTPS的实现》本文主要介绍在Nginx中生成自签名SSL证书并配置HTTPS,包括安装Nginx、创建证书、配置证书以及测试访问,具有一定的参考价值,感兴趣的可... 目录一、安装nginx二、创建证书三、配置证书并验证四、测试一、安装nginxnginx必须有"-