• vue整合pdfjs,实现pdf文件预览


    背景

    项目上要求实现pdf文件格式的预览。

    分析

    pdf格式的文件浏览器是可以直接打开的。所以只需要返回pdf文件的文件流,就可以直接预览文件,通过这种方式打开,整个页面全是pdf的文件内容。需求是要求预览时,页面上要加上特定的标题格式,所以直接把文件流在浏览器打开的方式行不通。通过收集相关资料,找到pdfjs插件以支持文件的预览。

    实现

    1.vue中引入pdfjs依赖

    npm install pdfjs-dist --save
    

    2.使用canvas当预览pdf文件的画布

    <canvas v-for="page in pages" :id="'the-canvas'+page" :key="page"></canvas>
    

    3.调用pdfjs api进行文档渲染

    _renderPage (num) {
         this.pdfDoc.getPage(num).then((page) => {
           let canvas = document.getElementById('the-canvas' + num)
          let ctx = canvas.getContext('2d')
           let dpr = window.devicePixelRatio || 1
           let bsr = ctx.webkitBackingStorePixelRatio ||
             ctx.mozBackingStorePixelRatio ||
             ctx.msBackingStorePixelRatio ||
             ctx.oBackingStorePixelRatio ||
             ctx.backingStorePixelRatio || 1
           let ratio = dpr / bsr
           let viewport = page.getViewport(screen.availWidth / page.getViewport(1).width)
           canvas.width = viewport.width * ratio
           canvas.height = viewport.height * ratio
           canvas.style.width = viewport.width + 'px'
           canvas.style.height = viewport.height + 'px'
          ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
           let renderContext = {
             canvasContext: ctx,
             viewport: viewport
           }
           page.render(renderContext)
           if (this.pages > num) {
             this._renderPage(num + 1)
           }
         })
       },
       _loadFile (url) {
         PDFJS.getDocument(url).then((pdf) => {
           this.pdfDoc = pdf
           console.log(pdf)
           this.pages = this.pdfDoc.numPages
           this.$nextTick(() => {
             this._renderPage(1)
           })
         })
       }
    

    4.使用时传递url

    this._loadFile('/data/ystest/test')
    

    5.反向代理,解决跨域

    proxyTable: {
         '/data': {
           target: 'http://127.0.0.1:8081',
           pathRewrite: {'^/data': ''}
         },
       }
    
     

     
    链接:https://www.jianshu.com/p/b48af7917656 
  • 相关阅读:
    SSRS应用理解与实现
    idea2022.1乱码问题
    yum安装mysql8
    curl fsSL
    IntelliJ IDEA 快捷键大全
    MYSQLcheck管理
    人机验证reCAPTCHA v3使用完备说明
    图像的梯度
    复数的理解
    傅里叶变换的理解
  • 原文地址:https://www.cnblogs.com/javalinux/p/15667799.html
Copyright © 2020-2023  润新知