102人参与 • 2025-04-24 • Javascript
只需几行代码,你就能在浏览器中完美预览 word 文档,甚至连表格样式、页眉页脚都原汁原味地呈现出来。
接下来,给大家分享两个 docx 预览的库:
docx-preview和mammoth是目前最流行的两个 word 文档预览库,它们各有特色且适用于不同场景。
安装简单:
npm install docx-preview
基础用法:
import { renderasync } from 'docx-preview';
// 获取到docx文件的blob或arraybuffer后
renderasync(docdata, document.getelementbyid('container')).then(() => console.log('文档渲染完成!'));
试了试后,这个库渲染出来的效果简直和 office 打开的一模一样!连段落格式、表格样式、甚至是分页效果,都完美呈现。
mammoth 的思路完全不同,它把 word 文档转成干净的 html:
npm install mammoth
使用也很简单:
import mammoth from 'mammoth';
mammoth.converttohtml({ arraybuffer: docxbuffer }).then(result => {
    document.getelementbyid('container').innerhtml = result.value;
    console.log('转换成功,但有些警告:', result.messages);
});
转换出来的 html 非常干净,只保留了文档的语义结构。
比如,word 中的"标题 1"样式会变成 html 中的<h1>标签。
要实现在线预览 word 文档,且跟 "word" 长得一模一样。
首选docx-preview:
import { renderasync } from 'docx-preview';
async function previewdocx(fileurl) {
    try {
        // 获取文件
        const response = await fetch(fileurl);
        const docxblob = await response.blob();
        // 渲染到页面上
        const container = document.getelementbyid('docx-container');
        await renderasync(docxblob, container, null, {
            classname: 'docx-viewer',
            inwrapper: true,
            breakpages: true,
            renderheaders: true,
            renderfooters: true,
        });
        console.log('文档渲染成功!');
    } catch (error) {
        console.error('渲染文档时出错:', error);
    }
}
效果很赞!文档分页显示,目录、页眉页脚、表格边框样式都完美呈现。
不过也有些小坑:
需要让用户上传 word 文档,然后提取内容进行编辑。
选择mammoth:
import mammoth from 'mammoth';
async function extractcontent(file) {
    try {
        // 读取文件
        const arraybuffer = await file.arraybuffer();
        // 自定义样式映射
        const options = {
            stylemap: ["p[style-name='注意事项'] => div.alert-warning", "p[style-name='重要提示'] => div.alert-danger"],
        };
        const result = await mammoth.converttohtml({ arraybuffer }, options);
        document.getelementbyid('content').innerhtml = result.value;
        if (result.messages.length > 0) {
            console.warn('转换有些小问题:', result.messages);
        }
    } catch (error) {
        console.error('转换文档失败:', error);
    }
}
mammoth 的优点在这个场景下完全发挥出来:
renderasync(docxblob, container, stylecontainer, {
    classname: 'custom-docx', // 自定义css类名前缀
    inwrapper: true, // 是否使用包装容器
    ignorewidth: false, // 是否忽略页面宽度
    ignoreheight: false, // 是否忽略页面高度
    breakpages: true, // 是否分页显示
    renderheaders: true, // 是否显示页眉
    renderfooters: true, // 是否显示页脚
    renderfootnotes: true, // 是否显示脚注
    renderendnotes: true, // 是否显示尾注
    rendercomments: true, // 是否显示评论
    usebase64url: false, // 使用base64还是objecturl处理资源
});
超实用技巧:如果只想把文档渲染成一整页(不分页),只需设置breakpages: false!
默认情况下,mammoth 会把图片转成 base64 嵌入 html。
在大型文档中,这会导致 html 特别大。
更好的方案:
const options = {
    convertimage: mammoth.images.imgelement(function (image) {
        return image.readasarraybuffer().then(function (imagebuffer) {
            // 创建blob url而不是base64
            const blob = new blob([imagebuffer], { type: image.contenttype });
            const url = url.createobjecturl(blob);
            return {
                src: url,
                alt: '文档图片',
            };
        });
    }),
};
mammoth.converttohtml({ arraybuffer: docxbuffer }, options).then(/* ... */);
这样一来,图片以 blob url 形式加载,页面性能显著提升!
说实话,在选择这两个库之前,也有其他解决方案:
微软 office online 在线预览
利用微软官方提供的 office online server 或 microsoft 365 的在线服务,通过嵌入 webview 或 <iframe> 实现 docx 的在线渲染。
示例代码:
<iframe src="https://view.officeapps.live.com/op/embed.aspx?src=文档url"></iframe>
优点
折腾一圈,还是docx-preview和mammoth这俩兄弟最实用。
它们提供了轻量级的解决方案,仅需几十 kb 就能搞定 word 预览问题,而且不需要依赖外部服务,完全可以在前端实现。
docx-preview适合需要高还原度的场景,如文档预览系统;
而mammoth适合内容提取、文档到 html 的转换场景,如内容管理系统。
而 微软 office online 适合高还原公开文档。
根据具体需求选择合适的工具吧!
到此这篇关于javascript使用docx-preview和mammoth预览docx的文章就介绍到这了,更多相关javascript预览docx内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论