使用poi-tl填充word模板,并转化为pdf输出

2023-12-09 05:20

本文主要是介绍使用poi-tl填充word模板,并转化为pdf输出,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

后端

依赖

<dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.12.0</version>
</dependency>

Word版本

Word版本填充代码

		// 培训详情HashMap<String, Object> textMap = new HashMap<>();textMap.put("projectNo", projectInitiation.getProjectNo());textMap.put("projectName", projectInitiation.getProjectName());textMap.put("organization1", organization.getName());textMap.put("email", Objects.isNull(user.getEmail()) ? "" : user.getEmail());textMap.put("headPhone", Objects.isNull(deviceManage.getHeadPhone()) ? "" : deviceManage.getHeadPhone());// 查看培训人员(扫码查看)QrConfig config = new QrConfig(300, 300);// 设置边距,既二维码和背景之间的边距config.setMargin(3);HashMap<String, String> qrMap = new HashMap<>();qrMap.put("type", RandomUtil.randomString(5));qrMap.put("data", AESUtils.encodeBase64(String.valueOf(visitationTask.getId())));String qr = QrCodeUtil.generateAsBase64(JsonUtils.objectToJsonString(qrMap), config, ImgUtil.IMAGE_TYPE_JPG);textMap.put("detailPages", Pictures.ofBase64(qr, PictureType.JPEG).size(100, 100).create());// 选中textMap.put("redio", "\u2611");textMap.put("customerSignature", Objects.isNull(cultivateDetail.getCustomerSignature()) ? "" : Pictures.ofUrl(cultivateDetail.getCustomerSignature(), PictureType.JPEG).size(100, 50).create());textMap.put("engineerSignature", Objects.isNull(cultivateDetail.getEngineerSignature()) ? "" : Pictures.ofUrl(cultivateDetail.getEngineerSignature(), PictureType.JPEG).size(100, 50).create());// 获取文件流try {InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/培训服务报告.docx");XWPFTemplate template = XWPFTemplate.compile(inputStream).render(textMap);Map<String, Object> map = new HashMap<>();ByteArrayOutputStream fos = new ByteArrayOutputStream();template.write(fos);byte[] bytes = fos.toByteArray();byte[] convertToPdf = Doc2PdfUtil.doc2Pdf(bytes);String bytesRes = StringUtils.bytesToHexString2(convertToPdf);map.put("bytes", bytesRes);map.put("title", System.currentTimeMillis() + "培训服务报告.docx");fos.close();template.close();return Response.successJson(map);} catch (Exception e) {throw new RuntimeException(e);}

pdf版本

依赖

		<!--aspose 破解 word转pdf--><dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>16.8.0-jdk16</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose-words-16.8.0-jdk16.jar</systemPath></dependency>

license放到resources下面 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>

word转pdf工具类

package com.gangwantech.web.utils;import com.aspose.words.*;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;public class Doc2PdfUtil {/*** 加载授权配置文件** @return*/private static boolean getLicense() {boolean result = false;try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("license.xml")) {// License的包路径必须为com.aspose.words.LicenseLicense license = new License();license.setLicense(in);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** doc转pdf** @return*/public static byte[] doc2Pdf(byte[] bytes) {System.out.println("pdf转换中...");long old = System.currentTimeMillis();try (ByteArrayOutputStream fos = new ByteArrayOutputStream()) {// 验证if (!getLicense()) {throw new RuntimeException("文件转换失败!");}// 加载字体//FontSettings settings = FontSettings.getDefaultInstance();//String[] fontFamilyNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();//settings.setFontsFolders(fontFamilyNames, true);//LoadOptions loadOptions = new LoadOptions();//loadOptions.setFontSettings(settings); 加载字体//FontSettings settings = FontSettings.getDefaultInstance();//settings.setFontsFolder("C:\\Windows\\Fonts", true);//LoadOptions loadOptions = new LoadOptions();//loadOptions.setFontSettings(settings);ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);//Document document = new Document(inputStream, loadOptions);Document document = new Document(inputStream);document.save(fos, SaveFormat.PDF);byte[] buffer = fos.toByteArray();long now = System.currentTimeMillis();System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");return buffer;} catch (Exception e) {e.printStackTrace();throw new RuntimeException("文件转换失败!");}}
}

pdf版本填充代码,并生成pdf下载

		// 培训详情CultivateDetail cultivateDetail = cultivateDetailService.selectOne(new QueryWrapper<CultivateDetail>().eq("work_id", visitationTask.getWorkOrderId()));HashMap<String, Object> textMap = new HashMap<>();textMap.put("projectNo", projectInitiation.getProjectNo());textMap.put("projectName", projectInitiation.getProjectName());// 查看培训人员(扫码查看)QrConfig config = new QrConfig(300, 300);// 设置边距,既二维码和背景之间的边距config.setMargin(3);HashMap<String, String> qrMap = new HashMap<>();qrMap.put("type", RandomUtil.randomString(5) + "train");qrMap.put("data", AESUtils.encodeBase64(String.valueOf(visitationTask.getId())));String qr = QrCodeUtil.generateAsBase64(JsonUtils.objectToJsonString(qrMap), config, ImgUtil.IMAGE_TYPE_JPG);textMap.put("detailPages", Pictures.ofBase64(qr, PictureType.JPEG).size(100, 100).create());// 选中textMap.put("redio", "\u2611");textMap.put("customerSignature", Objects.isNull(cultivateDetail.getCustomerSignature()) ? "" : Pictures.ofUrl(cultivateDetail.getCustomerSignature(), PictureType.JPEG).size(100, 50).create());textMap.put("engineerSignature", Objects.isNull(cultivateDetail.getEngineerSignature()) ? "" : Pictures.ofUrl(cultivateDetail.getEngineerSignature(), PictureType.JPEG).size(100, 50).create());// 获取文件流try {InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/培训服务报告.docx");XWPFTemplate template = XWPFTemplate.compile(inputStream).render(textMap);Map<String, Object> map = new HashMap<>();ByteArrayOutputStream fos = new ByteArrayOutputStream();template.write(fos);byte[] bytes = fos.toByteArray();byte[] convertToPdf = Doc2PdfUtil.doc2Pdf(bytes);String bytesRes = StringUtils.bytesToHexString2(convertToPdf);map.put("bytes", bytesRes);map.put("title", System.currentTimeMillis() + "培训服务报告.docx");fos.close();template.close();return Response.successJson(map);} catch (Exception e) {throw new RuntimeException(e);}

前端下载方法

word下载

		if (res.data.code === 0) {const data = res.data.dataconst bytes = hexStr2Byte(data.bytes)const blob = new Blob([bytes], {type: `application/vnd.openxmlformats-officedocument.wordprocessingml.document`})const objectUrl = URL.createObjectURL(blob)const link = document.createElement('a')link.href = objectUrllink.setAttribute('download', data.title)document.body.appendChild(link)link.click()} else {this.$message.error(res.data.msg)}

pdf下载

		  const data = res.data.dataconst bytes = hexStr2Byte(data.bytes)const blob = new Blob([bytes], {type: `application/pdf`})const objectUrl = URL.createObjectURL(blob)const link = document.createElement('a')link.href = objectUrllink.setAttribute('download', `${data.title}.pdf`)document.body.appendChild(link)link.click()} else {this.$message.error(res.data.msg)}

