最近遇到一個學習平臺的項目,涉及到各種文檔,爲了站點資源的安全性,文檔全部需要轉成pdf,只供用戶瀏覽。翻閱了很多資料,看了一個博主寫的使用open office實現的方式,簡單明瞭,這裏也分享一下。
這裏介紹在win環境下的openoffice使用。
百度搜索:open office就可以找到下載文件。安裝後,啓動服務就可以使用了。
代碼:
/**
* 將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, .txt 等. 示例: 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 (ConnectException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
demo下載地址:
http://download.csdn.net/download/qq_17770183/10156416
參考博文url:
http://titanseason.iteye.com/blog/1471606