JAVA实现向Word模板中插入Base64图片和数据信息

news2024/9/29 13:17:29

目录

    • 需求
    • 一、准备模板文件
    • 二、引入Poi-tl、Apache POI依赖
    • 三、创建实体类(用于保存向Word中写入的数据)
    • 四、实现Service接口
    • 五、Controller层实现

需求

在服务端提前准备好Word模板文件,并在用户请求接口时服务端动态获取图片。数据等信息插入到模板当中,然后返回包含数据信息的Word文件流。

一、准备模板文件

在需要插入图片的地方使用:{{@参数名}},文本信息使用:{{参数名}},进行占位,占位格式将会被保留,经过处理后格式不变

在这里插入图片描述

将准备好的模板文件放在resources目录下

blog.csdnimg.cn/direct/6d1474091083427483e11ea71e25ef51.png)

二、引入Poi-tl、Apache POI依赖

poi-tl(poi template language)是Word模板引擎,基于Apache POI,提供更友好的API,使用起来更加简单
版本对应关系参考Poi-tl官网

<!--    替换自己使用的版本    -->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>4.1.*</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>4.1.*</version>
</dependency>
<!--    Word模板引擎    -->
<dependency>
	<groupId>com.deepoove</groupId>
	<artifactId>poi-tl</artifactId>
	<version>1.7.*</version>
</dependency>

三、创建实体类(用于保存向Word中写入的数据)

参数名必须同Word模板中的参数名称保持一致

import com.deepoove.poi.data.PictureRenderData;

@Data
public class DownloadDate {
    //图片使用PictureRenderData类型
    private PictureRenderData image;
    
    private String name;

    private String a;

    private String b;

    private String c;

    private String d;

    private String e;

    private String f;

    private String g;

    private String h;
    
    private String i;
}

四、实现Service接口

public interface DownloadService {
     void download(HttpServletResponse response, DownloadDTO downloadDTO) throws IOException;
}

@Service
@Slf4j
public class DownloadServiceImpl implements DownloadService {

    @Resource
    //远程调用服务
    private FeignService feignService;
    
    @Override
    public void download(HttpServletResponse response, DownloadDTO downloadDTO) throws IOException {BufferedImage、字节数组),Base64可以转字节数组后使用
    	//通过调用其它接口获取待写入的数据信息
    	WordData wordData = feignService.getData(downloadDTO);
        /** 
        * 图片可以是多种格式------------------------
        * 图片路径:PictureRenderData(int width, int height, String path)
        * File:PictureRenderData(int width, int height, File picture)
        * InputStream:PictureRenderData(int width, int height, String format, InputStream input)
        * BufferedImage:PictureRenderData(int width, int height, String format, BufferedImage image)
        * 字节数组:PictureRenderData(int width, int height, String format, byte[] data)
        * Base64可以转字节数组后使用
        */

        //以Base64为例,先获取图片的Base64编码(wordData.getImg是原始图片Base64数据)
        String base64ImageData = wordData.getImg.substring(data.indexOf(",") + 1);
        //获取图片类型
        String format = getBase64Type(base64ImageData);
        // 将base64数据转为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64ImageData);
        // 将字节数组包装成PictureRenderData
        PictureRenderData pictureRenderData = new PictureRenderData(690,530,format,imageBytes);
        //待写入Word的数据
        DownloadDate downloadDate = new DownloadDate();
        //图片信息
        downloadDate.setImage(pictureRenderData);
        //其它信息
        downloadDate.setName(wordData.getName());
        //...
        XWPFTemplate template = null;
        BufferedOutputStream bufferedOutputStream = null;
        ServletOutputStream outputStream = null;
        try {
        	/** 
        	* 该方法会导致在部分环境中资源找不到的情况,不推荐使用
        	*/
            //获得resource路径+模板路径
            //String path = Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).getPath() + "word/template.docx";
            // 读取Word模板
            //FileInputStream templateInputStream = new FileInputStream(path);
            // 模板绑定数据
            //template = XWPFTemplate.compile(templateInputStream).render(imageDownloadDate);
            
            // 从资源中加载Word模板
            try (InputStream templateInputStream = getClass().getClassLoader().getResourceAsStream("word/template.docx")) {
                if (templateInputStream != null) {
                    // 模板绑定数据
                    template = XWPFTemplate.compile(templateInputStream).render(imageDownloadDate);
                } else {
                    // 处理模板资源未找到的情况
                    log.error("Word模板资源未找到");
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    return;
                }
            }
            //文件名
            String encodedFileName = URLEncoder.encode(System.currentTimeMillis()+"", "utf-8");
            //设置响应信息
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName + ".docx");
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setCharacterEncoding("utf-8");
            outputStream = response.getOutputStream();
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            template.write(bufferedOutputStream);
            //清空流
            bufferedOutputStream.flush();
            outputStream.flush();
        } catch (Exception e) {
            log.info(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            //关闭资源
            PoitlIOUtils.closeQuietlyMulti(template, bufferedOutputStream, outputStream);
        }
    }
    
    //根据base64编码获取图片格式信息
    private String getBase64Type(String base64) {
        byte[] b = Base64.getDecoder().decode(base64);
        String type = ".png";
        if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".bmp";
        } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".png";
        } else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".jpg";
        } else if (0x49492A00 == ((b[0] & 0xff) << 24 | (b[1] & 0xff) << 16 | (b[2] & 0xff) << 8 | (b[3] & 0xff))) {
            type = ".tif";
        }
        return type;
    }

}

