利用LibreOffice进行WORD转PDF

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Kevin_King1992/article/details/80198631

常用解决方案:

  • 收费,不介绍。
  • 免费,利用OpenOffice或者LibreOffice等进行转化,但是转化效率稍微慢点,但是word格式保持不错。
  • POI+itext,网上也有不少,但是没有真正研究。

思路:
安装libreoffice,然后直接利用命令行进行java调用。下述,仅限于使用windows,其他系统需修改命令。

代码实现:

package demo;

import com.sun.star.lang.NullPointerException;

/**
 * @author Kevin 2018-5-3
 *
 */
public final class LibreOfficeUtils {

    public static void main(String[] args) throws NullPointerException {
        long start = System.currentTimeMillis();
        convertOffice2PDF("d:/test/converting2.doc","d:/test");
        long end = System.currentTimeMillis();
        System.out.println((end-start) +"ms");
    }

    /**
     * 
     * soffice --headless --invisible --convert-to pdf:writer_pdf_Export D:/test/fb35e7d25afaf1b5d34f7bdb4f830c8c.doc --outdir D:/testfile2html
     * 
     * @param srcPath
     * @param desPath
     * @return
     * @throws NullPointerException 
     */
    public static boolean convertOffice2PDF(String srcPath, String desPath) throws NullPointerException{

        System.out.println("开始进行转化.....");
        if(srcPath == null || desPath == null){
            throw new NullPointerException("转化文件不存在或者路径有问题");
        }
        String command = "";
        String osName = System.getProperty("os.name");
        if (osName.contains("Windows")) {
            command = "cmd /c soffice --headless --invisible --convert-to pdf:writer_pdf_Export " + srcPath + " --outdir " + desPath;
        }
        System.err.println(command + " : 转化中....");

        try {
            Process p = Runtime.getRuntime().exec(command);
            p.waitFor();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            System.out.println("转化结束...");
        }
    }

}

遇到的问题:
1.
这里写图片描述
windows下执行需要 命令前加cmd /c ,就解决了,与系统相关的调用方式。

2.待转化文件名最好不要保留空格可能转化不成功!

猜你喜欢

转载自blog.csdn.net/Kevin_King1992/article/details/80198631