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 = []
    }
  },
相关推荐
yinuo8 分钟前
uniapp换肤最佳实践
前端
麦麦大数据13 分钟前
求职推荐大数据可视化平台招聘系统 Vue+Flask python爬虫 前后端分离
vue.js·爬虫·python·信息可视化·flask·推荐算法·协同过滤
XboxYan1 小时前
CSS 小技巧:如何将 img 转换成 background-image
前端·css
辉长六加12 小时前
nodejs和vue安装步骤记录
前端·javascript·vue.js·npm·node.js
coding随想2 小时前
掌控网页的灵魂!揭秘DOM事件中鼠标与滚轮的终极操控术
前端
Jerry3 小时前
Compose 基础知识测试
前端
changuncle3 小时前
Angular初学者入门第三课——工厂函数(精品)
前端·javascript·angular.js
ScottePerk3 小时前
前端安全之XSS和CSRF
前端·安全·xss
PineappleCoder3 小时前
Canvas 复杂交互步骤:从事件监听 to 重新绘制全流程
前端
s3xysteak3 小时前
我要成为vue高手01:上下文
前端·javascript·vue.js