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