高效实现Word转PDF的Java工具类

依赖文件

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>4.3.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>4.3.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-annotation</artifactId>
    <version>4.3.0</version>
</dependency>
<!--pdf-->
<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j-export-fo</artifactId>
    <version>6.1.0</version>
</dependency>

文件转换工具类

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;
    }

}

编写测试接口

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();
                    }
                }
            }
        }
    }
}

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

### 回答1: easypoi是一款Java的开源库,用于将数据以Excel或Word的形式导出。虽然easypoi本身并不直接支持导出图片,但我们可以通过一些技巧来实现将图片导出到Excel或Word中。 首先,我们需要将图片以二进制的形式保存到数据库或文件系统中,然后在导出时通过easypoi将二进制数据读取出来,并将其插入到Excel或Word的对应单元格中。 对于Excel导出,我们可以使用easypoi提供的注解`@ExcelImage`来实现图片导出。我们需要在实体类中添加一个对应图片字段,并在该字段上添加`@ExcelImage`注解。同时,在导出时,我们需要使用`ImageBaseTypeHandler`来读取二进制数据,并将其换为BufferedImage对象,最后通过`ExcelExportUtil.exportExcel`方法导出Excel。 对于Word导出,由于easypoi不支持直接导出图片到Word中,我们可以使用poi的相关类来实现。我们可以通过`XWPFRun`类的`addPicture`方法将图片插入到Word文档中的指定位置。 总结来说,虽然easypoi本身不直接支持导出图片,但我们可以通过一些技巧来实现将图片导出到Excel或Word中。对于Excel导出,可以使用easypoi提供的注解和相关类实现;对于Word导出,则需要借助poi的相关类来实现。 ### 回答2: Easypoi是一个Java的开源库,可用于导出Excel、Word等文档。虽然Easypoi主要用于导出表格数据,但是也可以借助其强大的特性来导出图片。 要使用Easypoi导出图片,需要按照以下步骤进行操作: 1. 导入相关的Easypoi的依赖包,例如easypoi、poi-ooxml、poi。 2. 创建一个实体类,用于存储要导出的图片的相关信息,例如图片路径、图片名称等。 3. 创建一个Excel导出的模板,包括要显示图片的单元格。可以使用Excel工具创建一个模板文件,然后在需要显示图片的单元格中插入图片。 4. 在Java代码中,使用Easypoi提供的API,读取模板文件,并根据实体类中的数据,将图片路径、名称等信息写入到Excel模板中。 5. 调用Easypoi的导出功能,将生成好的Excel文件导出,即可得到包含图片的Excel文件。 需要注意的是,Easypoi导出图片的原理是将图片的路径保存在Excel文件中,而不是将实际的图片数据存储在Excel中。所以在查看Excel文件时,需要保证图片文件的路径和名称是正确的,以确保能够正确显示图片。 总体而言,Easypoi提供了简便易用的功能,使得导出图片变得更加方便。无论是导出单个图片,还是在表格中显示多个图片,都可以通过Easypoi实现。不仅如此,Easypoi还提供了丰富的样式、格式、动态数据处理等功能,使得导出图片的过程更加灵活和可定制。 ### 回答3: easypoi是一款Java的POI扩展工具,可以用于导出Excel、WordPDF等文档。在easypoi中,可以通过设置字段属性来实现导出图片的功能。 首先,需要在实体类中定义一个图片类型的字段,使用easypoi提供的@Excel注解来标注该字段需要导出为图片。例如: ```java public class MyEntity { @Excel(name = "图片", type = 2, savePath = "\\images\\", width = 40, height = 60) private String image; //其他字段... } ``` 其中,@Excel注解的type属性设置为2,表示导出为图片类型;savePath属性指定图片保存的路径;width和height属性设置导出图片的宽度和高度。 接下来,在导出Excel时,需要将包含图片字段的实体类列表传递给easypoi的ExcelExportUtil工具类。例如: ```java public class ExportTest { public static void main(String[] args) { List<MyEntity> list = new ArrayList<>(); //添加数据到list... Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), MyEntity.class, list); try { FileOutputStream fos = new FileOutputStream("output.xlsx"); workbook.write(fos); fos.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 执行上述代码后,会在指定路径下生成output.xlsx文件,该文件中包含了导出的图片。 需要注意的是,图片的路径应该是相对于项目根目录的相对路径,而不是绝对路径。另外,导出图片的格式目前只支持jpg和png两种格式。 通过上述步骤,就可以使用easypoi导出带有图片的Excel文档了。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小蜜蜂127

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

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

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

打赏作者

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

抵扣说明:

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

余额充值