『VUE H5页面 - PDF预览』

  • 使用依赖:vue-pdf
  • 实现需求:将 PDF url 地址 转换为本地页面预览
<template>
  <div class="pdf-preview">
    <NavBar />

    <div class="container">
      <VuePdf v-for="i in numPages" :key="i" class="pdf" :src="src" :page="i">VuePdf>
    div>
  div>
template>

<script>
import { Toast } from 'vant'
export default {
  name: 'PdfPreview',
  components: {
    VuePdf: () => import(/* webpackChunkName: "vue-pdf-component" */ 'vue-pdf'),
  },
  props: {},
  data() {
    return {
      pdfUrl: '', //      pdf在线地址
      numPages: '', //    页数
      src: '',
    }
  },
  created() {
    this.pdfUrl = this.$route.query.pdfUrl
    this.loadingPDF(this.pdfUrl)
  },
  methods: {
    // 具体用法参考:https://github.com/FranckFreiburger/vue-pdf#readme
    async loadingPDF(url) {
      if (!url) return

      try {
        const { default: pdf } = await import(/* webpackChunkName: "vue-pdf-method" */ 'vue-pdf')
        this.src = pdf.createLoadingTask(url)

        this.src.promise
          .then(pdf => {
            this.numPages = pdf.numPages
          })
          .catch(error => Toast(error.message))
      } catch (error) {
        console.info(error)
      }
    },
  },
}
script>

<style lang="scss" scoped>
.pdf-preview {
  width: 100%;
  height: 100%;

  .container {
    width: 100%;
    height: calc(100% - #{$vue-container-top-height});
    background: #f5f5f5;
    position: relative;
    overflow-y: scroll;

    .pdf {
      width: 100%;
      &:not(:last-child) {
        margin-bottom: 10px;
      }
    }
  }
}
style>

你可能感兴趣的:(VUE2,vue.js,pdf)