1.下載pdfjs插件鏈接:http://mozilla.github.io/pdf.js/
2.pdfjs插件引入項目中:
①本地運行可將pdfjs放入vue項目的static文件夾下(本項目放在/static/pdf/下)
②如果在linux服務器部署建議將pdfjs單獨放一個文件夾,打包可能引起訪問路徑的文件名發生變化,如果你有更好的方法,everything will be ok!
3.vue搞一搞
<el-button size="small" type="primary" @click="pdfPrint()">打印預覽</el-button> pdfPrint() { this.$http({ //首先需要生成pdf文件 url: `/project/outPdf/exportPdf`, method: 'post', data: this.dataForm }).then(({data}) => { if (data && data.code === 0) { let url = '' //根據本地和linux服務器pdf存放的位置進行配置 if (this.$http.BASE_URL === 'http://127.0.0.1') { url = '/static/pdf/web/viewer.html?file=' } else { url = '/pdf/web/viewer.html?file=' } let pdfUrl = encodeURIComponent(this.$http.BASE_URL + `/project/outPdf/pdfFileStream?token=${this.$cookie.get('token')}&fileName=${fileName}`) window.open(url + pdfUrl) } }) }
4.后台返回文件流來一波
/** *返回文件流 **/ @RequestMapping("/pdfFileStream") public void pdfStreamHandeler(String fileName,HttpServletRequest request, HttpServletResponse response) { try { String pdfPath = filePath + fileName; File file = new File(pdfPath); byte [] data = null; FileInputStream inputStream = null; inputStream = new FileInputStream(file); data=new byte[inputStream.available()]; inputStream.read(data); response.getOutputStream().write(data); inputStream.close(); response.setHeader("Access-Control-Allow-Origin", "*"); } catch (Exception e) { e.printStackTrace(); } }
我踩過的坑希望大家都能跳過去~