这篇关于使用poi-tl填充word模板,并转化为pdf输出的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

C#中checked关键字的使用小结

《C#中checked关键字的使用小结》本文主要介绍了C#中checked关键字的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录✅ 为什么需要checked? 问题:整数溢出是“静默China编程”的(默认)checked的三种用

C#中预处理器指令的使用小结

《C#中预处理器指令的使用小结》本文主要介绍了C#中预处理器指令的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录 第 1 名:#if/#else/#elif/#endif✅用途:条件编译(绝对最常用!) 典型场景: 示例

Mysql中RelayLog中继日志的使用

《Mysql中RelayLog中继日志的使用》MySQLRelayLog中继日志是主从复制架构中的核心组件,负责将从主库获取的Binlog事件暂存并应用到从库,本文就来详细的介绍一下RelayLog中... 目录一、什么是 Relay Log(中继日志)二、Relay Log 的工作流程三、Relay Lo

使用Redis实现会话管理的示例代码

《使用Redis实现会话管理的示例代码》文章介绍了如何使用Redis实现会话管理,包括会话的创建、读取、更新和删除操作,通过设置会话超时时间并重置,可以确保会话在用户持续活动期间不会过期,此外,展示了... 目录1. 会话管理的基本概念2. 使用Redis实现会话管理2.1 引入依赖2.2 会话管理基本操作

Python自动化提取多个Word文档的文本

《Python自动化提取多个Word文档的文本》在日常工作和学习中,我们经常需要处理大量的Word文档,本文将深入探讨如何利用Python批量提取Word文档中的文本内容,帮助你解放生产力,感兴趣的小... 目录为什么需要批量提取Word文档文本批量提取Word文本的核心技术与工具安装 Spire.Doc

Springboot请求和响应相关注解及使用场景分析

《Springboot请求和响应相关注解及使用场景分析》本文介绍了SpringBoot中用于处理HTTP请求和构建HTTP响应的常用注解,包括@RequestMapping、@RequestParam... 目录1. 请求处理注解@RequestMapping@GetMapping, @PostMappin

springboot3.x使用@NacosValue无法获取配置信息的解决过程

《springboot3.x使用@NacosValue无法获取配置信息的解决过程》在SpringBoot3.x中升级Nacos依赖后,使用@NacosValue无法动态获取配置,通过引入SpringC... 目录一、python问题描述二、解决方案总结一、问题描述springboot从2android.x

C#高效实现在Word文档中自动化创建图表的可视化方案

《C#高效实现在Word文档中自动化创建图表的可视化方案》本文将深入探讨如何利用C#,结合一款功能强大的第三方库,实现在Word文档中自动化创建图表,为你的数据呈现和报告生成提供一套实用且高效的解决方... 目录Word文档图表自动化:为什么选择C#?从零开始:C#实现Word文档图表的基本步骤深度优化:C

SpringBoot整合AOP及使用案例实战

《SpringBoot整合AOP及使用案例实战》本文详细介绍了SpringAOP中的切入点表达式,重点讲解了execution表达式的语法和用法,通过案例实战,展示了AOP的基本使用、结合自定义注解以... 目录一、 引入依赖二、切入点表达式详解三、案例实战1. AOP基本使用2. AOP结合自定义注解3.

Python中Request的安装以及简单的使用方法图文教程

《Python中Request的安装以及简单的使用方法图文教程》python里的request库经常被用于进行网络爬虫,想要学习网络爬虫的同学必须得安装request这个第三方库,:本文主要介绍P... 目录1.Requests 安装cmd 窗口安装为pycharm安装在pycharm设置中为项目安装req