一、在本地浏览pdf(直接将element-dialog 和 iframe相结合)需要将要浏览的pdf放入static文件夹下面
点击打开 Dialog
在data中直接定义 dialogVisible
data() { return { dialogVisible: false } }
以上方法便可直接在本地查看pdf,无需添加pdf.js
二、通过后台传来的数据,展示pdf
在展示之前,要先接收到后台的axios的数据
1. api.js中定义
export const decision = data => ajaxHttp('/home/dynamic/decision/page', data, 'POST')
2.要接受的页面引入
import { decision } from '../api/api'
3.开始接收后台
async getList () { this.loading = true let params = { type: 1 } const res = await decision(params) if (res.data.code === 1) { this.list = res.data.data console.log(this.list) } else { this.$message({type: 'success', message: res.data.msg}) } this.listNumber = this.list.length this.loading = false },
接收后不要忘记在mounted里面定义如何开始
mounted () { this.getList() }
4.定义一下显示出来的和点击事件的位置
{ {item.title}}
5.定义el-dialog (定义之前要先引入,查看element.api)
上一页 下一页
6.写下如下方法
handleCurrentChange (val) { this.currentPage = val }, clickPDFfn (item) { this.loading = true this.otherDialogVisible = true this.showPDF('http://compre-tj-api.gov.bbdtek.com/repository/readPDF?path=' + item) }, showPDF (url) { let _this = this this.$pdf.getDocument(url).then(function (pdf) { _this.pdfDoc = pdf _this.$nextTick(() => { _this.renderPage(1) }) }) }, renderPage (num) { this.pageRendering = true let _this = this this.pdfDoc.getPage(num).then(function (page) { let canvas = document.getElementById('canvas1') let ctx = canvas.getContext('2d') let dpr = window.devicePixelRatio || 1 let bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1 let ratio = dpr / bsr let viewport = page.getViewport(screen.availWidth / page.getViewport(1).width) canvas.height = viewport.height * ratio canvas.width = viewport.width * ratio canvas.style.width = '100%' canvas.style.height = '100%' ctx.setTransform(ratio, 0, 0, ratio, 0, 0) // Render PDF page into canvas context var renderContext = { canvasContext: canvas.getContext('2d'), viewport: viewport } var renderTask = page.render(renderContext) // Wait for rendering to finish renderTask.promise.then(function () { _this.pageRendering = false if (_this.pageNumPending !== null) { // New page rendering is pending this.renderPage(_this.pageNumPending) _this.pageNumPending = null } }) }) }, queueRenderPage (num) { console.log(num) if (this.pageRendering) { this.pageNumPending = num } else { this.renderPage(num) } }, onPrevPage () { if (this.pageNum <= 1) { return } this.pageNum-- this.queueRenderPage(this.pageNum) }, onNextPage () { if (this.pageNum >= this.pdfDoc.numPages) { return } this.pageNum++ this.queueRenderPage(this.pageNum) }
7.添加以下属性
data () { return { listNumber: 0, loading: false, otherDialogVisible: false, pdfDoc: null, pageNum: 1, pageNumPending: null, currentPage: 1, list: [] } }
通过以上方法即可连接后台直接浏览pdf
注: 后台pdf地址定义为 filePath1