栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java - 填充Word文本域、Word转PDF操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java - 填充Word文本域、Word转PDF操作

先看效果:

填充前:

 填充后效果:


第一步: 引入Maven坐标:

        
        
            cn.hutool
            hutool-all
            4.6.3
        

        
        
            com.deepoove
            poi-tl
            1.9.0-beta
        
        
        
            com.aspose
            aspose-words
            14.7.0
            system
            ${pom.basedir}/lib/aspose-words-15.8.0-jdk16.jar
        

 

第二步: 工具类: 

import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.exception.RenderException;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Map;


@Slf4j
public class WordUtil {

    
    public static byte[] fillWordToPDF(Map datas,InputStream fileStream) throws IOException {
        try {
            //先填充word:
            byte[] bytes = fillWord(datas, fileStream);

            //在word转pdf:
            return wordToPDF(new ByteArrayInputStream(bytes));
        } catch (IOException ex){
            log.error("系统异常::{}",ex);
            throw ex;
        }
    }

    
    public static byte[] fillWord(Map datas, InputStream fileStream) throws IOException {
        XWPFTemplate template = null;
        ByteArrayOutputStream wordOut = new ByteArrayOutputStream(1024);
        try {
            //设置占位符:
            Configure config = Configure.builder()
                    .buildGramer("${", "}") //设置模板中的占位符${}, 默认是{{}}
                    .setValidErrorHandler(new Configure.AbortHandler()) //若模板中占位符与填充属性不对应,则报错;
                    .bind("item", new HackLoopTableRenderPolicy()) //设置模板中表格的参数属性
                    .build();

            //填充文本域:
            template = XWPFTemplate.compile(fileStream, config).render(datas);
            template.write(wordOut);
        }catch (RenderException ex){
            log.error("模板填充失败,请保证模板文本域与参数保持一致。错误信息::{}",ex);
            throw ex;
        } catch (IOException ex){
            log.error("系统异常::{}",ex);
            throw ex;
        }finally {
            try {
                if (template != null){
                    template.close();
                }
            } catch (IOException ex) {
                log.error("关闭文件流资源异常::{}",ex);
            }
        }
        return wordOut.toByteArray();
    }

    
    public static byte[] wordToPDF(InputStream wordInStream) {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream(1024);
        try {
            InputStream licenseIn = WordUtil.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(licenseIn);

            //因linux环境没有语言包,当项目部署到linux环境后,转成的pdf中的中文是类似乱码的,所以需要去加载此目录下的语言包;
            OsInfo osInfo = SystemUtil.getOsInfo();
            if(osInfo.isLinux()){
                //====================================== 注意 ============================================
                //注意: 需要把项目中resource/fonts目录下的语言包全部放到linux中的此目录下,否则linux环境中处理是乱码;
                //以下是我自己定义的目录,你可随意更改为你linux上的目录;
                FontSettings.setFontsFolder("/usr/share/fonts/chinese", true);
                //=======================================================================================
            }

            //Address是将要被转化的word文档
            Document doc = new Document(wordInStream);
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            doc.save(byteOut, SaveFormat.PDF);
        } catch (Exception e) {
            log.error("word转pdf异常::{}",e);
            throw new RuntimeException("word转pdf异常");
        }
        return byteOut.toByteArray();
    }

    
    public static void wordToPDF(InputStream wordInStream, OutputStream pdfOutStream) {
        try {
            InputStream licenseIn = WordUtil.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(licenseIn);

            //因linux环境没有语言包,当项目部署到linux环境后,转成的pdf中的中文是类似乱码的,所以需要去加载此目录下的语言包;
            OsInfo osInfo = SystemUtil.getOsInfo();
            if(osInfo.isLinux()){
                //====================================== 注意 ============================================
                //注意: 需要把项目中resource/fonts目录下的语言包全部放到linux中的此目录下,否则linux环境中处理是乱码;
                //以下是我自己定义的目录,你可随意更改为你linux上的目录;
                FontSettings.setFontsFolder("/usr/share/fonts/chinese", true);
                //=======================================================================================
            }

            //Address是将要被转化的word文档
            Document doc = new Document(wordInStream);
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            doc.save(pdfOutStream, SaveFormat.PDF);
        } catch (Exception e) {
            log.error("word转pdf异常::{}",e);
            throw new RuntimeException("word转pdf异常");
        }
    }
}

 注: license.xml文件内容如下



	
		
			Aspose.Total for Java
			Aspose.Words for Java
		
		Enterprise
		20991231
		20991231
		8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7
	
	sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=

第三步: 测试

1、word模板文件: 请按照第一张图片自行制作;

2、测试代码:填充成功后直接转成pdf文件;

    public static void main(String[] args) throws IOException {
        //数据
        Map datas = new HashMap();
        datas.put("dept", "采购部");
        datas.put("name", "张三");
        LocalDate date = LocalDate.now();
        datas.put("year", date.getYear());
        datas.put("month", date.getMonthValue());
        datas.put("day", date.getDayOfMonth());
        //表格(多条数据格式):
        List itemList = new ArrayList<>();
        Map itemMap = new HashMap();
        itemMap.put("goods", "笔记本电脑");
        itemMap.put("num", "2");
        itemMap.put("cost", "10000");
        itemMap.put("remark", "按需采购");
        itemList.add(itemMap);
        itemMap = new HashMap();
        itemMap.put("goods", "台式电脑");
        itemMap.put("num", "1");
        itemMap.put("cost", "8000");
        itemMap.put("remark", "按需采购");
        itemList.add(itemMap);
        datas.put("item",itemList);
        datas.put("total","10000");
        //需要填充到word中的图片数据
        ClassLoader classLoader = WordUtil.class.getClassLoader();
        InputStream imageStream = classLoader.getResourceAsStream("template/image.png");
        BufferedImage bi = ImageIO.read(imageStream);
        int width = bi.getWidth();
        int height = bi.getHeight();
        datas.put("image", new PictureRenderData(width, height, PictureType.PNG, imageStream));
        //模板文件流
        InputStream tempStream = classLoader.getResourceAsStream("template/测试模板文件.docx");

        //填充word:
        byte[] bytes = WordUtil.fillWord(datas, tempStream);
        //word转pdf:
        File pdfFile = new File("生成的PDF文件" + System.currentTimeMillis() + ".pdf");
        WordUtil.wordToPDF(new ByteArrayInputStream(bytes),new FileOutputStream(pdfFile));
    }

注意:

1、word转pdf的jar包,在maven中心仓库中不存在,下载不了。在此我提供了jar包:

百度网盘: 百度网盘 请输入提取码

提取码: qk0x

Maven项目手动引入Jar包的编译、打包方式请看此篇文章: https://mp.csdn.net/mp_blog/creation/editor/125435777

 2、word转pdf时,Linux会出现中文乱码问题(window不存在);解决办法:Linux环境aspose插件word转pdf中文乱码解决方案_赵广陆的博客-CSDN博客_aspose中文乱码

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/991990.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号