近日,遇到一個需求,要將 word 文檔轉化爲 pdf 文檔,並且能在 IE 瀏覽器、火狐瀏覽器、谷歌瀏覽器等主流瀏覽器上展示 pdf 內容。
分析:目前在線預覽 word 文檔用的是卓正的 pageoffice 控件,只需要將這份 word 文檔轉成 pdf ,再展示在瀏覽器即可。
一、將 word 文件轉化成 pdf 文件
這個需求,實現的方案有很多,之前也使用過開源的工具進行轉化,比如 openOffice、libreOffice 。他們的好處是提供免費的接口,但是弊端也很明顯,那就是需要在服務器安裝軟件。鑑於項目的拓展和實施現場的增加,決定換一種配置更加簡單的方式來實現需求。
在項目中,引入 aspose.words.jar ,然後只需要簡單的幾行代碼,便可實現 word 文件轉化爲 pdf 文件的功能:
package com.cdw.master;
import java.io.File;
import com.aspose.words.Document;
public class WordToPdf {
public static void main(String[] args) {
try {
// doc路徑
Document document = new Document("C:\\Users\\Administrator\\Desktop\\de115dc0dfc34e1da9a4d8e0b6b3cbd2.doc");
// pdf路徑
File outputFile = new File("C:\\Users\\Administrator\\Desktop\\java實現word轉pdf文件.pdf");
// 操作文檔保存
document.save(outputFile.getAbsolutePath(), com.aspose.words.SaveFormat.PDF);
} catch (Exception e) {
e.printStackTrace();
}
}
}
而後,只需要將生成的 pdf 文件路徑存入數據庫,轉化的簡單需求就完成了。
注意:
linux 服務器下如果出現中文亂碼,那可能是服務器缺少中文字體,安裝中文字體就可以解決。
安裝字體的方法如下:
- 查看系統支持的字體
fc-list- 查看系統支持的中文字體
fc-list :lang=zh- 創建字體目錄(需要root權限,linux系統默認的字體存放路徑爲/usr/share/fonts,沒有可自行創建)
cd /usr/share/fonts
mkdir windows- cp字體文件(將需要新增的字體文件拷貝到指定目錄中)
cd windows
cp ~/fonts/* ./- 目錄和字體文件設置爲所有用戶可見
chmod 755 …/windows
chmod 755 ./*- 應用字體
mkfontscale (如果提示 mkfontscale: command not found,需自行安裝 # yum install mkfontscale )
mkfontdir
fc-cache -fv (如果提示 fc-cache: command not found,則需要安裝# yum install fontconfig )- 再次查看系統支持的字體
fc-list
二、在瀏覽器直接打開 pdf 文件
這個需求,原本的實現方案是,谷歌、火狐等現代瀏覽器,可以直接打開 pdf 文件,不做處理,但是 IE 瀏覽器打開 pdf 文件會顯示下載,這時候,需要安裝 Adobe_Reader 軟件,然後在 IE 瀏覽器的加載項中,啓用 Adobe PDF Reader。
這樣的實現方式對用戶來說需要安裝軟件,不夠友好,於是採用新的方案,引入 pdf.js 來實現 pdf 預覽。
官網:http://mozilla.github.io/pdf.js/
源碼地址:https://github.com/mozilla/pdf.js
下載後,文件目錄如下:
其中代表的含義如下:
├── LICENSE
├── build/
│ ├── pdf.js - 顯示層
│ └── pdf.worker.js - 核心層
└── web/
├── cmaps/ - 字符映射(由核心要求)
├── compressed.tracemonkey-pldi-09.pdf - 測試 pdf
├── debugger.js - 有幫助的PDF調試功能
├── images/ - 觀看者和註釋圖標的圖像
├── l10n.js - 漢化
├── locale/ - 翻譯文件
├── viewer.css - viewer 頁面樣式
├── viewer.html - viewer 頁面
└── viewer.js - viewer js
使用的方法也很簡單,只需要在頁面調用即可,下面給出演示代碼:
<script type="text/javascript">
var pdfFilePath = '${pdfFilePath}';//後臺傳過來的 pdf 文件路徑
$(function() {
showPdf(pdfFilePath);
});
function showPdf(pdfFilePath){
document.getElementsByTagName('iframe')[0].src = "${resource}/pdfjs/web/viewer.html?file="+encodeURIComponent("${root}/writPrint/download.do?path=" + pdfFilePath + "&fileType=pdf");
document.getElementsByTagName('iframe')[0].height = document.documentElement.clientHeight-10;
}
/**
* 頁面變化調整高度
*/
window.onresize = function(){
var fm = document.getElementsByTagName("iframe")[0];
fm.height = window.document.documentElement.clientHeight-10;
}
</script>
<div style="margin:10px auto;">
<iframe src="" width="100%" frameborder="0"></iframe>
</div>
最終效果:
附錄
aspose.words.jar 三個破解版的 jar 包:
點擊下載 aspose.words.jar
pdf.js 調試可用的文件:
點擊下載 調試可用 pdf.js