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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM