实现效果:
代码实现:
<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>