今天让做一个登录页面的用户协议和隐私协议的预览
首先在vue项目的public文件夹的static文件夹项目放入
方法一
使用mammoth.js 会忽略复杂样式 我的版本是 "mammoth": "^1.7.2"
<template>
<div class="word-wrap-ss">
<div id="wordView" v-html="wordText" />
</div>
</template>
<script>
// docx文档预览(只能转换.docx文档,转换过程中复杂样式被忽,居中、首行缩进等)
import mammoth from 'mammoth'
export default {
name: 'Word1000',
data() {
return {
wordText: '',
wordURL: 'http://192.168.2.50:8080/static/userProtocol.docx' //文件地址
}
},
created() {
let str = window.location.href
let arr = str.split('#')
this.wordURL = arr[0] + 'static/userProtocol.docx'
this.getWordText()
},
methods: {
getWordText() {
const xhr = new XMLHttpRequest()
xhr.open('get', this.wordURL, true)
xhr.responseType = 'arraybuffer'
xhr.onload = () => {
if (xhr.status == 200) {
mammoth.convertToHtml({ arrayBuffer: new Uint8Array(xhr.response) }).then(resultObject => {
this.$nextTick(() => {
this.wordText = resultObject.value
})
})
}
}
xhr.send()
}
}
}
</script>
<style>
.word-wrap-ss {
padding: 20px;
font-size: medium;
}
</style>
方法二
使用docx-preview
这里特别需要注意版本,我使用的这两个版本才正常运行
"docx-preview": "^0.1.4", "jszip": "^3.10.0",
window.JSZip = require('jszip') 这一步是必要的,看了原码发现docx-preview里面require('JSZip')
<template>
<div class="word-wrap-ss">
<div id="file" />
</div>
</template>
<script>
const docx = require('docx-preview')
window.JSZip = require('jszip')
export default {
name: 'Word1000',
data() {
return {
wordURL: 'http://192.168.2.50:8080/static/userProtocol.docx' //文件地址
}
},
created() {
let str = window.location.href
let arr = str.split('#')
this.wordURL = arr[0] + 'static/userProtocol.docx'
this.getWordText()
},
methods: {
getWordText() {
const xhr = new XMLHttpRequest()
xhr.open('get', this.wordURL, true)
xhr.responseType = 'blob'
xhr.onload = () => {
if (xhr.status == 200) {
docx
.renderAsync(xhr.response, document.getElementById('file'), null, {
className: 'docx', // 默认和文档样式类的类名/前缀
inWrapper: true, // 启用围绕文档内容渲染包装器
ignoreWidth: false, // 禁止页面渲染宽度
ignoreHeight: false, // 禁止页面渲染高度
ignoreFonts: false, // 禁止字体渲染
breakPages: false, // 在分页符上启用分页
ignoreLastRenderedPageBreak: false, //禁用lastRenderedPageBreak元素的分页
experimental: false, //启用实验性功能(制表符停止计算)
trimXmlDeclaration: false, //如果为真,xml声明将在解析之前从xml文档中删除
debug: false // 启用额外的日志记录
})
.then(res => {
console.log('res---->', res)
})
.catch(err => {
console.log('err---->', err)
})
}
}
xhr.send()
}
}
}
</script>