• 使用EasyPoi导出word并转换为pdf


    依赖文件

    
        cn.afterturn
        easypoi-base
        4.3.0
    
    
        cn.afterturn
        easypoi-web
        4.3.0
    
    
        cn.afterturn
        easypoi-annotation
        4.3.0
    
    
    
        org.docx4j
        docx4j-export-fo
        6.1.0
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    文件转换工具类

    import cn.afterturn.easypoi.word.WordExportUtil;
    import org.apache.poi.xwpf.usermodel.XWPFDocument;
    import org.docx4j.Docx4J;
    import org.docx4j.convert.out.FOSettings;
    import org.docx4j.fonts.IdentityPlusMapper;
    import org.docx4j.fonts.PhysicalFonts;
    import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
    import org.docx4j.fonts.Mapper;
    import org.springframework.util.Assert;
    import java.io.*;
    import java.util.Map;
    
    public class FileUtils {
        /**
         *
         * @param templatePath
         * @param saveDir
         * @param fileName
         * @param params
         * @return
         */
        public static String exportWord(String templatePath, String saveDir, String fileName, Map<String, Object> params)  {
            Assert.notNull(templatePath, "模板路径不能为空");
            Assert.notNull(saveDir, "临时文件路径不能为空");
            Assert.notNull(fileName, "导出文件名不能为空");
            Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
            if (!saveDir.endsWith("/")) {
                saveDir = saveDir + File.separator;
            }
    
            File dir = new File(saveDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String savePath = saveDir + fileName;
    
            try {
                XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
                FileOutputStream fos = new FileOutputStream(savePath);
                doc.write(fos);
                fos.flush();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return savePath;
        }
    
    
    
        /**
         * @param wordPath word文件路径
         * @param pdfPath  pdf输出路径
         * @return
         */
        public static String convertDocx2Pdf(String wordPath, String pdfPath) {
            OutputStream os = null;
            InputStream is = null;
            if (pdfPath.endsWith("/")) {
                pdfPath = pdfPath + File.separator;
            }
            try {
                is = new FileInputStream(new File(wordPath));
                WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(is);
                Mapper fontMapper = new IdentityPlusMapper();
                fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
                fontMapper.put("宋体", PhysicalFonts.get("SimSun"));
                fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft Yahei"));
                fontMapper.put("黑体", PhysicalFonts.get("SimHei"));
                fontMapper.put("楷体", PhysicalFonts.get("KaiTi"));
                fontMapper.put("新宋体", PhysicalFonts.get("NSimSun"));
                fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai"));
                fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong"));
                fontMapper.put("宋体扩展", PhysicalFonts.get("simsun-extB"));
                fontMapper.put("仿宋", PhysicalFonts.get("FangSong"));
                fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312"));
                fontMapper.put("幼圆", PhysicalFonts.get("YouYuan"));
                fontMapper.put("华文宋体", PhysicalFonts.get("STSong"));
                fontMapper.put("华文中宋", PhysicalFonts.get("STZhongsong"));
                mlPackage.setFontMapper(fontMapper);
    
                os = new java.io.FileOutputStream(pdfPath);
    
                //docx4j  docx转pdf
                FOSettings foSettings = Docx4J.createFOSettings();
                foSettings.setWmlPackage(mlPackage);
                Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
    
                is.close();//关闭输入流
                os.close();//关闭输出流
    
                return "";
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (os != null) {
                        os.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } finally {
                File file = new File(wordPath);
                if (file != null && file.isFile() && file.exists()) {
                    file.delete();
                }
            }
            return "";
        }
    
    
        /**
         * @param path 图片路径
         * @return
         * @throws IOException
         */
        public static byte[] getImageBase64(String path) throws IOException {
            InputStream input = new FileInputStream(path);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            byte[] data = output.toByteArray();
            output.close();
            input.close();
            return data;
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135

    编写测试接口

    package com.cy.springboot.controller;
    
    import cn.afterturn.easypoi.entity.ImageEntity;
    import com.cy.springboot.utils.FileUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.Assert;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import javax.servlet.http.HttpServletResponse;
    
    import java.io.*;
    import java.net.URLEncoder;
    import java.util.Calendar;
    import java.util.HashMap;
    import java.util.Map;
    
    
    @Controller
    @RequestMapping("/poi")
    public class PoiController {
    
        private String filepath = "C:\\upload";
    
        @RequestMapping(value = "/convertWordToPdf", method = RequestMethod.POST)
        public void convertWordToPdf(HttpServletResponse response) throws Exception {
            File uploadFile = new File(filepath);
            String wordDir = "";
            String pdfDir = "";
            if (!uploadFile.exists()) {
                uploadFile.mkdirs();
            }
            if (!filepath.endsWith("/")) {
                wordDir = filepath + File.separator + "word";
                pdfDir = filepath + File.separator + "pdf";
            }
    
            File tf = new File(wordDir + File.separator + "word模板案例.docx");
            File tf_pic = new File(wordDir + File.separator + "tx.jpg");
            String pic_url = tf_pic.getCanonicalPath();
            Calendar now = Calendar.getInstance();
            Map<String, Object> params = new HashMap<>();
            params.put("name", "彭于晏");
            params.put("sex", "男");
            params.put("age", "28");
            params.put("address", "中国");
            params.put("description", "彭于晏,1982年3月24日出生于台湾省澎湖县,毕业于不列颠哥伦比亚大学,加拿大华裔男演员、歌手。");
    
            ImageEntity image = new ImageEntity();
            image.setHeight(200);
            image.setWidth(200);
            image.setUrl(pic_url);
            image.setData(FileUtils.getImageBase64(pic_url));
            params.put("image", image);
    
            params.put("y", now.get(Calendar.YEAR));
            params.put("m", (now.get(Calendar.MONTH) + 1));
            params.put("d", now.get(Calendar.DAY_OF_MONTH));
    
            String fileName = "wordExport.docx";
            String word = FileUtils.exportWord(tf.getPath(), wordDir, fileName, params);
            String pdfFileName = "convertDocx2Pdf.pdf";
            String downloadFile = "pdf导出.pdf";
    
            if (word.equals("")) {
                Assert.notNull(word, "word路径不能为空");
            } else {
                FileUtils.convertDocx2Pdf(word, pdfDir + File.separator + pdfFileName);
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8"));  // 中文名称下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                OutputStream outputStream = null;
                try {
                    fis = new FileInputStream(pdfDir + File.separator + pdfFileName);
                    bis = new BufferedInputStream(fis);
                    outputStream = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        outputStream.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    outputStream.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114

    word模板
    请添加图片描述
    pdf导出效果
    请添加图片描述

  • 相关阅读:
    【系统架构】-如何评估软件架构
    ​CUDA学习笔记(三)CUDA简介
    Java学习路线大纲
    【SA8295P 源码分析】126 - 摄像头 POC (Power over Coax) 同轴电缆供电技术原理分析
    微服务-gateway基本使用
    机器学习之模拟退火算法
    【C语言】每日一题(添加逗号)
    Head First设计模式(阅读笔记)-07.适配器模式
    ViewPager和ViewPager2
    结构体指针的引入
  • 原文地址:https://blog.csdn.net/Java721/article/details/127778227