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 = []
    }
  },
相关推荐
咖啡の猫1 小时前
Vue混入
前端·javascript·vue.js
两个西柚呀5 小时前
未在props中声明的属性
前端·javascript·vue.js
子伟-H58 小时前
App开发框架调研对比
前端
桃子不吃李子8 小时前
axios的二次封装
前端·学习·axios
SteveJrong8 小时前
面试题 - JavaScript
前端·javascript·面试·ecmascript·基础·找工作·红宝书
阿金要当大魔王~~8 小时前
uniapp 页面标签 传值 ————— uniapp 定义 接口
前端·javascript·uni-app·1024程序员节
全栈软件开发9 小时前
uniapp三端影视源码苹果cms自动采集电影视频网站源码前端源码带VIP
前端·uni-app·影视源码
chxii9 小时前
10.4FormData :前端文件上传与表单数据处理的核心工具
前端
AntBlack9 小时前
不当韭菜 : 好像真有点效果 ,想藏起来自己用了
前端·后端·python
楊无好9 小时前
react中props的使用
前端·react.js·前端框架