Java代码word转pdf

Java代码word转pdf

参考链接:https://blog.csdn.net/vatxiongxiaohui/article/details/83985896
https://www.cnblogs.com/chenpt/p/11096265.html
最近公司做的项目中有功能要对文件加水印,word文档加水印比较麻烦,于是就想将word类型文档转成pdf类型文档再进行处理,网上搜集了不少方法,也都试过,个人觉得比较好用的有两个,做个记录。

1、采用jacob插件实现

jacob提取链接:https://pan.baidu.com/s/1l8GVdMECOFxKkLfoYS-AYg
提取码:2qh3
① 下载好的压缩包解压,将里面的dll文件放置在jre/bin目录下面 如 D:\work\jdk1.8\jre\bin
在这里插入图片描述
②导入jacob.jar到项目
当前项目路径下
添加Maven依赖

        <dependency>
            <groupId>com.jacob</groupId>
            <artifactId>jacob</artifactId>
            <version>1.19</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/resources/lib/jacob.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.6</version>
        </dependency>

③ 具体代码实现

 /**
     * wordToPDF
     * @param sFilePath 传入文件
     * @param toFilePath 输出文件
     */
    public static void wordToPDF(String sFilePath,String toFilePath) {
        System.out.println("启动 Word...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", new Variant(false));
            Dispatch docs = app.getProperty("Documents").toDispatch();
            doc = Dispatch.call(docs, "Open", sFilePath).toDispatch();
            System.out.println("打开文档:" + sFilePath);
            System.out.println("转换文档到 PDF:" + toFilePath);
            File tofile = new File(toFilePath);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(doc, "SaveAs", toFilePath, // FileName
                    17);//17是pdf格式
            long end = System.currentTimeMillis();
            System.out.println("转换完成..用时:" + (end - start) + "ms.");

        } catch (Exception e) {
            System.out.println("========Error:文档转换失败:" + e.getMessage());
        } finally {
            Dispatch.call(doc, "Close", false);
            System.out.println("关闭文档");
            if (app != null)
                app.invoke("Quit", new Variant[]{});
        }
        // 如果没有这句话,winword.exe进程将不会关闭
        ComThread.Release();
    }

2、记录libreoffice实现office转pdf(适用于windows、linux)

LibreOffice提取地址:https://pan.baidu.com/s/1fmIiMXgVACHp5GIXzIIZvA
提取码:k02b
提取完成直接安装即可,需要注意的是这款软件是通过cmd命令调用LibreOffice指令的,安装完成后需要配置环境变量(D:\Program Files\LibreOffice\program)。配置好后调用cmd命令,进入dos界面输入 soffice 调用启动LibreOffice程序则表示安装配置成功。

    protected static final Logger logger = LoggerFactory.getLogger(SpireDocForJava.class);

    /**
     * 利用libreOffice将office文档转换成pdf
     *
     * @param inputFile 目标文件地址
     * @param pdfFile   输出文件夹
     * @return
     */
    public static boolean convertOffice2PDF(String inputFile, String pdfFile) {
        long start = System.currentTimeMillis();
        String command;
        boolean flag;
        String osName = System.getProperty("os.name");
        if (osName.contains("Windows")) {
            command = "cmd /c start soffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;
        } else {
            command = "libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;
        }
        flag = executeLibreOfficeCommand(command);
        long end = System.currentTimeMillis();
        logger.debug("用时:{} ms", end - start);
        return flag;
    }

    /**
     * 执行command指令
     *
     * @param command
     * @return
     */
    public static boolean executeLibreOfficeCommand(String command) {
        logger.info("开始进行转化.......");
        Process process;// Process可以控制该子进程的执行或获取该子进程的信息
        try {
            logger.debug("convertOffice2PDF cmd : {}", command);
            process = Runtime.getRuntime().exec(command);// exec()方法指示Java虚拟机创建一个子进程执行指定的可执行程序,并返回与该子进程对应的Process对象实例。
            // 下面两个可以获取输入输出流
//            InputStream errorStream = process.getErrorStream();
//            InputStream inputStream = process.getInputStream();
        } catch (IOException e) {
            logger.error(" convertOffice2PDF {} error", command, e);
            return false;
        }
        int exitStatus = 0;
        try {
            exitStatus = process.waitFor();// 等待子进程完成再往下执行,返回值是子线程执行完毕的返回值,返回0表示正常结束
            // 第二种接受返回值的方法
            int i = process.exitValue(); // 接收执行完毕的返回值
            logger.debug("i----" + i);
        } catch (InterruptedException e) {
            logger.error("InterruptedException  convertOffice2PDF {}", command, e);
            return false;
        }
        if (exitStatus != 0) {
            logger.error("convertOffice2PDF cmd exitStatus {}", exitStatus);
        } else {
            logger.debug("convertOffice2PDF cmd exitStatus {}", exitStatus);
        }
        process.destroy(); // 销毁子进程
        logger.info("转化结束.......");
        return true;
    }

    public static void main(String[] args) {
        try {
            // 建议都用/左斜杠这种,左斜杠是windows和linux通用的
            convertOffice2PDF("E:/信用卡互联网发卡业务补充合作协议2019.01.docx","E:/测试.pdf");
        } catch (Exception e) {
            System.out.println("word转换成pdf时出错");
            e.printStackTrace();
        }
    }

解压这三个包 (下面操作都要执行)

wget http://mirrors.ustc.edu.cn/tdf/libreoffice/stable/6.2.8/rpm/x86_64/LibreOffice_6.2.8_Linux_x86-64_rpm.tar.gz
wget http://mirrors.ustc.edu.cn/tdf/libreoffice/stable/6.2.8/rpm/x86_64/LibreOffice_6.2.8_Linux_x86-64_rpm_sdk.tar.gz
wget http://mirrors.ustc.edu.cn/tdf/libreoffice/stable/6.2.8/rpm/x86_64/LibreOffice_6.2.8_Linux_x86-64_rpm_langpack_zh-CN.tar.gz

tar -xvf LibreOffice_6.2.8_Linux_x86-64_rpm.tar.gz
tar -xvf LibreOffice_6.2.8_Linux_x86-64_rpm_sdk.tar.gz
tar -xvf LibreOffice_6.2.8_Linux_x86-64_rpm_langpack_zh-CN.tar.gz

解压后进入LibreOffice_6.2.8_Linux_x86-64_rpm/RPM目录下并执行yum localinstall *.rpm安装rpm文件
在这里插入图片描述
执行以上步骤,默认会将libreoffice的可执行安装在/opt/lib/libreoffice/…soffice.bin,也可以使用yum来指定安装路径:

yum -c /etc/yum.conf --installroot=/usr/local --releasever=/ localinstall *.rpm
该命令简单解释如下:
-c /etc/yum.conf 表示指定yum配置文件地址
–installroot=/usr/local 表示指定自定义的安装目录

linux下面命令行测试word转pdf(其参数与windows下的参数大体相同)
命令:libreoffice6.2 --convert-to pdf:writer_pdf_Export /home/file/测试.docx --outdir /home/file/

关于word转pdf中文乱码问题处理
1:查看fonts目录:cat /etc/fonts/fonts.conf | grep fon
得知字体存放位置:/usr/share/fonts

2: 把Windows下的字体C:\Windows\Fonts下的宋体,即simsun.ttc上传到linux服务器
在fonts下新建Fonts文件 把字体上传到该路径下即可

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值