当前位置:首页 > 编程笔记 > 正文
已解决

vue项目pdf文件的预览

来自网友在路上 159859提问 提问时间:2023-11-11 17:43:39阅读次数: 59

最佳答案 问答题库598位专家为你答疑解惑

1.下载
您可以在以下网址下载pdfjsLib:https://github.com/mozilla/pdf.js
pdfjsLib是一个开源项目,您可以在GitHub上找到其源代码和相关资源。
2.放置文件位置
在这里插入图片描述
3.进入
在index.html引入

<script src="<%= BASE_URL %>static/pdfjs-dist/build/pdf.js"></script>

4.获取pdf文件的信息并转换为链接

<div class="createModel"><pdf-viewer :url="pdfUrl" ref="pdf" /></div>
methods: {// 初始化数据initDate () {this.getPDFURL()},async getPDFURL () {if (this.fileObj.id) {try {const data = await uploadApi.getPDF(this.fileObj.id)const blob = new Blob([data]);this.pdfUrl = window.URL.createObjectURL(blob)this.$nextTick(() => {this.$refs.pdf.init()})} catch (error) {console.log(error)this.clearData()}}},clearData () {if (this.pdfUrl) {window.URL.revokeObjectURL(this.pdfUrl)}this.pdfUrl = ''this.$nextTick(() => {this.$refs.pdf?.destroyedData()})}},beforeDestroy () {this.clearData()},

5.在PdfViewer.vue组件中

methods: {init () {this.renderPDF();},async renderPDF () {if (!this.url) returnlet containerWidth = document.querySelector('.pdf-container').offsetWidththis.scale = containerWidth / 594const pdf = await pdfjsLib.getDocument(this.url).promise;console.log('pdf', pdf)this.numPages = pdf.numPages;this.$nextTick(async () => {for (let i = 1; i <= this.numPages; i++) {const canvasId = 'pdfCanvas-' + i;const canvasEl = this.$refs[canvasId][0];this.canvasEls.push(canvasEl);const page = await pdf.getPage(i);const viewport = page.getViewport({ scale: this.scale });canvasEl.height = viewport.height;canvasEl.width = viewport.width;const canvasContext = canvasEl.getContext('2d');await page.render({canvasContext,viewport,}).promise;}})},destroyedData () {this.numPages = 0this.canvasEls = []}},
查看全文

99%的人还看了

相似问题

猜你感兴趣

版权申明

本文"vue项目pdf文件的预览":http://eshow365.cn/6-37823-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!