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 = []
    }
  },
相关推荐
Rysxt_28 分钟前
Vue文件下载功能完整指南:从基础实现到进阶实战
前端·javascript·vue.js
一 乐38 分钟前
智慧养老|基于springboot+小程序社区养老保障系统设计与实现(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端·小程序
冰暮流星40 分钟前
css3网格布局2
前端·css·css3
JIseven1 小时前
uniapp页面新手引导
java·前端·uni-app
烛阴1 小时前
代码的“病历本”:深入解读C#常见异常
前端·c#
IT_陈寒1 小时前
Python 3.12 新特性实战:10个提升开发效率的隐藏技巧大揭秘
前端·人工智能·后端
老华带你飞2 小时前
旅游|基于Java旅游信息推荐系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·旅游
dangdang___go2 小时前
文件操作2+程序的编译和链接(1)
java·服务器·前端
czliutz2 小时前
使用pdfplumber库处理pdf文件获取文本图片作者等信息
python·pdf
西西学代码2 小时前
Flutter中常用的UI设计
前端·flutter·ui