【vue2+docx-preview】实现docx文档预览(自定义修改样式)

前言

使用vue预览docx的解决方案,过去还有一种Mammoth
它旨在转换 .docx 文档(例如由 Microsoft Word 创建的文档),并将其转换为 HTML。 不支持样式。实现方式可以参考:Vue Word预览之mammoth.js
因此选择换成支持渲染样式的docx-preview

正文

安装 npm 依赖

(23年6月最新版本为@2.1.4

npm i docx-preview --save 

导入

import {
    
     renderAsync } from "docx-preview";

使用

  • 封装了这个功能,监听外部传入的url进行动态渲染,如果只是想测试功能,写死url就行了。
  • 传入的url可以是本地的也可以是在线的。
  • 修改原有的样式,以符合UI的要求。做了简单的移动端自适应。

完整代码

<template>
    <div class="docx-container">
      <div ref="file"></div>
    </div>
</template>

<script>
import axios from "axios";
import {
    
     renderAsync } from "docx-preview";

export default {
    
    
  props: {
    
    
    url: {
    
    
      type: String,
      default: "",
    },
  },

  mounted() {
    
    
    // this.renderFile();
  },

  watch: {
    
    
    url(value) {
    
    
      this.renderFile();
    },
  },

  methods: {
    
    
    renderFile() {
    
    
      console.log(this.url);
      axios({
    
    
        method: "get",
        responseType: "blob",
        url: this.url,
      }).then((response) => {
    
    
        renderAsync(response.data, this.$refs.file);
      });
    },
  },
};
</script>

<style scoped>
.docx-container ::v-deep .docx-wrapper {
    
    
  background-color: #fff;
  padding: 20px 20px;
}
.docx-container ::v-deep .docx-wrapper > section.docx {
    
    
  width: 55vw !important;
  padding: 0rem !important;
  min-height: auto !important;
  box-shadow: none;
  margin-bottom: 0;
  overflow-y: scroll;
  height: 100vh;
}

.docx-container ::v-deep .docx-wrapper > section.docx::-webkit-scrollbar {
    
    
  display: none;
}
</style>

实现效果

在这里插入图片描述

参考

猜你喜欢

转载自blog.csdn.net/sinat_41838682/article/details/130999285
今日推荐