事实上有很多种在前端展示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>