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

相关文章

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

Nexus安装和启动的实现教程

《Nexus安装和启动的实现教程》:本文主要介绍Nexus安装和启动的实现教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、Nexus下载二、Nexus安装和启动三、关闭Nexus总结一、Nexus下载官方下载链接:DownloadWindows系统根

java Long 与long之间的转换流程

《javaLong与long之间的转换流程》Long类提供了一些方法,用于在long和其他数据类型(如String)之间进行转换,本文将详细介绍如何在Java中实现Long和long之间的转换,感... 目录概述流程步骤1:将long转换为Long对象步骤2:将Longhttp://www.cppcns.c

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte

MySQL 横向衍生表(Lateral Derived Tables)的实现

《MySQL横向衍生表(LateralDerivedTables)的实现》横向衍生表适用于在需要通过子查询获取中间结果集的场景,相对于普通衍生表,横向衍生表可以引用在其之前出现过的表名,本文就来... 目录一、横向衍生表用法示例1.1 用法示例1.2 使用建议前面我们介绍过mysql中的衍生表(From子句

Mybatis的分页实现方式

《Mybatis的分页实现方式》MyBatis的分页实现方式主要有以下几种,每种方式适用于不同的场景,且在性能、灵活性和代码侵入性上有所差异,对Mybatis的分页实现方式感兴趣的朋友一起看看吧... 目录​1. 原生 SQL 分页(物理分页)​​2. RowBounds 分页(逻辑分页)​​3. Page

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis