background
The preview of pdf file format is required on the project.
Analysis
pdf file browser can be opened directly. So you only need to return the file stream of pdf file to preview the file directly. Open in this way, the whole page is full of pdf file content. The requirement is to add a specific title format to the page when previewing, so it is not feasible to directly open the file stream in the browser. By collecting relevant information, find the pdfjs plug-in to support the preview of files.
Realization
1.vue Introduce in pdfjs rely on
npm install pdfjs-dist --save
2. Use canvas to preview the canvas of pdf file
<canvas v-for="page in pages" :id="'the-canvas'+page" :key="page"></canvas>
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) }) }) }
4. Pass the url when using
this._loadFile('/data/ystest/test')
5. Reverse proxy to solve cross domain problems
proxyTable: { '/data': { target: 'http://127.0.0.1:8081', pathRewrite: {'^/data': ''} }, }
Effect demonstration
epilogue
At present, most of the common needs are to find relevant information. It is hereby recorded.