項(xiàng)目需求要實(shí)現(xiàn)在線預(yù)覽pdf文件功能,PDF區(qū)別于office的三類文檔在于它不會(huì)默認(rèn)打開鏈接自動(dòng)下載而是瀏覽。PDF文件理論上可以在瀏覽器直接打開預(yù)覽但是需要打開新頁(yè)面。如果對(duì)預(yù)覽頁(yè)面UI有要求的情況下可以直接通過(guò)canvasc畫布來(lái)實(shí)現(xiàn)。
安裝依賴:npm install pdfjs-dist 我安裝的是@2.0.943版本
下面是實(shí)現(xiàn)的完整代碼:
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 // 頁(yè)碼
}
},
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)
}
})
}
}
}