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

使用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.License
            License 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.data
          const 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 = objectUrl
          link.setAttribute('download', data.title)
          document.body.appendChild(link)
          link.click()
        } else {
          this.$message.error(res.data.msg)
        }

pdf下载

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

http://www.kler.cn/a/162982.html

相关文章:

  • HTML之表单学习记录
  • 使用Python实现定期从API获取数据并存储到数据库的完整指南
  • 类别变量分析——卡方独立性检验卡方拟合优度检验
  • ubuntu ros 解决建完图后 保存的地图非常小的问题
  • vxe-table 3.10+ 进阶高级用法(一),根据业务需求自定义实现筛选功能
  • 深度学习之 LSTM
  • 从根上理解elasticsearch(lucene)查询原理(1)-lucece查询逻辑介绍
  • Python与ArcGIS系列(十六)重复节点检测
  • 【Java用法】Hutool树结构工具-TreeUtil快速构建树形结构的两种方式 + 数据排序
  • Navicat 技术指引 | 连接 GaussDB 分布式
  • RocketMQ-RocketMQ高性能核心原理(流程图)
  • Docker的安装与简单操作命令
  • CSS——标准流、浮动、Flex布局
  • GO设计模式——7、适配器模式(结构型)
  • SAP UI5 walkthrough step7 JSON Model
  • 伦茨科技宣布ST17H6x芯片已通过Apple Find My「查找」认证
  • HTML5 Audio/Video 标签、属性、方法、事件汇总(详细)
  • 目标检测器技术演进简史
  • 3D点云:平面模型上提取凸(凹)多边形方法
  • jenkins中“Jenkins Plot Plugin”的使用方法,比较两个excel的数据差异
  • LeetCode124.二叉树中最大路径和
  • 微信小程序 - 格式化操作 moment.js格式化常用使用方法总结大全
  • 代理IP怎么使用?Mac苹果系统设置http代理IP教程
  • react-photo-view 的介绍、安装、使用。
  • HarmonyOS鸿蒙操作系统架构开发
  • Gitleaks - 一款高效的Github仓库敏感信息泄露查询工具