对于pdf文件,通过测试ios是能够失常关上,而在安卓机上,则须要下载福昕阅读器能力关上。如何可能不借助客户端之力,依附h5来实现pdf文件预览性能呢?咱们能够装置pdfjs-dist模块来实现。
本示例是基于vue框架:
- 装置pdfjs-dist包:
npm install pdfjs-dist -D
这里应用的版本是:
"pdfjs-dist": "^2.4.456"
2、html模板
<template> <div class="canvas-container"> <canvas v-for="page in pages" :id="'the- canvas'+page" :key="page"> </canvas> </div></template>
3、script代码段
import PDFJS from 'pdfjs-dist';import workerSrc from 'pdfjs-dist/build/pdf.worker.entry'PDFJS.workerSrc = workerSrc;
export default { name: 'Pdf', data() { return { pages: [] }; }, created() { this._loadFile(yourUrl); }, methods: { _renderPage (num) { this.pdfDoc.getPage(num).then((page) => { let canvas = document.getElementById('the-canvas' + num) var vp = page.getViewport({scale: 1}); 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({scale: window.innerWidth / vp.width}); canvas.width = viewport.width * ratio canvas.height = viewport.height * ratio canvas.style.width = viewport.width + '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) { this.$showLoading(); PDFJS.getDocument(url).promise.then((pdf) => { this.$closeLoading(); this.pdfDoc = pdf this.pages = this.pdfDoc.numPages this.$nextTick(() => { this._renderPage(1); }); }); } }};
4、css代码
<style lang="scss" scoped>.canvas-container{ margin: 0 auto; canvas{ height: 100vh; }}</style>