1. 程式人生 > 實用技巧 >Java利用OpenOffice將word等office文件轉換成PDF

Java利用OpenOffice將word等office文件轉換成PDF

package demo;

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 Word2PdfJacobUtil {
	

	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=8100;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",8100);
        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(); 
        } 
        }

	    public static void main(String[] args) {
	        office2PDF("E:\\新建 DOCX 文件.docx", "E:\\新建 DOCX 文件.pdf");
	    }
	}

  以上程式碼親測有效

問題:

java.net.ConnectException: connection failed: socket,host=10.101.50.71,port=8100,tcpNoDelay=1: java.net.ConnectException: Connection refused: connect
at com.artofsolving.jodconverter.openoffice.connection.AbstractOpenOfficeConnection.connect(AbstractOpenOfficeConnection.java:79)
原因以及解決方法:第一次呼叫,soffice需要註冊,所以到soffice.exe的安裝路徑下雙擊soffice.exe,註冊即可。

OpenOffice:https://openoffice.en.softonic.com/

用到的jar包(專案中的所有包,都匯入進去,反正不會出錯)