使用vue-pdf 实现pdf在线预览并且自定义预览框高度

首先,安装vue-pdf

npm install --save vue-pdf

在你的vue页面文件中引入这个组件

然后运行程序,这时候你会发现,pdf预览图并不能铺满你的容器框。
查看样式:

在这里插入图片描述
发现vue-pdf组件的canvas标签里面把高度写死成 height:212.269px了。
我们尝试给这个组件再写一个pdf-preview的class 将设置高度为100%发现不生效。

  .pdf-preview {
    
    
    height: 100%;
  }

解决方案:提高指定样式的应用优先权(优先级)

  .pdf-preview {
    
    
    height: 100%;
  }
  // 穿透vue-pdf插件中的canvas样式
  .pdf-preview canvas {
    
    
    //提高指定样式规则的应用优先权(优先级)
    height: 100% !important;
  }

附上完整代码:

<!--
 * @Author: WenZhiming
 * @Date: 2022-09-26 17:17:55
 * @LastEditors: WenZhiming
 * @LastEditTime: 2022-09-26 18:03:13
 * @Description: file content
-->
<template>
  <div class="container_upload relative">
    <pdf
      v-if="pdfUrl && pdfUrl.endsWith('.pdf')"
      class="pdf-preview"
      :src="pdfUrl"
    ></pdf>
    <div class="buttons">
      <el-button v-if="pdfUrl" type="primary" plain @click="previewPDF">
        {
    
    {
    
     $t('查看') }}
      </el-button>
      <el-button type="primary" class="mt-12" @click="uploadPdf">
        {
    
    {
    
     $t('上傳') }}
      </el-button>
    </div>
    <input
      ref="pdfInput"
      type="file"
      style="display: none"
      accept="application/pdf"
      @change="fileChange"
    />
  </div>
</template>
<script>
  import pdf from 'vue-pdf'
  export default {
    
    
    components: {
    
    
      pdf,
    },
    data() {
    
    
      return {
    
    
        pdfUrl: '',
      }
    },
    methods: {
    
    
      uploadPdf() {
    
    
        this.$refs.pdfInput.click()
      },
      fileChange(ev) {
    
    
        //文件上传到阿里云oss获得url
        // this._upload(ev, (url) => {
    
    
        //   this.pdfUrl = url
        // })
        this.pdfUrl = 'https://www.pinduoduo.com/pdd_privacy_policy.pdf'
      },
      previewPDF() {
    
    
        window.open(this.pdfUrl, '_blank')
      },
    },
  }
</script>

<style lang="scss">
  .container_upload {
    
    
    width: 150px;
    height: 256px;
    border: 1px solid #ddd;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .buttons {
    
    
      z-index: 1;
      position: absolute;
      display: flex;
      flex-direction: column;
      .el-button {
    
    
        margin-left: 0;
        width: 80px;
      }
    }
    img {
    
    
      width: 100%;
      height: 100%;
    }
  }

  .pdf-preview {
    
    
    height: 100%;
  }
  // 穿透vue-pdf插件中的canvas样式
  .pdf-preview canvas {
    
    
    //提高指定样式规则的应用优先权(优先级)
    height: 100% !important;
  }
</style>

猜你喜欢

转载自blog.csdn.net/Jackson_Wen/article/details/127058165
今日推荐