当前位置: 代码网 > it编程>前端脚本>Vue.js > vue-pdf实现pdf在线预览并实现自定义预览框高度

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

2024年05月18日 Vue.js 我要评论
首先安装vue-pdf库npm install --save vue-pdf在你的vue页面文件中引入这个组件然后运行程序,这时候你会发现,pdf预览图并不能铺满你的容器框。查看样式:发现vue-pd

首先

安装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>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com