Vue使用vue-pdf实现PDF流文件预览
2023-12-11 本文已影响0人
Frank_Fang
先安装依赖
npm install vue-pdf
Template
<pdf v-for="currentPage in pdfPages" :key="currentPage" :src="pdfUrl" :page="currentPage" class="preview-pdf mb-3" @loaded="loadPdfHandler"></pdf>
Script
import Pdf from "vue-pdf"
export default {
name: 'PdfPreview',
components: {
Pdf
},
data () {
return {
pdfUrl: '',
pdfPages: 1,
currentPage: 1
}
},
methods: {
async getPdfUrl () {
...
// 获取文件流之后
const blob = new Blob([result], { type: 'application/octet-stream' })
const url = window.URL.createObjectURL(blob)
this.pdfUrl = Pdf.createLoadingTask({ url })
this.loadPdfHandler()
},
loadPdfHandler () {
this.pdfUrl.promise.then(pdf => {
// 获取pdf文件相关信息,页码等
this.pdfPages = pdf.numPages
})
this.currentPage = 1 // 加载的时候先加载第一页
// 强制刷新
// this.$forceUpdate()
}
},
mounted () {
this.getPdfUrl()
}
}
Style
.preview-pdf {
border: 1px solid #ddd;
box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}