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

相关文章

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

MySQL更新某个字段拼接固定字符串的实现

《MySQL更新某个字段拼接固定字符串的实现》在MySQL中,我们经常需要对数据库中的某个字段进行更新操作,本文就来介绍一下MySQL更新某个字段拼接固定字符串的实现,感兴趣的可以了解一下... 目录1. 查看字段当前值2. 更新字段拼接固定字符串3. 验证更新结果mysql更新某个字段拼接固定字符串 -

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

在Android平台上实现消息推送功能

《在Android平台上实现消息推送功能》随着移动互联网应用的飞速发展,消息推送已成为移动应用中不可或缺的功能,在Android平台上,实现消息推送涉及到服务端的消息发送、客户端的消息接收、通知渠道(... 目录一、项目概述二、相关知识介绍2.1 消息推送的基本原理2.2 Firebase Cloud Me

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

Redis实现延迟任务的三种方法详解

《Redis实现延迟任务的三种方法详解》延迟任务(DelayedTask)是指在未来的某个时间点,执行相应的任务,本文为大家整理了三种常见的实现方法,感兴趣的小伙伴可以参考一下... 目录1.前言2.Redis如何实现延迟任务3.代码实现3.1. 过期键通知事件实现3.2. 使用ZSet实现延迟任务3.3

基于Python和MoviePy实现照片管理和视频合成工具

《基于Python和MoviePy实现照片管理和视频合成工具》在这篇博客中,我们将详细剖析一个基于Python的图形界面应用程序,该程序使用wxPython构建用户界面,并结合MoviePy、Pill... 目录引言项目概述代码结构分析1. 导入和依赖2. 主类:PhotoManager初始化方法:__in

springboot filter实现请求响应全链路拦截

《springbootfilter实现请求响应全链路拦截》这篇文章主要为大家详细介绍了SpringBoot如何结合Filter同时拦截请求和响应,从而实现​​日志采集自动化,感兴趣的小伙伴可以跟随小... 目录一、为什么你需要这个过滤器?​​​二、核心实现:一个Filter搞定双向数据流​​​​三、完整代码