前言
使用docx-preview 实现在页面中预览docx文件功能
安装
npm i docx-preview --save
用法
1.引入
这里我是用的局部引入,在需要使用的组件文件内引入即可,代码如下:
import { renderAsync } from "docx-preview";
2.使用
这里使用接口获取文件流或者是手动上传都可以实现预览功能
两种方法,代码里面目前是手动上传,注释部分是通过接口请求实现
<template>
<div>
<div class="docx-preview-wrap">
<h1>kaimo test docx-preview</h1>
<h4>
<input type="file" id="file" accept=".docx" />
<button @click="handlePreview">预览</button>
</h4>
<div id="bodyContainer"></div>
</div>
</div>
</template>
<script>
// 引入axios用来发请求
import axios from "axios";
// 引入docx-preview插件
let docx = require("docx-preview");
import { renderAsync } from "docx-preview";
export default {
data() {
return {
docxOptions: {
className: "kaimo-docx-666", // string:默认和文档样式类的类名/前缀
inWrapper: true, // boolean:启用围绕文档内容的包装器渲染
ignoreWidth: true, // boolean:禁用页面的渲染宽度
ignoreHeight: false, // boolean:禁止渲染页面高度
ignoreFonts: true, // boolean:禁用字体渲染
breakPages: false, // boolean:在分页符上启用分页
ignoreLastRenderedPageBreak: true, // boolean:在 lastRenderedPageBreak 元素上禁用分页
experimental: false, // boolean:启用实验功能(制表符停止计算)
trimXmlDeclaration: true, // boolean:如果为true,解析前会从 xml 文档中移除 xml 声明
useBase64URL: false, // boolean:如果为true,图片、字体等会转为base 64 URL,否则使用URL.createObjectURL
useMathMLPolyfill: false, // boolean:包括用于 chrome、edge 等的 MathML polyfill。
showChanges: false, // boolean:启用文档更改的实验性渲染(插入/删除)
debug: false, // boolean:启用额外的日志记录
},
drawer: false,
form: {
name: "",
region: "",
date1: "",
date2: "",
delivery: false,
type: [],
resource: "",
desc: "",
},
};
},
mounted() {
console.log("使用插件的renderAsync方法来渲染", docx); //
},
methods: {
onSubmit() {
console.log("submit!");
},
handlePreview() {
let file = document.getElementById("file").files[0];
console.log(file);
// 将file转为buffer
let fr = new FileReader();
fr.readAsArrayBuffer(file);
fr.addEventListener(
"loadend",
(e) => {
console.log("loadend---->", e);
let buffer = e.target.result;
this.docxRender(buffer);
},
false
);
// this.docxRender();
},
// 渲染docx
docxRender(buffer) {
// axios({
// method: "get",
// responseType: "blob", // 因为是流文件,所以要指定blob类型
// url: "/management/cooperation/ChannelMerchantApi/download", // 自己的服务器,提供的一个word下载文件接口
// }).then(({ data }) => {
// console.log(data); // 后端返回的是流文件
// renderAsync(
// data,
// // buffer, // Blob | ArrayBuffer | Uint8Array, 可以是 JSZip.loadAsync 支持的任何类型
// bodyContainer, // HTMLElement 渲染文档内容的元素,
// null, // HTMLElement, 用于呈现文档样式、数字、字体的元素。如果为 null,则将使用 bodyContainer。
// this.docxOptions // 配置
// );
// });
let bodyContainer = document.getElementById("bodyContainer");
renderAsync(
buffer, // Blob | ArrayBuffer | Uint8Array, 可以是 JSZip.loadAsync 支持的任何类型
bodyContainer, // HTMLElement 渲染文档内容的元素,
null, // HTMLElement, 用于呈现文档样式、数字、字体的元素。如果为 null,则将使用 bodyContainer。
this.docxOptions // 配置
).then((res) => {
console.log("res---->", res);
});
},
},
};
</script>
<style lang="less" scoped>
.docWrap {
// 指定样式宽度
width: 900px;
// overflow-x: auto;
}
.docproview {
width: 980px;
height: 900px;
background-color: #f6f9f9;
}
</style>