word转pdf

一、docx4j

注意事项:

1、只能在windows环境下使用

2、 poi使用高版本,打包后会使转换成的pdf文档出现排版乱码,本地测试无任何问题。没测试更换低版本后的情况,建议使用第二种方法

<!--pdf-->
<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j-export-fo</artifactId>
    <version>6.1.0</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.15</version>
</dependency>
<dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml-schemas</artifactId>
     <version>3.15</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>
@RestController
@RequestMapping("/poi")
public class PoiController {

    @GetMapping("/export_word")
    public void export_Word(HttpServletResponse response) throws Exception {
        File templateFile = new File("E:\\MP-AUTO-CODE\\template.docx");
        File imgFile = new File("C:\\Users\\sunya\\Desktop\\picture\\1111.jpg");
        String imgUrl = imgFile.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", "吴彦祖,演员,代表作《新警察故事》");
        ImageEntity image = new ImageEntity();
        image.setHeight(200);
        image.setWidth(200);
        image.setUrl(imgUrl);
        image.setData(FileUtils.getImageBase64(imgUrl));
        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 wordPath = FileUtils.exportWord(templateFile.getPath(), "E:\\MP-AUTO-CODE", "生成文件.docx", params);
        FileUtils.convertDocx2Pdf(wordPath, "E:\\MP-AUTO-CODE\\导出.pdf");
        FileUtils.downloadFile(response, "E:\\MP-AUTO-CODE\\导出.pdf", "导出测试.pdf");
    }
}
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.hutool.core.lang.Assert;
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.Mapper;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Description pdf工具类
 * @ClassName FileUtils
 * @Author syh
 * @Date 2022/12/9 16:08
 */
public class FileUtils {
    /**
     * 生成word 只支持docx * * @param templatePath 模板文件路径 * @param temDir 生成文件的目录 * @param fileName 生成文件名 * @param params 参数
     */
    public static String exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params) {

        Assert.notNull(templatePath, "模板路径不能为空");
        Assert.notNull(temDir, "临时文件路径不能为空");
        Assert.notNull(fileName, "导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
        if (!temDir.endsWith("/")) {

            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {

            dir.mkdirs();
        }
        String tmpPath = "";
        try {

            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {

//e.printStackTrace();
        }
        return tmpPath;
    }

    public static String convertDocx2Pdf(String wordPath, String pdfPath) {

        OutputStream os = null;
        InputStream is = null;
        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);
//输出pdf文件路径和名称
// String fileName = "pdfNoMark_" + System.currentTimeMillis() + ".pdf";
// String fileName = "事务信息表.pdf";;
// String pdfNoMarkPath = System.getProperty("java.io.tmpdir").replaceAll(separator + "$", "") + separator + fileName;
            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 "";
    }

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

    public static void downloadFile(HttpServletResponse response, String downloadFilePath, String fileName) throws UnsupportedEncodingException {

        File file = new File(downloadFilePath);
        if (file.exists()) {

            response.setContentType("application/force-download");// 设置强制下载不打开
// response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
//中文名称下载
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            OutputStream outputStream = null;
            try {

                fis = new FileInputStream(file);
                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();
                    }
                }
            }
        }
    }
}

 

二、xdocreport

word模板

依赖

注意事项:

poi使用高版本会出现找不到某个jar包的问题,具体为本地测试没有问题,打完jar包放到服务器上报错Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/apache/poi/xwpf/usermodel/IRunBody!

解决方法:实测将poi版本更换为3.15可以正常使用。

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.15</version>
</dependency>
<dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml-schemas</artifactId>
     <version>3.15</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>
<dependency>
	<groupId>fr.opensagres.xdocreport</groupId>
	<artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId>
	<version>2.0.1</version>
</dependency>

将word转为pdf工具类,并将文件下载到浏览器的工具类

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.hutool.core.lang.Assert;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Description pdf工具类
 * @ClassName FileUtils
 * @Author syh
 * @Date 2022/12/9 16:08
 */
public class WordTurnPdfUtils {
    /***
     * 生成word 只支持docx * * @param templatePath 模板文件路径 * @param temDir 生成文件的目录 * @param fileName 生成文件名 * @param params 参数
     * @MethodName exportWord poi使用模板生成word
     * @param templatePath  模板路径
     * @param temDir 存放路径  E:/case/officeCopy
     * @param fileName  word文件名称
     * @param params 数据集
     * @return java.lang.String 
     *
     * @Author syh
     * @Date 2023/4/13 14:24
     */
    public static String exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params) {
        Assert.notNull(templatePath, "模板路径不能为空");
        Assert.notNull(temDir, "临时文件路径不能为空");
        Assert.notNull(fileName, "导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
        if (!temDir.endsWith("/")) {
            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String tmpPath = "";
        try {
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tmpPath;
    }

    /***
     * @MethodName wordTurnPdf word转pdf
     * @param wordPath word文件地址  E:/case/officeCopy
     * @param officeCopyPdf pdf生成地址  E:/case/officeCopy/smgzs_template.pdf
     * @param response  HttpServletResponse对象
     *
     * @Author syh
     * @Date 2023/4/13 14:14
     */
    public static void wordTurnPdf(String wordPath, String officeCopyPdf, HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        XWPFDocument xwpfDocument = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(wordPath);
            xwpfDocument = new XWPFDocument(fileInputStream);
            PdfOptions pdfOptions = PdfOptions.create();
            fileOutputStream = new FileOutputStream(officeCopyPdf);
            PdfConverter.getInstance().convert(xwpfDocument,fileOutputStream,pdfOptions);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            WordTurnPdfUtils.downloadFile(response, officeCopyPdf, "书面告知书_template.pdf");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /***
     * @MethodName downloadFile 返回浏览器文件流
     * @param response HttpServletResponse
     * @param downloadFilePath 文件路径
     * @param fileName 浏览器端文件名称
     *
     * @Author syh
     * @Date 2023/4/13 14:23
     */
    public static void downloadFile(HttpServletResponse response, String downloadFilePath, String fileName) throws UnsupportedEncodingException {
        File file = new File(downloadFilePath);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            // response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            //中文名称下载
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] buffer = new byte[4096];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            OutputStream outputStream = null;
            try {
                fis = new FileInputStream(file);
                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();
                    }
                }
            }
        }
    }
}

在linux环境下,可能会遇到排版错乱问题,Word转换PDF成功但是中文显示不出都是因为字体的问题

解决方法:

a、将C:\Windows\Fonts 所有字体全部压缩成zip包(allfont.zip)

b、将压缩包拷贝到linux服务器上的 /usr/share/fonts目录

c、unzip allfont.zip 解压文件

d、使用命令刷新到缓存中:执行命令:fc-cache -fv

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

S Y H

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

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

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

打赏作者

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

抵扣说明:

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

余额充值