提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
目的
最近有一个需求,使用JS在网页上预览docx文档,网上搜索了一下,发现docx-preview库可以完成。期间参考了这篇博文“https://blog.csdn.net/qq_44977299/article/details/128562163”,但是发现一些问题,只能在本页面进行预览,打开新页面后显示空白,研究了一下,给出另一种方法。
一、使用步骤
1.引入库
import axios from 'axios'; // 从后端获取文档数据流
import { renderAsync } from "docx-preview";
window.JSZip = require('jszip'); // 这是docx-preview的依赖
2.设置文档渲染选项
docxOptions: {
className: "kaimo-docx-666", // string:默认和文档样式类的类名/前缀
inWrapper: true, // boolean:启用围绕文档内容的包装器渲染
ignoreWidth: false, // boolean:禁用页面的渲染宽度
ignoreHeight: false, // boolean:禁止渲染页面高度
ignoreFonts: false, // boolean:禁用字体渲染
breakPages: true, // 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:启用额外的日志记录
},
3.创建新窗口和Iframe渲染文档
async showDocx() {
try{
// 向后端发送请求以获取文件流
let responseForFile = await axios.post('path of router', {}, {
responseType: 'arraybuffer'
});
let buffer = responseForFile.data;
console.log(buffer)
// 创建新窗口和 iframe
let docwindow = window.open("", '_blank');
let iframe = docwindow.document.createElement('iframe');
iframe.style.width = '100%';
iframe.style.height = '100%';
docwindow.document.body.appendChild(iframe);
// 等待 iframe 加载完成
iframe.onload = () => {
// 渲染 DOCX 数据到 iframe 中
let iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
let docxContainer = iframeDoc.body; // 直接在 body 中渲染
// 需要确保 docx-preview 库已加载在父窗口
renderAsync(buffer, docxContainer, null, this.docxOptions).catch(error => {
console.error("Error rendering the docx:", error);
});
};
// 初始化 iframe 的文档内容
let iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
iframeDoc.open();
iframeDoc.write('<!DOCTYPE html><html><head><title>文档预览</title></head><body></body></html>');
iframeDoc.close();
} catch(error){
console.log('获取和渲染文档时出错:', error)
}
}
}