1、肯定是先安装了:
npm i pdfobject --save2、引入
import pdf from 'pdfobject'3、指定元素与样式
<template> <div id="pdf-content"> </div> </template> <style lang="scss" scoped> #pdf-content{ width: 100%; height: 100%; position: fixed; top: 0; left: 20%; background: #999; } </style>4、一定要在mounted中调用,因为它必须等待dom元素渲染出来才能找到节点。
mounted(){ pdf.embed("../../static/pdf.pdf", "#pdf-content"); }小技巧:建议将上面的代码封装到一个组建当中,然后用dialog等方法打开,这样的话,按esc可以直接关闭,否则全屏的话会导致关闭不了。esc其实关闭的是dialog。下面是我爱模板网在工作中封装的一个组件:ViewPDF,这个组件还带提示:ESC可关闭PDF
<template> <div> <div class="pdf-tips" v-if="showTips">按“ESC”键可关闭PDF<el-button type="text"><i class="el-icon-close" @click="pdfTop=0; showTips=false"></i></el-button></div> <div id="pdf-content" :style="{top:pdfTop+'px'}"></div> </div> </template> <script> import pdf from 'pdfobject' export default { name: "ViewPDF", props: { pdfUrl: { type: String, default: "" } }, data() { return { pdfTop:40, showTips:true } }, created() { }, methods: { }, beforeMount() { var that = this; that.$nextTick(function () { pdf.embed(that.pdfUrl, "#pdf-content"); }) }, } </script> <style lang="scss" scoped> .pdf-tips{ width: 100%; height: 40px; display: flex; justify-content: center; align-items: center; position: fixed; text-align: center; top:0; left:0; z-index: 999999999999; background: #fff; } #pdf-content{ width: 100%; height: 100%; position: fixed; left:0; z-index: 999999999999; background: #999; } </style>使用ViewPDF组件也很简单:
1、打开PDF按钮
<el-button @click="showPdf=true">打开pdf</el-button>2、将ViewPDF放到dialog中:
<el-dialog :visible.sync="showPdf"> <ViewPDF v-if="showPdf" :pdfUrl="pdfUrl"></ViewPDF> </el-dialog>3、导入ViewPDF组件
import ViewPDF from "@/components/ViewPDF";4、在components中加入组件
components: { ViewPDF },5、设置data
data(){ return { showPdf:false, pdfUrl:'http://abc.com/1.pdf' //pdf路径 } }