前端实现word预览--基于docx-preview插件

 实现效果:

代码实现:

<template>
  <div class="home">
    <button @click="goPreview">点击预览word文件</button>
    <div class="docWrap">
      <!-- 预览文件的地方(用于渲染) -->
      <div ref="file"></div>
      <!-- <a href="" download="1.html">下载</a> -->
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import axios from "axios";
import { renderAsync } from "docx-preview";
// 引入docx-preview插件
// let docx = import.meta.glob("docx-preview");
let file = ref(null);

let goPreview = () => {
  axios({
    method: "GET",
    responseType: "blob", // 因为是流文件,所以要指定blob类型
    url: "../../../public/新建 DOCX 文档.docx", // 一个word下载文件的接口
  }).then((res) => {
    console.log(res); // 后端返回的是流文件
    const blob = new Blob([res.data], {
      type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    });
    console.log(blob);
    /**
     *
     * 第一个参数: data为文件流,Blob | ArrayBuffer | Uint8Array 格式
     * 第二个参数: 渲染到页面的dom元素
     * 第三个参数: 渲染word文档的样式的元素,如果为null,则设置到第二个参数的DOM上
     * 第四个参数: 配置对象
     */
    renderAsync(res.data, file.value, null, {
      className: "text-docx", //class name/prefix for default and document style classes
      inWrapper: true, //enables rendering of wrapper around document content
      ignoreWidth: false, //disables rendering width of page
      ignoreHeight: false, //disables rendering height of page
      ignoreFonts: false, //disables fonts rendering
      breakPages: true, //enables page breaking on page breaks
      ignoreLastRenderedPageBreak: true, //disables page breaking on lastRenderedPageBreak elements
      experimental: true, //enables experimental features (tab stops calculation)
      trimXmlDeclaration: true, //if true, xml declaration will be removed from xml documents before parsing
      useBase64URL: false, //if true, images, fonts, etc. will be converted to base 64 URL, otherwise URL.createObjectURL is used
      useMathMLPolyfill: true, //includes MathML polyfills for chrome, edge, etc.
      debug: false, //enables additional logging
    }); // 渲染到页面
  });
};
</script>
<style scoped>
.home {
  height: 100%;
  overflow: auto;
}
.docWrap {
  width: 900px;
  overflow: auto;
}
.text-docx-wrapper {
  background: #fff !important;
}
</style>

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值