vue3项目打开本地pdf文件实现方法
- 效果图
- 引入pdf插件
- pdf页面封装
- pdf存放目录
- 结语
效果图
引入pdf插件
注意一定要这个版本,不然会报错key.split(...).at is not a function
npm install pdfjs-dist@2.12.313
pdf页面封装
<template>
<div class="pdf-container">
<canvas
v-for="page in pdfPages"
:key="page"
:id="`pdf-canvas-${page}`" />
<el-backtop :right="100" :bottom="100">
<div class="backtop">返回顶部</div>
</el-backtop>
</div>
</template>
<script setup>
//一定要引入下面两个依赖文件
import * as PdfJs from 'pdfjs-dist';
import * as worker from 'pdfjs-dist/build/pdf.worker.entry';
import { nextTick, ref, watchEffect } from 'vue';
import { useRoute, useRouter } from 'vue-router';//引入路由
const route = useRoute();
let pdfDoc = null; // pdf整体实例
const pdfPages = ref(0); // pdf文件总页数
const pdfScale = ref(2.0);// pdf文件预览缩放
const loadFile = (url) => {
PdfJs.GlobalWorkerOptions.workerSrc = worker;
// PdfJs.disableWorker = true;
//通过getDocument获取到PDf文档
const loadingTask = PdfJs.getDocument(url);
loadingTask.promise.then((pdf) => {
pdfDoc = pdf; // 文件流
pdfPages.value = pdf.numPages; // 文件总页数
nextTick(() => {
renderPage(1);
});
})
.catch((error) => {
console.log(error);
});
};
const renderPage = (num) => {
// 页数检测
if (num <= 0 || num > pdfPages.value) {
return;
}
pdfDoc.getPage(num).then((page) => {
const canvas = document.getElementById(`pdf-canvas-${num}`);
const ctx = canvas.getContext('2d');
//dpr和bsr设置pdf的比例尺寸
const dpr = window.devicePixelRatio || 1;
const bsr = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
1;
const ratio = dpr / bsr;
const viewport = page.getViewport({ scale: pdfScale.value }); // 文件显示比例
canvas.width = viewport.width * ratio;
canvas.height = viewport.height * ratio;
canvas.style.width = viewport.width + 'px';
canvas.style.height = viewport.height + 'px';
ctx.setTransform(ratio, 0, 0, ratio, 0, 0); // 设置当pdf文件处于缩小或放大状态时,可以拖动
// 将pdf文件的内容渲染到canvas中
const renderContext = {
canvasContext: ctx,
viewport: viewport
};
page.render(renderContext);
if (num < pdfPages.value) {
renderPage(num + 1);
}
})
.catch((error) => {
console.log(error);
});
};
watchEffect(() => {
//我这里是菜单直接跳转,所以通过获取路由
let pdfUrl = `/pdfs${route.query.pdfUrl}`;
loadFile(pdfUrl);
});
</script>
<style scoped>
.pdf-container {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
height: 100%;
}
.backtop {
height: 100%;
width: 100%;
background-color: #ffffff;
box-shadow: 0px 0px 6px rgba(0, 0, 0, .12);
text-align: center;
line-height: 20px;
font-size: 16px;
color: #1989fa;
}
</style>
pdf存放目录
具体实现就这么多,欢迎来吐槽!
结语
一个人久了连喜欢上一个人都好难,不要轻易地拒绝学习新知,因为你所拒绝的不是别人,而是你自己的成长之路。