使用版本
使用vue3 + vite版本开发
npm install pdfjs-dist@2.12.313 -S
在public文件夹存放pdf.worker.js
安装好包之后在最外层public文件夹存放pdf.worker.js。此文件在node_modules/pdfjs-dist/build/pdf.worker.js
预览组件
<template>
<div class="pdf-container" id="pdfRef">
<canvas
v-for="pageIndex in pdfPages"
class="canvas-x"
:id="`pdf-canvas-${pageIndex}`"
:key="pageIndex" />
</div>
</template>
<script setup>
import * as PDF from 'pdfjs-dist';
import { useRoute } from "vue-router";
PDF.GlobalWorkerOptions.workerSrc = '/pdf.worker.js';
const route = useRoute();
const props = defineProps({
// 文件路径
pdfUrl: {
type: String,
default: ""
}
})
let pdfDoc = null;
const pdfPages = ref(0)
const pdfScale = ref(0.63);
const renderPdf = (num = 1) => {
pdfDoc.getPage(num).then(page => {
const canvas = document.getElementById(`pdf-canvas-${num}`)
const ctx = canvas.getContext('2d')
const viewport = page.getViewport({ scale: 1 })
// 画布大小
canvas.height = viewport.height
canvas.width = viewport.width
// 画布的dom大小, 设置移动端,宽度设置铺满整个屏幕
const clientWidth = document.body.clientWidth
canvas.style.width = clientWidth + 'px'
// 根据pdf每页的宽高比例设置canvas的高度
canvas.style.height = clientWidth * (viewport.height / viewport.width) + 'px'
page.render({
canvasContext: ctx,
viewport
})
if (num < pdfPages.value) {
renderPdf(num + 1)
}
})
}
const resolvePdf = async (url) => {
const loadingTask = PDF.getDocument({
url,
cMapUrl: '/cmaps/',
cMapPacked: true
})
loadingTask.promise.then(pdf => {
pdfDoc = pdf;
pdfPages.value = pdf.numPages;
nextTick(() => {
renderPdf()
})
})
}
watch(() => props.pdfUrl, newVal => {
if(newVal) {
resolvePdf(props.pdfUrl);
}
}, { immediate: true })
onMounted(() => {
const { url } = route.query;
if(url) {
nextTick(() => {
resolvePdf(url);
})
}
})
</script>
<style lang="scss" scoped>
.pdf-container{
width: 100%;
height: 100%;
}
.img-wrapper{
width: 222px;
height: 80px;
display: none;
background: rgba(230, 54, 51, 0.2);
.sign-picture{
width: 222px;
height: 80px;
}
}
</style>
关于嵌入app里面报错globalThis的解决方法
在html文件的head中嵌入此段代码
<head>
<script>
this.globalThis || (this.globalThis = this)
</script>
</head>