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

2,621 阅读1分钟
背景

项目上要求实现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': ''}
     },
   }
效果演示
原始文件.png

pc端效果1.png

pc端效果2.png

手机ipone.png

手机ipone2.png
结语

目前常见的大部分需求都是可以找到相关资料。特此记录。



作者:帅哥哥写代码
链接:https://www.jianshu.com/p/b48af7917656
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。