项目需求要实现在线预览pdf文件功能,PDF区别于office的三类文档在于它不会默认打开链接自动下载而是浏览。PDF文件理论上可以在浏览器直接打开预览但是需要打开新页面。如果对预览页面UI有要求的情况下可以直接通过canvasc画布来实现。
安装依赖:npm install pdfjs-dist 我安装的是@2.0.943版本
下面是实现的完整代码:
HTML:
<template>
<div class="pdf-wrapper">
<canvas v-for="page in pages" :id="'the-canvas' + page" :key="page"></canvas>
</div>
</template>
JS:
import PDFJS from 'pdfjs-dist'
PDFJS.GlobalWorkerOptions.workerSrc = '../../node_modules/pdfjs-dist/build/pdf.worker.min.js'
export default {
data() {
return {
pdfDoc: null,
pages: 0 // 页码
}
},
methods: {
loadFile(url) {
let that = this
PDFJS.getDocument(url).then(function (pdf) {
that.pdfDoc = pdf
that.pages = that.pdfDoc.numPages
that.$nextTick(() => {
that.renderPage(1)
})
})
},
renderPage(num) {
let _this = this
_this.pdfDoc.getPage(num).then(function (page) {
let canvas = document.getElementById('the-canvas' + num)
let ctx = canvas.getContext('2d')
let dpr = window.devicePixelRatio || 1.0
let bsr =
ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio ||
1.0
let ratio = dpr / bsr
let viewport = page.getViewport(window.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)
var renderContext = {
canvasContext: ctx,
viewport: viewport
}
page.render(renderContext)
if (_this.pages > num) {
_this.renderPage(num + 1)
}
})
}
}
}