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(); } }
我踩过的坑希望大家都能跳过去~