当前位置: 首页 > news >正文

使用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)}
http://www.lryc.cn/news/260286.html

相关文章:

  • 计算机视觉-机器学习-人工智能 顶会会议召开地址
  • GAN的原理分析与实例
  • 什么是POM设计模式?
  • 没有数据线,在手机上查看电脑备忘录怎么操作
  • Elasitcsearch--解决CPU使用率升高
  • vue和jQuery有什么区别
  • [Android] Binder all-in-all
  • 无人零售柜:快捷舒适购物体验
  • Bash script进阶笔记
  • OpenCV图像处理——Python开发中OpenCV视频流的多线程处理方式
  • webGL开发智慧城市流程
  • Django讲课笔记02:Django环境搭建
  • 黑豹程序员-原生JS拖动div到任何地方-自定义布局
  • <软考高项备考>《论文专题 - 7 论文的项目背景之技术架构》
  • 6.3 C++11 原子操作与原子类型
  • 智能优化算法应用:基于狮群算法3D无线传感器网络(WSN)覆盖优化 - 附代码
  • BERT、GPT学习问题个人记录
  • HeartBeat监控Mysql状态
  • 软件开发经常出现的bug原因有哪些
  • 代码随想录27期|Python|Day15|二叉树|层序遍历|对称二叉树|翻转二叉树
  • 鸿蒙开发组件之Web
  • 成绩分析。
  • Excel实现字母+数字拖拉自动递增,步长可更改
  • Java之Stream流
  • vue中element-ui日期选择组件el-date-picker 清空所选时间,会将model绑定的值设置为null 问题 及 限制起止日期范围
  • 使用模方时,三维模型在su中显示不了怎么办?
  • AR-LDM原理及代码分析
  • MySQL常见死锁的发生场景以及如何解决
  • Leetcode 47 全排列 II
  • C# 图解教程 第5版 —— 第18章 泛型