需求:
使用JS實現PDF文件預覽功能
備選方案:
- 使用ViewerJS,官網 http://viewerjs.org/
- 使用PDFJS,官網 https://mozilla.github.io/pdf.js/
結論:
通過研究發現,Viewer JS預覽pdf文件,其pdf文件只能url地址,不支持獲取文件流到客戶端,生成blob地址預覽。而PDFJS能夠支持
代碼實踐:
<div class="modal inmodal fade" id="previewModal" tabindex="-1" role="dialog" aria-hidden="true"> <div style="width:60%;height:90%" class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-body" style="padding:0; height:700px"> <iframe id="iframePreview" width='100%' height='700' allowfullscreen webkitallowfullscreen></iframe> </div> </div> </div> </div>
this.previewFile = function(fileUrl,fileType) {
if (fileType === 'pdf') {
var tmpUrl = 'vendor/pdfjs/web/viewer.html?file=' + encodeURIComponent(fileUrl);
$("#iframePreview").attr("src", tmpUrl);
angular.element('#previewModal').modal();
}
};