Vue + ElementUI项目中使用vue-pdf实现简单预览,供大家参考,具体内容如下
1、安装 vue-pdf
npm install --save vue-pdf
2、在vue页面中导入对应的组件
我这是通过点击 预览 按钮 获取id打开一个dialog来实现
<!--PDF 预览--> <el-dialog :title="PDF 预览" :visible.sync="viewVisible" width="80%" center @close='closeDialog'> <div style="margin-bottom: 15px; text-align: right"> <el-button type="primary" size="small" @click.stop="previousPage"> 上一页 </el-button> <el-button type="primary" size="small" @click.stop="nextPage"> 下一页 </el-button> <span>当前第{{pdfPage}}页 / 共{{pageCount}}页</span> </div> <div > <pdf :src="src" :page="pdfPage" @num-pages="pageCount = $event" @page-loaded="pdfPage = $event" style="display: inline-block; width: 100%" ></pdf> </div> </el-dialog>
<script> import pdf from 'vue-pdf'; export default { components: { pdf }, data() { return { //PDF预览 viewVisible: false, src: null, pdfPage : 1, pageCount: 0, } }, methods:{ //PDF预览 previewPDF(row){ this.src = pdf.createLoadingTask(documentConstants.previewPDFUrl+row.contractId); this.src.then(pdf => { this.viewVisible = true; }); }, //关闭窗口初始化PDF页码 closeDialog(){ this.pdfPage = 1; }, //PDF改变页数 previousPage(){ var p = this.pdfPage p = p>1?p-1:this.pageCount this.pdfPage = p }, nextPage(){ var p = this.pdfPage p = p<this.pageCount?p+1:1 this.pdfPage = p } } } </script>
3、Controller的返回
@RequestMapping(value = "/previewPDF/{contractId}") public ResponseEntity<byte[]> previewPDF(@PathVariable Long contractId) throws TException, IOException { ContractAttachmentTmpModelDTO model = contractScanManagementRpcService.queryContractAttachmentTmp(contractId); HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", model.getAttachmentName()); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(model.getAttachmentData(), headers, HttpStatus.OK); }
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!