事實上有很多種在前端展示PDF格式文檔的方法,小編也用過好多種,例如有<iframe>、<embed>和<object>這些標簽,但是在Vue項目里,這些方法都不能很好的展示PDF文檔,實際上Vue給大家准備了展示PDF的插件,所以小編今天給大家講解一下這個插件的用法。
首先下載插件
命令:npm install pdfjs-dist
下載完畢以后新建一個組件用來存放PDF文檔
引入所需要的插件:

接下來就是Vue給大家已經准備好了展示PDF文檔所需要的代碼,不需要大家在手動書寫了:

這里需要告訴大家,url最好還是傳到七牛雲上比較好(因為跨域這個東西很煩人)。
下面給大家帶來完整的代碼:(這里要注意,存放PDF的容器最好用canvas)
<template>
<div>
<p>合同預覽</p>
<canvas v-for="page in pages" :id="'the-canvas'+page" :key="page"></canvas>
</div>
</template>
<script>
import PDFJS from "pdfjs-dist";
import pdfjsLib from "pdfjs-dist";
// const Base64 = require('js-base64').Base64
export default {
name: "ContractPreview",
data() {
return {
title: "查看協議",
pdfDoc: null,
pages: 0
};
},
methods: {
// 初始化pdfjs
initThePDFJSLIB: function() {
pdfjsLib.GlobalWorkerOptions.workerSrc = "pdfjs-dist/build/pdf.worker.js";
},
_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;
this.pages = this.pdfDoc.numPages;
this.$nextTick(() => {
this._renderPage(1);
});
});
}
},
mounted() {
this.initThePDFJSLIB();
document.title = this.title;
let url = 'PDF鏈接地址’;
console.log(url);
this._loadFile(url);
}
};
</script>
<style scoped>
canvas {
display: block;
border-bottom: 1px solid black;
}
</style>
