文章目录
pdf预览组件
前情:项目要的急,就简单的能看pdf文件,没有其他功能
使用的 pdfjs-dist 版本号:2.5.207
接下来,直接上代码
封装组件
<template>
<template v-for="item in pageNum" :key="item">
<canvas :id="`pdf-canvas-${item}`" class="pdf-page" />
</template>
</template>
<script>
import { reactive, toRefs, nextTick, watchEffect } from 'vue'
import * as pdfjs from 'pdfjs-dist'
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry';
import { Toast } from 'vant'
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker
export default {
name: 'PdfViewer',
props: {
url: {type: String, default: ''} // pdf文件路径
},
setup (props, { emit }) {
const state = reactive({
pageNum: 0,
pdfCtx: null
})
const resolvePdf = (url) => {
const loadingTask = pdfjs.getDocument(url)
loadingTask.promise.then(pdf => {
state.pdfCtx = pdf
state.pageNum = pdf.numPages
nextTick(() => {
renderPdf()
})
})
}
const renderPdf = (num = 1) => {
state.pdfCtx.getPage(num).then(page => {
const canvas = document.getElementById(`pdf-canvas-${num}`)
const ctx = canvas.getContext('2d')
const viewport = page.getViewport({ scale: 1 })
// 画布大小,默认值是width:300px,height:150px