效果图
引入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存放目录
具体实现就这么多,欢迎来吐槽!文章来源:https://www.toymoban.com/news/detail-529184.html
结语
一个人久了连喜欢上一个人都好难,不要轻易地拒绝学习新知,因为你所拒绝的不是别人,而是你自己的成长之路。文章来源地址https://www.toymoban.com/news/detail-529184.html
到了这里,关于vue3项目打开本地pdf文件实现方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!