OFFICE 文檔在線預覽方案很多:
- 服務器先轉換為PDF,再轉換為SWF,最后通過網頁加載Flash預覽,比如flexpaper
- Office文檔直接轉換為SWF,通過網頁加載Flash預覽
- 微軟的Office365
- 在瀏覽器中直接打開
- 轉換為html
今天,我們要用的方案是轉換為html來預覽。
技術方案:
- office文檔轉換為pdf:使用libreoffice
- pdf轉html,使用pdf2htmlex
測試環境:
操作系統:ubuntu 12.04
1. office文檔轉pdf
1.1 安裝libreoffice
apt-get install libreoffice-common
1.2 啟動轉換服務
soffice --accept="socket,host=127.0.0.1,port=2002;urp;" --nofirststartwizard
1.3 文檔轉換
網上一般介紹的都是使用JODConverter ,通過java來調用轉換服務,其實還有一種替代方案,就是使用pyodconverter,python版本的轉換腳本https://github.com/mirkonasato/pyodconverter/
下載后,進行測試:
python DocumentConverter.py Website_Information_Form.doc new.pdf
soffice 可以正常轉換為pdf,但是中文顯示為亂碼
1.4 中文亂碼問題修復
google一下,亂碼問題大概是字體缺失的問題,於是嘗試將windows下的字體拷貝過去,復制windows下的字體到/usr/share/fonts下,然后刷新字體緩存
sudo fc-cache -fv 2>&1 | grep failed | cut -f1 -d":" | xargs -i sudo touch {} && sudo fc-cache -fv
再重啟轉換服務,再次測試,已經OK了!
2.pdf轉html
pdf轉html,使用國人開源的pdf2htmlex,一開始嘗試通過源碼編譯安裝,依賴組件太多,安裝非常麻煩!感興趣的可以執行編譯安裝,參見(https://github.com/coolwanglu/pdf2htmlEX/wiki/Building)
下面介紹簡單安裝方式:
2.1 通過apt安裝
sudo add-apt-repository ppa:coolwanglu/pdf2htmlex
sudo apt-get update
sudo apt-get install pdf2htmlex
2.2 測試pdf2htmlex
pdf2htmlEX --zoom 1.3 xiaoshujiang.pdf
可以看到,當前目錄生成了xiaoshujiang.html
2.3 轉換腳本
寫一個腳本,將兩次轉換放到一起,方便調用:
#convert2html.sh
temp=$(date +%Y%m%d%H%m%s)
python DocumentConverter.py $1 ${temp}.pdf
pdf2htmlEX --zoom 1.3 $temp.pdf
mv $temp.html $2
rm $temp.pdf
3. 測試
3.1 word (doc.docx)測試
convert2html.sh imo雲辦公室-私有雲用戶使用手冊V2.0.doc imo-doc.html
效果:
3.2 表格 (xls)測試
convert2html.sh xxx.xlsx xxx.html
3.3 PPT (pptx)測試
./convert.sh xxx.pptx xxx.html
4. 總結
本文介紹了一種在服務端將office文檔轉換為html以方便預覽的方法。
實際使用時,可以將生成好的html放到網站路徑下,通過攔截器,設置訪問權限。