vue项目实现在线文档预览效果:Office、PDF、Word等格式一网打尽

在项目中遇到过一个实际需求,需要能够预览office、pdf、word等在线文件,要是让我们自己手写完全没一点思路,不过好在优秀的开源插件@vue-office/docx,@vue-office/excel,@vue-office/pdf直接就帮我们高效的实现了,让在线预览变得如此简单,话不多说我们开始学习如何在项目中使用这些插件帮我们完成需求点。

实现在线文档预览我们需要准备下面这些:

1、首先了解需求需要安装所需要的插件

npm安装

npm install @vue-office/docx @vue-office/excel @vue-office/pdf --save

yarn安装

yarn add @vue-office/docx @vue-office/excel @vue-office/pdf 

2、文档插件通过加载文档的URL或文件路径来获取文档内容,并在网页上进行渲染和展示。

<template>
  <div class="wrap">
    <NavBar></NavBar>
    <van-loading v-if="loading" size="24px">加载中...</van-loading>
    <vue-office-docx v-if="fileType === 'docx' || fileType === 'doc'" :src="filePath" style="height: 100vh"
      @rendered="rendered" @error="HandlError"></vue-office-docx>
    <vue-office-pdf v-if="fileType === 'pdf'" :src="filePath" style="height: 100vh" @rendered="rendered"
      @error="HandlError"></vue-office-pdf>
    <vue-office-excel v-if="fileType === 'xlsx' || fileType === 'xls'" :src="filePath" style="height: 100vh"
      @rendered="rendered" @error="HandlError"></vue-office-excel>

    <!-- 签名 -->
  </div>
</template>

<script>
import VueOfficeDocx from "@vue-office/docx";
import VueOfficeExcel from "@vue-office/excel";
import VueOfficePdf from "@vue-office/pdf";
//引入相关样式
import "@vue-office/docx/lib/index.css";
export default {
  data() {
    return {
      loading: true,
      info: {},
      filePath: "",  // 预览地址
      fileType: "", // 文件类型
      baseUrl: process.env.VUE_APP_BASE_URL + "/graphicDoc/preview?dir=",
    };
  },

  components: {
    NavBar: () => import("@/components/NavBar"),
    VueOfficeDocx,
    VueOfficeExcel,
    VueOfficePdf,
  },
  created() {
    this.info = JSON.parse(decodeURIComponent(this.$route.query.info));
    this.filePath = this.baseUrl + this.info.filePath;
    this.fileType = this.info.fileType;
    console.log(this.info);
  },
  methods: {
    /* pdf,word组件渲染完毕 */
    rendered() {
      this.loading = false;
    },
    /* pdf,word组件渲染出错 */
    HandlError(errorInfo) {
      this.$toast("该文件暂不支持在线预览");
      this.loading = false;
    },
  },
};
</script>

<style scoped lang="scss">
.wrap {
  width: 100vw;
  height: 100vh;
  padding: 40px 0 0 0;


  .content {
    white-space: pre;
    width: 100%;
    height: 100%;
    padding: 20px 10px;
    background: #fff;
    overflow-x: auto;
  }

  .van-loading {
    background-color: #fff;
    position: absolute;
    width: 100vw;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>

3、最关键的一步,千万不要忘记引入css样式了,不然文档可能无法正常预览哦

import "@vue-office/docx/lib/index.css";

这样就轻松解决了在线文档预览的需求了。

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值