百度文庫的實現——java利用openoffice,批量word轉pdf


 百度文庫的主要功能就是將上傳的word文檔,轉碼成pdf格式再展示出來。其中有四種方法可以實現這樣的操作:

方法一:用apache pio 讀取doc文件,然后轉成html文件用Jsoup格式化html文件,最后用itext將html文件轉成pdf。

方法2:使用jdoctopdf來實現,這是一個封裝好的包,可以把doc轉換成pdf,html,xml等格式,調用很方便
需要注意中文字體的寫入問題。

方法3:使用jodconverter來調用openOffice的服務來轉換,openOffice有個各個平台的版本,所以這種方法跟方法1一樣都是跨平台的。
安裝完后要啟動openOffice的服務,具體啟動方法請自行google

方法4:效果最好的一種方法,但是需要window環境,而且速度是最慢的需要安裝msofficeWord以及SaveAsPDFandXPS.exe(word的一個插件,用來把word轉化為pdf)
Office版本是2007,因為SaveAsPDFandXPS是微軟為office2007及以上版本開發的插件

這里我們采用第三種方法,因為其跨平台的屬性和簡單方便的操作。
windows下:1.首先下載window版本的openoffice進行安裝,並首次啟動。
2.這里我們不做配置,因為在代碼中我們調用命令對openoffice進行啟動並實時關閉,這樣對占用內存的解決是一個很好的方案,如果轉碼不是常用功能的話。
3.下載jodconverter,將lib文件夾下所有的jar包導入

Linux下:

1.首先安裝openoffice for linux,可以去官網下載也可以用命令。
命令下載:
    wget http://sourceforge.net/projects/openofficeorg.mirror/files/4.1.1/binaries/zh-CN/Apache_OpenOffice_4.1.1_Linux_x86-64_install-rpm_zh-CN.tar.gz 
      tar -xzvf Apache_OpenOffice_4.1.1_Linux_x86-64_install-rpm_zh-CN.tar.gz
      cd zh-CN
      cd RPMS
      rpm -ivh *.rpm
2.在linux中也同樣可以調用命令啟動,不過告訴大家的是,可以設置為開機啟動或隨tomcat啟動,以便轉碼程序啟動頻繁。
 
        

 

 以下批量純屬測試使用,正常項目采用mq隊列。
package wordtopdf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

public class topdftest {
    private static int depth=1;
    
    public static void main(String[] args) throws IOException {
        //office2PDF("D:\\資源管理\\11","D:\\資源管理\\11");
        find("D:\\資源管理\\11",depth);
    }
    /** 
     * 將Office文檔轉換為PDF. 運行該函數需要用到OpenOffice, OpenOffice下載地址為 
     * http://www.openoffice.org/ 
     *  
     * <pre> 
     * 方法示例: 
     * String sourcePath = "F:\\office\\source.doc"; 
     * String destFile = "F:\\pdf\\dest.pdf"; 
     * Converter.office2PDF(sourcePath, destFile); 
     * </pre> 
     *  
     * @param sourceFile 
     *            源文件, 絕對路徑. 可以是Office2003-2007全部格式的文檔, Office2010的沒測試. 包括.doc, 
     *            .docx, .xls, .xlsx, .ppt, .pptx等. 示例: F:\\office\\source.doc 
     * @param destFile 
     *            目標文件. 絕對路徑. 示例: F:\\pdf\\dest.pdf 
     * @return 操作成功與否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置錯誤; 如果返回 0, 
     *         則表示操作成功; 返回1, 則表示轉換失敗 
     */  
    public static int office2PDF(String sourceFile, String destFile) {  
        try {  
            File inputFile = new File(sourceFile);  
            if (!inputFile.exists()) {  
                return -1;// 找不到源文件, 則返回-1  
            }  
  
            // 如果目標路徑不存在, 則新建該路徑  
            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=8100;urp;\"";  
            Process pro = Runtime.getRuntime().exec(command);  
            // connect to an OpenOffice.org instance running on port 8100  
            OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);  
            connection.connect();  
  
            // convert  
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
            converter.convert(inputFile, outputFile);  
  
            // close the connection  
            connection.disconnect();  
            // 關閉OpenOffice服務的進程  
            pro.destroy();  
  
            return 0;  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
            return -1;  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
        return 1;  
    }  
    
      
    
    public static void find(String pathName,int depth) throws IOException{  
        int filecount=0;  
        //獲取pathName的File對象  
        File dirFile = new File(pathName);  
        //判斷該文件或目錄是否存在,不存在時在控制台輸出提醒  
        if (!dirFile.exists()) {  
            System.out.println("do not exit");  
            return ;  
        }  
        //判斷如果不是一個目錄,就判斷是不是一個文件,時文件則輸出文件路徑  
        if (!dirFile.isDirectory()) {  
            if (dirFile.isFile()) {  
                System.out.println(dirFile.getCanonicalFile()); 
                int end = String.valueOf(dirFile.getCanonicalFile()).lastIndexOf(".");
                office2PDF(String.valueOf(dirFile.getCanonicalFile()),String.valueOf(dirFile.getCanonicalFile()).substring(0,end)+".pdf");
            }  
            return ;  
        }  
        //獲取此目錄下的所有文件名與目錄名  
        String[] fileList = dirFile.list();  
        int currentDepth=depth+1;  
        for (int i = 0; i < fileList.length; i++) {  
            //遍歷文件目錄  
            String string = fileList[i];  
            //File("documentName","fileName")是File的另一個構造器  
            File file = new File(dirFile.getPath(),string);  
            String name = file.getName();  
            //如果是一個目錄,搜索深度depth++,輸出目錄名后,進行遞歸  
            if (file.isDirectory()) {  
                //遞歸  
                find(file.getCanonicalPath(),currentDepth);  
            }else{  
                int end = file.getPath().lastIndexOf(".");
                office2PDF(file.getPath(),file.getPath().substring(0,end)+".pdf"); 
            }  
        }  
    }  
}
 
        

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM