效果展示: https://volodymyrbaydalka.github.io/docxjs

4.创建dom去展示对应的docx文件
5.创建一个基于Web的文档查看器,用于查看和预览Microsoft Word文档。
1.获取当前文档(currentDocument):通过document.querySelector(‘#document-container’)获取一个用于显示文档内容的HTML元素。
2.设置docx选项:使用Object.assign()方法将docx.defaultOptions与一个包含debug和experimental属性值的对象进行合并。
3.获取加载按钮(loadButton):通过document.querySelector(‘#loadButton’)获取一个用于加载文档的按钮。
4.定义renderDocx函数:一个异步函数,用于渲染Word文档。它接受一个文件参数(file),将其转换为Blob对象,然后使用docx.renderAsync()方法将其渲染到指定的容器中。同时,它还调用renderThumbnails()函数来生成文档的缩略图。
5.处理加载文档按钮的点击事件:当用户点击加载按钮时,调用renderDocx()函数并传入当前文档
6.读取本地存储的文件base64并展示
在实验中,发现文章太长可能会导致存储超长,可以使用一下方法解决:
核心点:直接使用接口返回,在html中直接读取数据,页面添加loading
fetch(
`接口api`,
{
method: 'GET'
}
)
.then((resp) => resp.json())
.then((response) => {
const base64String = response?.data
// 将Base64字符串转换为Blob对象
const byteCharacters = atob(base64String)
7.触发预览按钮的事件
//预览报告
function previewReportRequest() {
setsubmitLoading(true)
asyncActionCreators.previewReport({ id: ID }).then((response) => {
setsubmitLoading(false)
if (response?.data?.code === 0) {
localStorage.setItem('base64String', response?.data?.data)
//存好之后,跳转到预览页面
const htmlFilePath = `${window.location.origin}/docpreview.html`
openHtmlFileInNewTab(htmlFilePath)
} else {
message.warning(response.data.msg || '获取报告失败')
}
})
}
const openHtmlFileInNewTab = (url) => {
const anchor = document.createElement('a')
anchor.href = url
anchor.target = '_blank'
anchor.rel = 'noopener noreferrer'
anchor.click()
}
1.设一个input选取文件
2.添加文件选择方法
const handleLocalFilePreview = (event) => {
const file = event.target.files[0]
const reader = new FileReader()
// 将 Blob 数据编码为 Base64 字符串
reader.onload = (event) => {
const base64String = event.target.result
localStorage.setItem('base64String', base64String)
}
reader.readAsDataURL(file)
}
3.预览按钮的事件 openHtmlFileInNewTab同在线预览
const docxPreview = () => {
const htmlFilePath = `${window.location.origin}/docpreview.html`
openHtmlFileInNewTab(htmlFilePath)
}
4.html文件需要改变方法