记录前端预览word文档的需求实现

方案一:XDOC文档预览

可以使用XDOC文档预览云服务来进行word文件的在线预览,直接去网站体验就知道怎么用了。
https://view.xdocin.com/

使用方法

1
https://view.xdocin.com/view?src=你的文档地址

例如:https://view.xdocin.com/view?src=https%3A%2F%2Fview.xdocin.com%2Fdemo%2Fview.docx

优点:

  1. 实现简单,只需要将文件地址拼在url参数中即可,且在页面会生成对应的目录结构。
  2. 文档地址也可以是IP地址。

缺点:

  1. 缺少了首行缩进、页面间距等效果
  2. 文档地址必须是对外可访问的,内网则无法使用该方案

方案二:使用微软官方提供的在线预览工具(限制较多,不推荐)

使用方法:

1
https://view.officeapps.live.com/op/view.aspx?src=你的文件的地址

优点:无

缺点:

  1. 文件的地址只能是域名,且不能包含端口号
  2. 与XDOC文档预览一样文档地址必须是对外可访问的,内网无法使用该方案

方案三:使用docx-preview插件预览docx后缀文件

使用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<template>
<div class="home">
<a-button @click="goPreview">点击预览word文件</a-button>
<div class="docWrap">
<!-- 预览文件的地方(用于渲染) -->
<div ref="file"></div>
</div>
</div>
</template>
<script>
import axios from 'axios';
// 引入docx-preview插件
let docx = require('docx-preview');
export default {
data() {
return {
fileLink: 'http://ashuai.work:10000/getDoc'
}
},
mounted() {
console.log('使用插件的renderAsync方法来渲染', docx) //
},
methods: {
// 预览
goPreview() {
axios({
method: 'get',
responseType: 'blob', // 因为是流文件,所以要指定blob类型
url: this.fileLink // 一个word下载文件的接口
}).then(({ data }) => {
console.log(data) // 后端返回的是流文件
/**
* 第一个参数: data为文件流,Blob | ArrayBuffer | Uint8Array 格式
* 第二个参数: 渲染到页面的dom元素
* 第三个参数: 渲染word文档的样式的元素,如果为null,则设置到第二个参数的DOM上
* 第四个参数: 配置对象
*/
docx.renderAsync(data, this.$refs.file, 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 lang="less" scoped>
.home {
height: 100%;
overflow: auto;
}
.docWrap {
// 指定样式宽度
width: 900px;
overflow: auto;
}
</style>
<style>
.text-docx-wrapper {
background: #fff !important;
}
</style>

可以在以下网址上传word文档体验预览:
https://volodymyrbaydalka.github.io/docxjs/

优点:

  1. 样式与word打开基本一直,不会像XDOC文档预览一样没有了首行缩进
  2. 接口返回文件流即可预览,内网也可以实现

缺点:

  1. 只能预览后缀为.docx的word文档,无法预览后缀为.doc的文档(如果实在要预览doc文件,可以考虑让后端复制源文件转成docx类型后返回前端文件流即可)
  2. 无法像XDOC文档预览一样生成对应的目录