Java word文档转图片 || word转pdf两行代码搞定

1 篇文章 0 订阅
1 篇文章 0 订阅

目录

一、首先引入我们需要的依赖。

二、准备一个word文档模板,使用{{}}定义我们需要填充的数据。

三、word文档动态数据填充转换图片demo示例

四、poi-tl(poi template language)Word模板引擎

五、把demo示例简化封装成Controller接口层

六、word文档生成动态数据转换成pdf


一、首先引入我们需要的依赖。

<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.8.0</version>
</dependency>
<dependency>
    <groupId>com.luhuiguo</groupId>
    <artifactId>aspose-words</artifactId>
    <version>23.1</version>
</dependency>

二、准备一个word文档模板,使用{{}}定义我们需要填充的数据。

eb5a5952d71c4a48bf6ab4d1253c3ad1.png

 三、word文档动态数据填充转换图片demo示例

package com.valueguard.web;

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.deepoove.poi.XWPFTemplate;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 行舟668
 * @Description: word转图片
 * @date 2023/6/20 15:58
 */
public class Demo {

    public static void main(String[] args) throws Exception {
        // word文档名称,我把他放在项目resources文件下
        String name = "fofpa-cert-template.docx";
        // 读取resources文件下 Word 模板文件
        InputStream ins = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
        // 使用模板引擎将模板渲染,并传入一个数据映射表 initWordMap()。
        XWPFTemplate template = XWPFTemplate.compile(ins).render(initWordMap());
        // 将模板渲染后保存为新的 Word 文件
        template.writeToFile("test.docx");

        // 填充数据完毕的test.docx,在转换成图片
        File file1 = new File("test.docx");
        String filename = file1.getName();
        // 打开生成的 Word 文件
        Document doc = new Document(new FileInputStream(file1));
        String pathPre = filename.substring(0, filename.lastIndexOf("."));
        // 逐页将 Word 文件保存为图片(PNG格式)
        for (int i = 0; i < doc.getPageCount(); i++) {
            Document extractedPage = doc.extractPages(i,1);
            // 拼接上文件名 test1.png
            String path = pathPre + (i + 1) + ".png";
            // 将 Word 文件保存为图片PNG格式
            extractedPage.save(path, SaveFormat.PNG);
        }
    }

    /**
     * word文档需要填充的数据
     * @return
     */
    private static Map<String, Object> initWordMap() {
        Map<String, Object> wordData = new HashMap<>();
        wordData.put("id", "2023001");
        wordData.put("companyName", "xxxxx有限公司");
        wordData.put("companyNameEN", "Shenzhen Taihe Tianjian Technology Co., LTD");
        wordData.put("expiryDate", "2022年 至 2023年");
        wordData.put("expiryDateEN", "From 2022 to 2023");
        return wordData;
    }
}

 运行后生成一个填充完数据的test.docx文档,还有一个test.docx转换成功test1.png图片

0a794743ee57457084652894dd49b8a4.png

 成功后的效果

b60a9eb9805d42d1a6779fbb471d6649.png

 四、poi-tl(poi template language)Word模板引擎

        poi-ti是一个基于Apache POIWord模板引擎,也是一个免费开源的Java类库。它提供了简单而强大的API,使得处理和创建Office文档变得更加容易。您可以使用该库来生成和修改各种类型的文档,并添加表格、图表、图片、样式等。

感兴趣的小伙伴可以了解一下:Poi-tl Documentation

五、把demo示例简化封装成Controller接口层

package com.controller.member;

import cn.hutool.core.io.FileUtil;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.deepoove.poi.XWPFTemplate;
import com.valueguard.common.config.ValueGuardConfig;
import com.valueguard.common.constant.Constants;
import com.valueguard.common.core.controller.BaseController;
import com.valueguard.common.core.domain.AjaxResult;
import com.valueguard.common.utils.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 行舟668、
 * @Description: 测试controller接口
 * @date 2023/6/20 18:33
 */
@RestController
@RequestMapping("/test")
public class MainController extends BaseController {
    
