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 = []
    }
  },
相关推荐
ayqy贾杰13 分钟前
Claude Code 重构,并行化或终结 IDE 时代
前端·javascript·面试
SuperChe1 小时前
用AI Native的方式优化前端性能
前端·算法
陈广亮1 小时前
工具指南24-在线CSS Box Shadow生成器
前端
颜酱1 小时前
智能体与工作流:从「想做一个应用」到「能跑通一条链」
前端·javascript·人工智能
前端 贾公子1 小时前
Tailwind CSS OKLCH 颜色与所有浏览器兼容
前端
Lans1 小时前
别再手动管理 NavBackStackEntry 了!ComposeResult:更优雅的 Jetpack Compose 页面通信方案
前端
AI茶水间管理员1 小时前
如何让LLM稳定输出 JSON 格式结果?
前端·人工智能·后端
PILIPALAPENG1 小时前
第2周 Day 4:英语 Agent Web 版上线:从命令行到浏览器
前端·人工智能·python
月弦笙音2 小时前
【monorepo架构】前端 pnpm workspace详解
前端
小嘿前端仔2 小时前
React 19 正式发布:这一次,表单和服务器组件终于"原生"了
前端