(共566篇)
全部分类

Vue 中 pdf 文件进行预览下载
[ Vue(2+3) ] 

下载插件 vue-pdf

1
2
3
npm install --save vue-pdf
或者
cnpm install --save vue-pdf

所需页面引入组件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<!-- 模板代码 -->
<div class="pdfPreview">
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :fullscreen="true"
      :before-close="handleClose"
      title="合同预览">
      <div class="agreement_picture">
        <div class="tools">
          <el-button @click="prePage" class="mr10"> 上一页</el-button>
          <el-button @click="nextPage" class="mr10"> 下一页</el-button>
          <span class="page">{{pageNum}}/{{pageTotalNum}} </span>
          <el-button @click="handleClose" class="mr10 fl-r btn-cancel"> 取消</el-button>
          <el-button @click="downPDF" class="mr10 dowmBtn"> 下载</el-button>
        </div>
        <pdf ref="pdf"
          :src="src"
          :page="pageNum"
          @page-loaded="pageLoaded($event)"
          @num-pages="pageTotalNum=$event"
          @error="pdfError($event)"
          @link-clicked="page = $event">
        </pdf>
      </div>
    </el-dialog>


import pdf from 'vue-pdf';

export default {
  name: 'PdfPreview',
  components: {
    pdf
  },

  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      url: "http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf", // pdf 地址(网上的pdf例子地址,此地址就是后端返回的真正需要预览的pdf地址)
      src: '', // 预览地址
      pageNum: 1, // 当前页码
      pageTotalNum: 1, // 总页数
    };
  },

  mounted () {
    // 有时PDF文件地址会出现跨域的情况,这里最好处理一下
    var url = this.url
    this.src = pdf.createLoadingTask(url);
  },

  methods: {
    // 上一页函数,
    prePage() {
      var page = this.pageNum
      page = page > 1 ? page - 1 : this.pageTotalNum
      this.pageNum = page
    },
    // 下一页函数
    nextPage() {
      var page = this.pageNum
      page = page < this.pageTotalNum ? page + 1 : 1
      this.pageNum = page
    },
    // 页面加载回调函数,其中e为当前页数
    pageLoaded(e) {
      this.curPageNum = e
    },
    // 抛出错误的回调函数。
    pdfError(error) {
      console.error(error)
    },
    downPDF() { // 下载 pdf
    var url = this.url
    var tempLink = document.createElement("a");
    tempLink.style.display = "none";
    tempLink.href = url;
    tempLink.setAttribute("download", 'XXX.pdf');
    if (typeof tempLink.download === "undefined") {
    tempLink.setAttribute("target", "_blank");
    }
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
        this.handleClose();
    },
    handleClose() {
      this.$emit('update:dialogVisible', false);
    }
  }
};