zoukankan      html  css  js  c++  java
  • 利用LibreOffice进行WORD转PDF

    常用解决方案:

    • 收费,不介绍。
    • 免费,利用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.待转化文件名最好不要保留空格可能转化不成功!

  • 相关阅读:
    python复习-数据类型与运算
    爬虫笔记
    网络爬虫-总结
    pymongo使用方法
    Mac下,安装redis之后,启动时遇到的问题
    java实现23种设计模式之迭代器模式
    java实现23种设计模式之观察者模式
    java实现23种设计模式之模版方法模式
    java实现23种设计模式之策略模式
    jvm参数的优化
  • 原文地址:https://www.cnblogs.com/Kevin-1992/p/12608356.html
Copyright © 2011-2022 走看看