😉 你好呀,我是爱编程的Sherry,很高兴在这里遇见你!我是一名拥有十多年开发经验的前端工程师。这一路走来,面对困难时也曾感到迷茫,凭借不懈的努力和坚持,重新找到了前进的方向。我的人生格言是——认准方向,坚持不懈,你终将迎来辉煌!欢迎关注我😁,我将在这里分享工作中积累的经验和心得,希望我的分享能够给你带来帮助。
文章目录
功能描述
点击文件名称,预览pdf文件,要求只能预览,不能做其他操作。
实现效果展示
项目环境介绍
node v18+
pdfjs-dist v2.16.105
vue3
nuxt3
typescript
实现步骤
安装pdfjs-dist
npm i pdfjs-dist@2.16.105
封装独立pdf组件
<template>
<Modal v-model="visible" width="1300" footer-hide @on-cancel="cancel">
<div id="pdf-view" class="page-center">
<canvas v-for="page in state.pdfPages" :key="page" id="pdfCanvas" />
<div id="text-view"></div>
</div>
</Modal>
</template>
<script>
import "pdfjs-dist/web/pdf_viewer.css";
import * as PDF from "pdfjs-dist";
PDF.GlobalWorkerOptions.workerSrc = "/pdf.worker.js";
const pdf = "/科学第一单元 声音 知识点.pdf";
let pdfDoc = null;
export default {
data() {
return {
state: {
// 文件路径
pdfPath: pdf,
// 总页数
pdfPages: 1,
// 页面缩放
pdfScale: 2,
},
visible: false,
};
},
mounted() {
// this.loadFile(this.state.pdfPath)
},
methods: {
init(url) {
this.visible = true;
this.state.pdfPath = url
console.log('pdf url', url)
this.$nextTick(() => {
this.loadFile(this.state.pdfPath);
})
// this.loadFile(this.state.pdfPath);
},
cancel() {
this.visible = false;
},
loadFile(url) {
PDF.getDocument({
url,
cMapUrl: "https://cdn.jsdelivr.net/npm/pdfjs-dist@2.16.105/cmaps/",
cMapPacked: true,
}).promise.then((pdf) => {
pdfDoc = pdf;
// 获取pdf文件总页数
this.state.pdfPages = pdf.numPages;
this.$nextTick(() => {
this.renderPage(1); // 从第一页开始渲染
});
});
},
renderPage(num) {
pdfDoc.getPage(num).then((page) => {
const canvas = document.getElementById("pdfCanvas");
const ctx = canvas.getContext("2d");
const viewport = page.getViewport({ scale: this.state.pdfScale });
canvas.width = viewport.width;
canvas.height = viewport.height;
const renderContext = {
canvasContext: ctx,
viewport,
};
page.render(renderContext);
});
},
},
};
</script>
在父组件中使用
<script lang="ts" setup>
import PdfFrame from '@/components/PdfFrame';
const pdfFrameRef = ref<InstanceType<typeof PdfFrame> | null>(null);
const viewFile = (url:string) => {
const path = '/file' + url
pdfFrameRef.value?.init(path)
}
</script>
<template>
<div>
<a @click="viewFile(info.attachPath)">{{ info.attachName }}</a>
</div>
<PdfFrame ref="pdfFrameRef" />
</template>
注意:info.attachPath 是pdf文件的地址;info.attachName是文件名称。文件的地址需要换成自己的,如果文件打不开要先检查文件的地址是否正确。
常见问题
No “GlobalWorkerOptions.workerSrc” specified.
起初没有配置GlobalWorkerOptions.workerSrc,报了下面的错误
需要将pdfjs-dist包中的build文件夹下的pdf.worker.js文件复制到public文件夹下
然后添加下面这行代码
PDF.GlobalWorkerOptions.workerSrc = "/pdf.worker.js";
跨域问题
Access to fetch at “url” from origin “url” present on the request, If an opaque responseserves your needs, set the request s mode to ‘no-cors’ to fetch the resource with CORS disabled.
解决跨域问题需要使用代理,我的项目配置如下
nitro: {
devProxy: {
'/file': {
target: 'https://yours.cn/file', // 这里是接口地址
changeOrigin: true,
prependPath: true,
},
},
}
文件地址不正确引发的报错
假如文件地址不正确会报下面这种错误,请先检查文件路径是否能够正常访问。
总结
以上就是如何使用pdfjs-dist实现文件预览功能,按照上面的步骤如果有其他问题,欢迎在评论区给我留言哦!