background

The project requires the implementation of PDF file format preview.

Analysis of the

The PDF file browser can be opened directly. So just need to return the PDF file stream, you can directly preview the file, through this way open, the entire page is full of PDF file content. The requirement is to preview the page with a specific title format, so streaming the file directly to the browser doesn’t work. By collecting relevant information, find the PDFJS plug-in to support file preview.

implementation

1. Introduction of PDFJS dependency in Vue

npm install pdfjs-dist --save
Copy the code

2. Use Canvas as the canvas to preview PDF files

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

3. Call PDFJS API for document rendering

_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)
       })
     })
   }
Copy the code

4. Pass the URL when using

this._loadFile('/data/ystest/test')
Copy the code

5. Reverse proxy for cross-domain resolution

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

Results demonstrate

PNG original file


PNG on PC


PNG on PC


Mobile phone iphone. PNG


Mobile phone ipone2. PNG

conclusion

Most of the requirements that are common today are for finding relevant information. For the record.





Author: handsome guy writes code


Link: https://www.jianshu.com/p/b48af7917656


Source: Jane Book


Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.