对于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>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。