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

相关文章

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

Java操作Word文档的全面指南

《Java操作Word文档的全面指南》在Java开发中,操作Word文档是常见的业务需求,广泛应用于合同生成、报表输出、通知发布、法律文书生成、病历模板填写等场景,本文将全面介绍Java操作Word文... 目录简介段落页头与页脚页码表格图片批注文本框目录图表简介Word编程最重要的类是org.apach