JODConverter v2.2.2,
LibreOffice v3.5
JODConverter 需要在本機電腦中安裝 LibreOffice (OpenOffice 也可),本處以 LibreOffice 為範例
可轉換類型:
*.doc,
*.ppt,
*.xls,
*.docx,
*.pptx,
*.xlsx
使用教學:
Step1: 安裝 LibreOffice
Step2: 啟動 LibreOffice Service
1. cd C:\Program Files\LibreOffice 3.5\program
2. soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
Step3: 將 JODConverter library 裡的 jar 檔放進專案
完成以上動作後,即可開始測試下面範例程式
使用方式,可傳入檔案完整路徑,或檔案的 File 物件,如
OfficePDFUtil officePDFUtil = new OfficePDFUtil();
officePDFUtil.convert("test.doc", "doc.pdf");
<<範例程式>>
import java.io.File;
import java.net.ConnectException;
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 OfficePDFUtil {
/**
* Convert office document to PDF
*
* @param inputFile - File path of original office document (*.doc, *.xls, *.ppt)
* @param outputFile - File path of target pdf document
* @throws ConnectException
*/
public void convert(String inputFilePath, String outputFilePath) throws Exception {
File inputFile = new File(inputFilePath);
File outputFile = new File(outputFilePath);
this.convert(inputFile, outputFile);
}
/**
* Convert office document to PDF
*
* @param inputFile - File of original office document (*.doc, *.xls, *.ppt)
* @param outputFile - File of target pdf document
* @throws ConnectException
*/
public void convert(File inputFile, File outputFile) throws Exception {
//connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
try {
connection.connect();
// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);
} catch (Exception e) {
throw e;
} finally {
//close the connection
try {
if (connection != null) {
connection.disconnect();
connection = null;
}
} catch (Exception e) {
throw e;
}
}
}
}