五、Controller层实现

@RestController
@RequestMapping("/test")
@Api(tags = "获取商品图片")
public class GetImageController {

    @Resource
    DownloadService downloadService;

    @PostMapping("/download")
    @ApiOperation(value = "下载Word")
    void download(HttpServletResponse response,@RequestBody DownloadDTO downloadDTO) throws IOException {
        //鉴权或其它处理
        //....
        downloadService.download(response,downloadDTO);
    }
    
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1396131.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Week-P5】CNN运动鞋品牌识别

文章目录 一、环境配置二、准备数据三、搭建网络结构四、开始训练五、查看训练结果六、总结6.1 torch.optim.lr_scheduler.StepLR 等间隔动态调整6.2 lr_scheduler.LambdaLR 自定义学习率更新函数6.3 lr_scheduler.MultiStepLR 特定epoch中调整学习率6.4 本文四种学习率方法得到…

详细的说说mfc110u.dll丢失的解决方法分享,四种解决办法的详细步骤

在电脑运行过程中&#xff0c;有时会遇到各种各样的错误提示&#xff0c;比如“由于找不到mfc110u.dll&#xff0c;无法继续执行代码”&#xff0c;这不仅令人困扰&#xff0c;也影响了我们的工作和娱乐体验。如果你也在为mfc110u.dll缺失问题感到苦恼&#xff0c;那么你来对地…

Ubuntu重启后进入initramfs导致无法开机

今晚&#xff0c;我的电脑意外关机&#xff0c;重新开机后打开了虚拟机后出现initramfs&#xff0c;一直无法开机。该虚拟机使用的是 vm17,系统是ubuntu20, 解决方案 使用如下命令查看和识别磁盘、分区或文件系统的信息 在initramfs后面输入 fsck /dev/sdb4 ,即修复上面损坏的…

非线性最小二乘问题的数值方法 —— 狗腿法 Powell‘s Dog Leg Method (I - 原理与算法)

Title: 非线性最小二乘问题的数值方法 —— 狗腿法 Powell’s Dog Leg Method (I - 原理与算法) 文章目录 I. 前言II. 线搜索类型和信赖域类型1. 线搜索类型 —— 最速下降法2. 信赖域类型3. 柯西点 III. 狗腿法的原理1. 狗腿法的构建2. 狗腿法的优化说明3. 狗腿法的插值权重 I…

Spring Security 优化鉴权注解:自定义鉴权注解的崭新征程

文章目录 1. 引言2. Spring Security基础2.1 Spring Security概述2.2 PreAuthorize注解 3. 自定义鉴权注解的优势3.1 业务语义更明确3.2 参数化鉴权更灵活3.3 可维护性更好 4. 实现自定义鉴权注解4.1 创建自定义注解4.2 实现鉴权逻辑4.3 注册自定义注解和逻辑4.4 使用自定义注解…

去掉element-ui的el-table的所有边框+表头+背景颜色

实例: 1.去掉table表头(加上:show-header"false") <el-table:data"tableData":show-header"false"style"width: 100%"> </el-table> 2.去掉table所有边框 ::v-deep .el-table--border th.el-table__cell, ::v-deep .el…

.NetCore Flurl.Http 升级到4.0后 https 无法建立SSL连接

Flurl.Http-3.2.4 升级到 4.0.0 版本后&#xff0c;https请求异常&#xff1a;Call failed. The SSL connection could not be established. 如下图&#xff1a; Flurl.Http-3.2.4版本绕过https的代码&#xff0c;对于 Flurl.Http-4.0.0 版本来说方法不再适用&#xff0c;3.2.…

如何定义眼图测试模板

设计眼图模板时所需的参数列举如下&#xff1a; TCLK clock period&#xff0c;时钟周期&#xff1b;TSKEW the difference between the clock and data propagation time&#xff0c;时钟和数据之间的偏斜&#xff0c;默认为0&#xff1b;TJITTER clock data jitter (pea…

代码随想录 Leetcode459. 重复的子字符串(KMP算法)

题目&#xff1a; 代码&#xff08;首刷看解析 KMP算法 2024年1月18日&#xff09;&#xff1a; class Solution { public:void getNext(string& s,vector<int>& next) {int j 0;next[0] j;for (int i 1; i < s.size(); i) {while (j > 0 && s…

leetcode:1736. 替换隐藏数字得到的最晚时间(python3解法)

难度&#xff1a;简单 给你一个字符串 time &#xff0c;格式为 hh:mm&#xff08;小时&#xff1a;分钟&#xff09;&#xff0c;其中某几位数字被隐藏&#xff08;用 ? 表示&#xff09;。 有效的时间为 00:00 到 23:59 之间的所有时间&#xff0c;包括 00:00 和 23:59 。 …

【Qt】安装及环境搭建

概述&#xff1a;1. 搭建《QtCreator快速入门》一书中所使用的Qt版本qt6.2.3 文章目录 1 安装2 环境变量设置 1 安装 先下载下载器&#xff0c;然后在下载器中选择自己需要的版本下载并安装&#xff0c;有点像 LOL 下载器&#xff0c;先下个小的&#xff0c;然后再在这个下载器…

芯品荟 | 酒精测试仪市场调研报告

产品简介 酒精检测仪是一种可以测量人体酒精浓度的电子设备。 它可以通过呼气或血液等方式来检测酒精浓度&#xff0c;被广泛应用于交通安全、职业健康等领域。 酒精检测仪的工作原理&#xff1a; 1、酒精检测仪分为2种&#xff0c;基于化学传感器与基于光学传感器&#xff…

RDMA Scatter Gather List详解

1. 前言 在使用RDMA操作之前&#xff0c;我们需要了解一些RDMA API中的一些需要的值。其中在ibv_send_wr我们需要一个sg_list的数组&#xff0c;sg_list是用来存放ibv_sge元素&#xff0c;那么什么是SGL以及什么是sge呢&#xff1f;对于一个使用RDMA进行开发的程序员来说&#…

Docker(三)使用 Docker 镜像:从仓库获取镜像;管理本地主机上的镜像;介绍镜像实现的基本原理

作者主页&#xff1a; 正函数的个人主页 文章收录专栏&#xff1a; Docker 欢迎大家点赞 &#x1f44d; 收藏 ⭐ 加关注哦&#xff01; 使用 Docker 镜像 在之前的介绍中&#xff0c;我们知道镜像是 Docker 的三大组件之一。 Docker 运行容器前需要本地存在对应的镜像&#x…

牛客周赛 Round 15 解题报告 | 珂学家 | 状态DP构造 + 树形DP

前言 整体评价 这场T3挺有意思的&#xff0c;只会3维状态DP进行构造。不过这题其实是脑筋急转弯&#xff0c;有规律可循。 T4是经典的树形DP&#xff0c;从比赛来看&#xff0c;T3难于T4. A. 游游的整数切割 枚举遍历就行&#xff0c;需要满足前后两段其末尾的元素奇偶一致 …

Docker 与 Linux Cgroups:资源隔离的魔法之旅

这篇文章主要介绍了 Docker 如何利用 Linux 的 Control Groups&#xff08;cgroups&#xff09;实现容器的资源隔离和管理。 最后通过简单 Demo 演示了如何使用 Go 和 cgroups 交互。 如果你对云原生技术充满好奇&#xff0c;想要深入了解更多相关的文章和资讯&#xff0c;欢迎…

Python OpenCV 影像处理:影像二值化

► 前言 本篇将介绍使用OpenCV Python对于图像上的二值化操作&#xff0c;二值化主要用途包括图像分割、物体侦测、文字识别等。这种转换可以帮助检测图像中的物体或特定特征&#xff0c;并提取有用的信息。透过程式码的说明&#xff0c;让各位了解OpenCV Python于图像处理上的…

mysql安装及部署

1.在/usr/local下创建mysql目录 cd /usr/local mkdir /mysql 2.在mysql目录中下载 cd mysql/ wget https://cdn.mysql.com/archives/mysql-8.0/mysql-8.0.34-1.el9.x86_64.rpm-bundle.tar 3.解压 tar xvf mysql-8.0.34-1.el9.x86_64.rpm-bundle.tar 4.安装 dnf localinst…

JS-WebAPIs-元素尺寸与位置(三)

使用场景&#xff1a; 前面案例滚动多少距离&#xff0c;都是我们自己算的&#xff0c;最好是页面滚动到某个元素&#xff0c;就可以做某些事。简单说&#xff0c;就是通过js的方式&#xff0c;得到元素在页面中的位置这样我们可以做&#xff0c;页面滚动到这个位置&#xff0…

137基于matlab的面和线接触的滑块润滑

基于matlab的面和线接触的滑块润滑&#xff0c;基于有限差分法求解面接触滑块润滑的油膜厚度、油膜压力&#xff0c;输出三维可视化结果。程序已调通&#xff0c;可直接运行。 137 matlab油膜压力油膜厚度 (xiaohongshu.com)