vue pdf预览
时间: 2023-11-17 16:03:34 浏览: 116
以下是两种在Vue中实现PDF文件在线预览的方法:
1. 使用vue-pdf组件
```vue
<template>
<div>
<pdf :src="pdfUrl" :page="1" :show-all="false"></pdf>
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
components: {
pdf
},
data() {
return {
pdfUrl: 'your_pdf_url'
}
}
}
</script>
```
2. 使用pdf.js库
```vue
<template>
<div>
<canvas ref="pdfCanvas"></canvas>
</div>
</template>
<script>
import pdfjsLib from 'pdfjs-dist'
export default {
data() {
return {
pdfUrl: 'your_pdf_url',
pdfDoc: null,
pageNum: 1,
pageRendering: false,
pageNumPending: null,
scale: 1.5,
canvas: null,
ctx: null
}
},
mounted() {
this.canvas = this.$refs.pdfCanvas
this.ctx = this.canvas.getContext('2d')
this.renderPage(this.pageNum)
},
methods: {
renderPage(num) {
this.pageRendering = true
this.pdfDoc.getPage(num).then(page => {
const viewport = page.getViewport({ scale: this.scale })
this.canvas.height = viewport.height
this.canvas.width = viewport.width
const renderContext = {
canvasContext: this.ctx,
viewport: viewport
}
const renderTask = page.render(renderContext)
renderTask.promise.then(() => {
this.pageRendering = false
if (this.pageNumPending !== null) {
this.renderPage(this.pageNumPending)
this.pageNumPending = null
}
})
})
},
queueRenderPage(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)
}
},
async created() {
const loadingTask = pdfjsLib.getDocument(this.pdfUrl)
this.pdfDoc = await loadingTask.promise
}
}
</script>
```
阅读全文