|
引言:突然接到任務(wù),要將word或者ppt轉(zhuǎn)換成HTML的格式在頁面上顯示,類似于百度文庫的效果。以前也聽說過,覺得用java實(shí)現(xiàn)起來還是很簡單的。于是我就帶著我的任務(wù)以及我的好奇心出發(fā)了,在網(wǎng)上找了些資料,最終決定用OpenOffice。
首先簡單的介紹下轉(zhuǎn)換需要的環(huán)境:
1、轉(zhuǎn)換組要安裝openoffice軟件(下載地址:http://download./index.html)
2、需要下載jodconverter包
在此我提供了jodconverter包(包括jodconverter2、jodconverter3,注:jodconverter2需要手動(dòng)啟動(dòng)openoffice服務(wù),如有不清楚的地方可以在我文章下面留言),下載請點(diǎn)擊...
JODConverter是一個(gè)開源文檔轉(zhuǎn)換工具,既可以應(yīng)用于Linux平臺(tái),也可其應(yīng)用于Windows平臺(tái)。其基于OpenOffice.org或者LibreOffice。因此,文檔轉(zhuǎn)換服務(wù)器上必須安裝有OpenOffice或者LibreOffice。
目前最新版本的JODConverter為JODConverter3.0,它要求JDK1.5以上的Java環(huán)境,同時(shí)還需要OpenOffice.org 3.x版本。本文基于最新版本3.0設(shè)計(jì)實(shí)現(xiàn),如果是版本為2,則有不同的實(shí)現(xiàn)。(版本2需要手動(dòng)啟動(dòng)OpenOffice.org服務(wù),或者創(chuàng)建Windows服務(wù)設(shè)置為開機(jī)啟動(dòng),而版本3提供了開啟服務(wù)的接口,在此我使用的是版本3)
一切準(zhǔn)備就緒那就直接開始了...
下面是一個(gè)比較完整的例子,可以實(shí)現(xiàn) WORD==>HTML 、PPT==>HTML、WORD==>PDF、PPT==>PDF的轉(zhuǎn)換。
- 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;
-
- //轉(zhuǎn)換文檔為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文檔到服務(wù)器
-
- //2、服務(wù)器調(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");
- // 開啟服務(wù)器
- startService();
- // 進(jìn)行轉(zhuǎn)換
- System.out.println("進(jìn)行文檔轉(zhuǎn)換轉(zhuǎn)換:" + inputFile + " --> " + outputFile);
- OfficeDocumentConverter converter = new OfficeDocumentConverter(
- officeManager);
- converter.convert(new File(inputFile), wantFile);
- // 關(guān)閉服務(wù)器
- stopService();
- System.out.println();
- return wantFile;
-
- }
-
- // 打開服務(wù)器
- public static Boolean startService() {
- DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
- try {
- System.out.println("準(zhǔn)備啟動(dòng)服務(wù)....");
- configuration.setOfficeHome(OFFICE_HOME);// 設(shè)置OpenOffice.org安裝目錄
- configuration.setPortNumbers(port); // 設(shè)置轉(zhuǎn)換端口,默認(rèn)為8100
- configuration.setTaskExecutionTimeout(1000 * 60 * 5L);// 設(shè)置任務(wù)執(zhí)行超時(shí)為5分鐘
- configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);// 設(shè)置任務(wù)隊(duì)列超時(shí)為24小時(shí)
-
- officeManager = configuration.buildOfficeManager();
- officeManager.start(); // 啟動(dòng)服務(wù)
- System.out.println("office轉(zhuǎn)換服務(wù)啟動(dòng)成功!");
- return true;
- } catch (Exception ce) {
- System.out.println("office轉(zhuǎn)換服務(wù)啟動(dòng)失敗!詳細(xì)信息:" + ce);
- return false;
- }
- }
-
- // 關(guān)閉服務(wù)器
- public static void stopService() {
- System.out.println("關(guān)閉office轉(zhuǎn)換服務(wù)....");
- if (officeManager != null) {
- officeManager.stop();
- }
- System.out.println("關(guān)閉office轉(zhuǎn)換成功!");
- }
-
- /*
- * 進(jìn)行測試轉(zhuǎn)換是否成功
- */
- 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標(biāo)簽的字符串可以調(diào)用這個(gè)方法進(jìn)行簡化
- System.out.println(toHtmlString(inputFile, outputFile));} catch (FileNotFoundException e) {
- e.printStackTrace();
- }*/
- System.out.println("恭喜您,轉(zhuǎn)換成功...");
- }
-
- /**
- * 將word轉(zhuǎn)換成html文件,并且獲取html文件代碼。
- *
- * @param docFile
- * 需要轉(zhuǎn)換的文檔
- * @param filepath
- * 文檔中圖片的保存位置
- * @return 轉(zhuǎn)換成功的html代碼
- * @throws FileNotFoundException
- */
- public static String toHtmlString(String docFile, String filepath)
- throws FileNotFoundException {
- System.out.println("文檔中圖片的保存位置 ==>" + filepath);
- // 轉(zhuǎn)換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();
- // 刪除臨時(shí)文件
- // 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標(biāo)記
- *
- * @param htmlStr 帶有復(fù)雜html標(biāo)記的html語句
- *
- * @return 去除了不需要html標(biāo)記的語句
- */
- 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)容,并轉(zhuǎn)化BODY標(biāo)簽為DIV
- htmlStr = bodyMatcher.group().replaceFirst("<BODY", "<DIV")
- .replaceAll("</BODY>", "</DIV>");
- }
- // 調(diào)整圖片地址
- htmlStr = htmlStr.replaceAll("<IMG SRC=\"", "<IMG SRC=\"" + docImgPath
- + "/");
- // 把<P></P>轉(zhuǎn)換成</div></div>保留樣式
- // content = content.replaceAll("(<P)([^>]*>.*?)(<\\/P>)",
- // "<div$2</div>");
- // 把<P></P>轉(zhuǎn)換成</div></div>并刪除樣式
- htmlStr = htmlStr.replaceAll("(<P)([^>]*)(>.*?)(<\\/P>)", "<p$3</p>");
- // 刪除不需要的標(biāo)簽
- 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是一個(gè)接口,主要定義了三個(gè)方法:
1.public void start( )啟動(dòng)OpenOffice服務(wù)
2.public void stop( )停止OpenOffice服務(wù)
3.public void execute(OfficeTask task)執(zhí)行轉(zhuǎn)換任務(wù)
DefaultOfficeManagerConfiguration是一個(gè)實(shí)現(xiàn)了OfficeManager接口的實(shí)體類,其提供了相關(guān)方法配置OpenOffice.org,比如:
public DefaultOfficeManagerConfiguration setOfficeHome(String officeHome)設(shè)置OpenOffice.org或者LibreOffice安裝目錄,
windows下默認(rèn)值為” C:\Program Files\OpenOffice.org 3”(LibreOffice進(jìn)行相應(yīng)更改),因此如果OpenOffice.org安裝在別的目錄,必須設(shè)置此項(xiàng)。
public DefaultOfficeManagerConfiguration setConnectionProtocol(OfficeConnectionProtocol conn)設(shè)置連接協(xié)議,確定使用管道通信,還是socekt通信。
pubcli DefaultOfficeManagerConfiguration setTemplateProfileDir(File templateProfileDir)設(shè)定臨時(shí)目錄。
除以上幾個(gè)方法之外,DefaultOfficeManagerConfiguration還提供了別的配置OpenOffice.org的方法,具體方法可以查詢JODConverter API手冊。
配置完之后,必須要執(zhí)行方法buildOfficeManager(),實(shí)現(xiàn)真正的配置。
OfficeDocumentConverter中主要包含convert方法,該方法實(shí)際上調(diào)用的是實(shí)現(xiàn)OfficeManager接口的類中的execute方法。
整體看起來還是比較簡單的,但對自己也是一種提高,在此特別感謝肖恩也有夢想:http://www.cnblogs.com/luckyxiaoxuan/archive/2012/06/14/2549012.html
|