vue项目pdf文件的预览

1.下载

您可以在以下网址下载pdfjsLib:https://github.com/mozilla/pdf.js

pdfjsLib是一个开源项目,您可以在GitHub上找到其源代码和相关资源。

2.放置文件位置

3.进入

在index.html引入

bash 复制代码
<script src="<%= BASE_URL %>static/pdfjs-dist/build/pdf.js"></script>

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

bash 复制代码
<div class="createModel">
      <pdf-viewer :url="pdfUrl" ref="pdf" />
    </div>
bash 复制代码
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组件中

bash 复制代码
methods: {
    init () {
      this.renderPDF();

    },
    async renderPDF () {
      if (!this.url) return
      let containerWidth = document.querySelector('.pdf-container').offsetWidth
      this.scale = containerWidth / 594
      const 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 = 0
      this.canvasEls = []
    }
  },
相关推荐
知识分享小能手13 小时前
React学习教程,从入门到精通,React 组件生命周期详解(适用于 React 16.3+,推荐函数组件 + Hooks)(17)
前端·javascript·vue.js·学习·react.js·前端框架·vue3
面向星辰13 小时前
html音视频和超链接标签,颜色标签
前端·html·音视频
lxh011313 小时前
LRU 缓存
开发语言·前端·javascript
yangzhi_emo14 小时前
ES6笔记5
前端·笔记·es6
wow_DG14 小时前
【Vue2 ✨】Vue2 入门之旅 · 进阶篇(二):虚拟 DOM 与 Diff 算法
开发语言·javascript·vue.js·算法·前端框架
Hexene...15 小时前
【前端Vue】el-dialog关闭后黑色遮罩依然存在如何解决?
前端·javascript·vue.js·elementui·前端框架
Jay_See15 小时前
JC链客云——项目过程中获得的知识、遇到的问题及解决
前端·javascript·vue.js
勘察加熊人15 小时前
python将pdf转txt,并切割ai
数据库·python·pdf
@小匠15 小时前
iText与OpenPDF使用差异及中文处理完全指南
java·pdf