引言:突然接到任務,要將word或者ppt轉換成HTML的格式在頁面上顯示,類似于百度文庫的效果。以前也聽說過,覺得用java實現(xiàn)起來還是很簡單的。于是我就帶著我的任務以及我的好奇心出發(fā)了,在網(wǎng)上找了些資料,最終決定用OpenOffice。
首先簡單的介紹下轉換需要的環(huán)境:
1、轉換組要安裝openoffice軟件(下載地址:http://download.openoffice.org/index.html)
2、需要下載jodconverter包
在此我提供了jodconverter包(包括jodconverter2、jodconverter3,注:jodconverter2需要手動啟動openoffice服務,如有不清楚的地方可以在我文章下面留言),下載請點擊...
JODConverter是一個開源文檔轉換工具,既可以應用于Linux平臺,也可其應用于Windows平臺。其基于OpenOffice.org或者LibreOffice。因此,文檔轉換服務器上必須安裝有OpenOffice或者LibreOffice。
目前最新版本的JODConverter為JODConverter3.0,它要求JDK1.5以上的Java環(huán)境,同時還需要OpenOffice.org 3.x版本。本文基于最新版本3.0設計實現(xiàn),如果是版本為2,則有不同的實現(xiàn)。(版本2需要手動啟動OpenOffice.org服務,或者創(chuàng)建Windows服務設置為開機啟動,而版本3提供了開啟服務的接口,在此我使用的是版本3)
一切準備就緒那就直接開始了...
下面是一個比較完整的例子,可以實現(xiàn) WORD==>HTML 、PPT==>HTML、WORD==>PDF、PPT==>PDF的轉換。
- package core;
-
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Date;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
-
- import org.artofsolving.jodconverter.OfficeDocumentConverter;
- import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
- import org.artofsolving.jodconverter.office.OfficeManager;
-
- //轉換文檔為pdf
- public class OpenOfficePdfConvert {
-
- /**
- * @param args
- */
- private static OfficeManager officeManager;
- private static String OFFICE_HOME = "d:\\Program Files\\OpenOffice.org 3";// 安裝OPenOffice
- // 的路徑
- private static int port[] = { 8100 };
-
- //1、客戶上傳Word文檔到服務器
-
- //2、服務器調(diào)用OpenOffice程序打開上傳的Word文檔
-
- //3、OpenOffice將Word文檔另存為Html格式
-
-
- public File convertToHtml(String inputFile, String outputFile)
- throws FileNotFoundException {
- // 創(chuàng)建保存html的文件
- File wantFile = new File(outputFile + File.separator + new Date().getTime()
- + ".html");
- // 開啟服務器
- startService();
- // 進行轉換
- System.out.println("進行文檔轉換轉換:" + inputFile + " --> " + outputFile);
- OfficeDocumentConverter converter = new OfficeDocumentConverter(
- officeManager);
- converter.convert(new File(inputFile), wantFile);
- // 關閉服務器
- stopService();
- System.out.println();
- return wantFile;
-
- }
-
- // 打開服務器
- public static Boolean startService() {
- DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
- try {
- System.out.println("準備啟動服務....");
- configuration.setOfficeHome(OFFICE_HOME);// 設置OpenOffice.org安裝目錄
- configuration.setPortNumbers(port); // 設置轉換端口,默認為8100
- configuration.setTaskExecutionTimeout(1000 * 60 * 5L);// 設置任務執(zhí)行超時為5分鐘
- configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);// 設置任務隊列超時為24小時
-
- officeManager = configuration.buildOfficeManager();
- officeManager.start(); // 啟動服務
- System.out.println("office轉換服務啟動成功!");
- return true;
- } catch (Exception ce) {
- System.out.println("office轉換服務啟動失敗!詳細信息:" + ce);
- return false;
- }
- }
-
- // 關閉服務器
- public static void stopService() {
- System.out.println("關閉office轉換服務....");
- if (officeManager != null) {
- officeManager.stop();
- }
- System.out.println("關閉office轉換成功!");
- }
-
- /*
- * 進行測試轉換是否成功
- */
- public static void main(String[] args) {
- String inputFile = "c:\\test\\test.docx";
- String outputFile = "c:\\test";
- OpenOfficePdfConvert opc = new OpenOfficePdfConvert();
- try {
- opc.convertToHtml(inputFile,outputFile);
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- }
- /*try {
- * 如果想看到不帶HTML標簽的字符串可以調(diào)用這個方法進行簡化
- System.out.println(toHtmlString(inputFile, outputFile));} catch (FileNotFoundException e) {
- e.printStackTrace();
- }*/
- System.out.println("恭喜您,轉換成功...");
- }
-
- /**
- * 將word轉換成html文件,并且獲取html文件代碼。
- *
- * @param docFile
- * 需要轉換的文檔
- * @param filepath
- * 文檔中圖片的保存位置
- * @return 轉換成功的html代碼
- * @throws FileNotFoundException
- */
- public static String toHtmlString(String docFile, String filepath)
- throws FileNotFoundException {
- System.out.println("文檔中圖片的保存位置 ==>" + filepath);
- // 轉換word文檔
- OpenOfficePdfConvert opc = new OpenOfficePdfConvert();
- File htmlFile = opc.convertToHtml(docFile, filepath);
- // 獲取html文件流
- StringBuffer htmlSb = new StringBuffer();
- try {
- BufferedReader br = new BufferedReader(new InputStreamReader(
- new FileInputStream(htmlFile)));
- while (br.ready()) {
- htmlSb.append(br.readLine());
- }
- br.close();
- // 刪除臨時文件
- // htmlFile.delete();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- // HTML文件字符串
- String htmlStr = htmlSb.toString();
- // 返回經(jīng)過清潔的html文本
- return clearFormat(htmlStr, filepath);
- }
-
- /**
- * 清除一些不需要的html標記
- *
- * @param htmlStr 帶有復雜html標記的html語句
- *
- * @return 去除了不需要html標記的語句
- */
- protected static String clearFormat(String htmlStr, String docImgPath) {
- // 獲取body內(nèi)容的正則
- String bodyReg = "<BODY .*</BODY>";
- Pattern bodyPattern = Pattern.compile(bodyReg);
- Matcher bodyMatcher = bodyPattern.matcher(htmlStr);
- if (bodyMatcher.find()) {
- // 獲取BODY內(nèi)容,并轉化BODY標簽為DIV
- htmlStr = bodyMatcher.group().replaceFirst("<BODY", "<DIV")
- .replaceAll("</BODY>", "</DIV>");
- }
- // 調(diào)整圖片地址
- htmlStr = htmlStr.replaceAll("<IMG SRC=\"", "<IMG SRC=\"" + docImgPath
- + "/");
- // 把<P></P>轉換成</div></div>保留樣式
- // content = content.replaceAll("(<P)([^>]*>.*?)(<\\/P>)",
- // "<div$2</div>");
- // 把<P></P>轉換成</div></div>并刪除樣式
- htmlStr = htmlStr.replaceAll("(<P)([^>]*)(>.*?)(<\\/P>)", "<p$3</p>");
- // 刪除不需要的標簽
- htmlStr = htmlStr
- .replaceAll(
- "<[/]?(font|FONT|span|SPAN|xml|XML|del|DEL|ins|INS|meta|META|[ovwxpOVWXP]:\\w+)[^>]*?>",
- "");
- // 刪除不需要的屬性
- htmlStr = htmlStr
- .replaceAll(
- "<([^>]*)(?:lang|LANG|class|CLASS|style|STYLE|size|SIZE|face|FACE|[ovwxpOVWXP]:\\w+)=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^>]+)([^>]*)>",
- "<$1$2>");
- return htmlStr;
- }
- }
主要類說明:
OfficeManager是一個接口,主要定義了三個方法:
1.public void start( )啟動OpenOffice服務
2.public void stop( )停止OpenOffice服務
3.public void execute(OfficeTask task)執(zhí)行轉換任務
DefaultOfficeManagerConfiguration是一個實現(xiàn)了OfficeManager接口的實體類,其提供了相關方法配置OpenOffice.org,比如:
public DefaultOfficeManagerConfiguration setOfficeHome(String officeHome)設置OpenOffice.org或者LibreOffice安裝目錄,
windows下默認值為” C:\Program Files\OpenOffice.org 3”(LibreOffice進行相應更改),因此如果OpenOffice.org安裝在別的目錄,必須設置此項。
public DefaultOfficeManagerConfiguration setConnectionProtocol(OfficeConnectionProtocol conn)設置連接協(xié)議,確定使用管道通信,還是socekt通信。
pubcli DefaultOfficeManagerConfiguration setTemplateProfileDir(File templateProfileDir)設定臨時目錄。
除以上幾個方法之外,DefaultOfficeManagerConfiguration還提供了別的配置OpenOffice.org的方法,具體方法可以查詢JODConverter API手冊。
配置完之后,必須要執(zhí)行方法buildOfficeManager(),實現(xiàn)真正的配置。
OfficeDocumentConverter中主要包含convert方法,該方法實際上調(diào)用的是實現(xiàn)OfficeManager接口的類中的execute方法。
整體看起來還是比較簡單的,但對自己也是一種提高,在此特別感謝肖恩也有夢想:http://www.cnblogs.com/luckyxiaoxuan/archive/2012/06/14/2549012.html
本站僅提供存儲服務,所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內(nèi)容,請
點擊舉報。