    @GetMapping("word-to-images")
    public AjaxResult test() throws Exception
    {
        String name = "fofpa-cert-template.docx";
        // 读取resources文件下 Word 模板文件
        InputStream ins = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
        // 使用模板引擎将模板渲染,并传入一个数据映射表 initWordMap()。
        XWPFTemplate template = XWPFTemplate.compile(ins).render(initWordMap());
        //不存在则创建目录
        FileUtil.mkdir(ValueGuardConfig.geCertUploadPath());
        // 上传路径Users/admin/project/logs/valueguard/uploadPath/cert/test.docx
        String tmpFilePath = ValueGuardConfig.geCertUploadPath() + "/test.docx";
        // 填充完数据后保持到上面路径
        template.writeToFile(tmpFilePath);

        // 上传保存到/Users/admin/project/logs/valueguard/uploadPath/cert/test.jpeg
        String jpgFilePath = ValueGuardConfig.geCertUploadPath() + "/test.jpeg";
        // 打开生成的 Word 文件
        Document doc = new Document(new FileInputStream(new File(tmpFilePath)));
        // 方式一:直接用这个生成图片,分辨率相对ok。
        //doc.save(jpgFilePath,SaveFormat.JPEG);

        // 2.对图片分辨率要求高的,使用以下对象ImageSaveOptions去调。图片相对会比较高清
        // 保存呈现的文档页面或形状的格式,可以是栅格SaveFormat.PNG, SaveFormat.BMP, SaveFormat.JPEG或矢量SaveFormat.SVG.
        ImageSaveOptions saveOptions =  new ImageSaveOptions(SaveFormat.PNG);
        // 设置生成图像的水平分辨率,以每英寸点数为单位
        saveOptions.setHorizontalResolution(300F);
        // 为生成的图像设置水平和垂直分辨率,以每英寸点数为单位
        saveOptions.setResolution(212.7F);
        doc.save(jpgFilePath, saveOptions);

        int dirLastIndex = ValueGuardConfig.getProfile().length() + 1;
        // 截取cert/test.jpeg
        String currentDir = StringUtils.substring(jpgFilePath, dirLastIndex);
        // 拼接路径
        String imagesPath = "http://localhost:8015" + Constants.RESOURCE_PREFIX + "/" + currentDir;
        System.out.println(imagesPath);

        return success(imagesPath);
    }

    /**
     * word文档需要填充的数据
     * @return
     */
    private static Map<String, Object> initWordMap() {
        Map<String, Object> wordData = new HashMap<>();
        wordData.put("id", "2023001");
        wordData.put("companyName", "xxxxx有限公司");
        wordData.put("companyNameEN", "Shenzhen Taihe Tianjian Technology Co., LTD");
        wordData.put("expiryDate", "2022年 至 2023年");
        wordData.put("expiryDateEN", "From 2022 to 2023");
        // 将base64字符串图片转换为字节数组
        String base64Image = "data:image/pngbase64........."; 
        byte[] imageBytes = Base64.getDecoder().decode(base64Image.split(",")[1]);
        // 注意图片在word模板插入使用:{@imgaes}
        wordData.put("images",Pictures.ofBufferedImage(image, PictureType.PNG)
                    .size(100, 100).create());
        return wordData;
    }
}

返回的是上传到本地的图片路径了

baec228f2b6249a4ab2e8936a341546a.png

407bfeadfad54ee29cf22e51277c3539.png

 六、word文档生成动态数据转换成pdf

1、引入依赖

<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-local</artifactId>
    <version>1.0.3</version>
</dependency>

2、word转换pdf文档demo示例

package com.valueguard.web;

import com.deepoove.poi.XWPFTemplate;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 行舟668、
 * @Description: word生成动态数据转换pdf
 * @date 2023/6/20 19:12
 */
public class WordToPdf {
    public static void main(String[] args) throws Exception {
        InputStream ins = Thread.currentThread().getContextClassLoader().getResourceAsStream("fofpa-cert-template.docx");
        XWPFTemplate template = XWPFTemplate.compile(ins).render(initWordMap());
        template.writeToFile("test.docx");

        // 创建一个转换器实例
        IConverter converter = LocalConverter.builder().build();
        // 使用转换器将输入文件(test.docx)转换为输出文件(test.pdf)
        converter.convert(new FileInputStream("test.docx")).as(DocumentType.DOCX).
                to(new FileOutputStream("test.pdf")).as(DocumentType.PDF).execute();
        System.out.println("转换成功");
    }
    /**
     * word文档需要填充的数据
     * @return
     */
    private static Map<String, Object> initWordMap() {
        Map<String, Object> wordData = new HashMap<>();
        wordData.put("id", "2023001");
        wordData.put("companyName", "xxxxx有限公司");
        wordData.put("companyNameEN", "Shenzhen Taihe Tianjian Technology Co., LTD");
        wordData.put("expiryDate", "2022年 至 2023年");
        wordData.put("expiryDateEN", "From 2022 to 2023");
        return wordData;
    }
}

d2ccdf57fae34d23abe8ade6daf48177.png

注意事项:在本地环境测试是没问题的,因为本地环境windows本身安装自带了多种字体。部署到服务器上去word模板转图片可能会导致图片有一些字体丢失,主要原因是因为服务器没有我们的标题字体。

 

 解决方案: 在服务器上安装一个我们需要的字体就行了,不会安装的小伙伴可以看一下别人写好的博客!

linux服务器安装字体,删除字体,详细步骤_Male晓的博客-CSDN博客

 欢迎大家在评论区留言,相互交流学习!

  • 9
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

行舟、668

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值