public static void office2PDF(String sourceFile, String destFile) { 
        try { 
        File inputFile = new File(sourceFile); 
        if (!inputFile.exists()) { 
        return ;// 找不到源文件, 则返回
        } 

        // 如果目标路径不存在, 则新建该路径 
        File outputFile = new File(destFile); 
        if (!outputFile.getParentFile().exists()) { 
        outputFile.getParentFile().mkdirs(); 
        } 

        String OpenOffice_HOME = "c:\\Program Files (x86)\\OpenOffice 4";//这里是OpenOffice的安装目录, 在我的项目中,为了便于拓展接口,没有直接写成这个样子,但是这样是绝对没问题的 
        // 如果从文件中读取的URL地址最后一个字符不是 '\',则添加'\' 
        if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') { 
        OpenOffice_HOME += "\\"; 
        } 
        // 启动OpenOffice的服务 
        String command = OpenOffice_HOME 
        + "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8001;urp;\"-nofirststartwizard"; 
        Process pro = Runtime.getRuntime().exec(command); 
        // connect to an OpenOffice.org instance running on port 8100 
        OpenOfficeConnection connection = new SocketOpenOfficeConnection( 
        "127.0.0.1", 8001); 
        connection.connect(); 

        // convert 
        DocumentConverter converter = new OpenOfficeDocumentConverter( 
        connection); 
        converter.convert(inputFile, outputFile); 

        // close the connection 
        connection.disconnect(); 
        // 关闭OpenOffice服务的进程 
        pro.destroy(); 

        } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
        } catch (IOException e) { 
        e.printStackTrace(); 
        } 
        }

 

posted on 2015-09-02 09:47  jianlunx  阅读(734)  评论(0编辑  收藏  举报