只需幾行代碼,你就能在瀏覽器中完美預覽 Word 文檔,甚至連表格樣式、頁眉頁腳都原汁原味地呈現出來。
接下來,給大家分享兩個 Docx 預覽的庫:
docx-preview VS mammoth
docx-preview
和mammoth
是目前最流行的兩個 Word 文檔預覽庫,它們各有特色且適用于不同場景。
docx-preview:還原度爆表的選擇
安裝簡單:
npm install docx-preview
基礎用法:
import { renderAsync } from 'docx-preview';
renderAsync(docData, document.getElementById('container')).then(() => console.log('文檔渲染完成!'));
試了試后,這個庫渲染出來的效果簡直和 Office 打開的一模一樣!連段落格式、表格樣式、甚至是分頁效果,都完美呈現。
mammoth:簡潔至上的轉換器
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 文檔,且跟 "Word" 長得一模一樣。
首選docx-preview
:
import { renderAsync } from'docx-preview';
async functionpreviewDocx(fileUrl) {
try {
const response = awaitfetch(fileUrl);
const docxBlob = await response.blob();
const container = document.getElementById('docx-container');
awaitrenderAsync(docxBlob, container, null, {
className: 'docx-viewer',
inWrapper: true,
breakPages: true,
renderHeaders: true,
renderFooters: true,
});
console.log('文檔渲染成功!');
} catch (error) {
console.error('渲染文檔時出錯:', error);
}
}
效果很贊!文檔分頁顯示,目錄、頁眉頁腳、表格邊框樣式都完美呈現。
不過也有些小坑:
文檔特別大時,渲染速度會變慢
一些復雜的 Word 功能可能顯示不完美
場景二:做內容編輯系統
需要讓用戶上傳 Word 文檔,然后提取內容進行編輯。
選擇mammoth
:
import mammoth from'mammoth';
async functionextractContent(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 的優點在這個場景下完全發揮出來:
- 語義化 HTML:生成干凈的 HTML 結構
- 樣式映射:可以自定義 Word 樣式到 HTML 元素的映射規則
- 輕量轉換:處理速度非常快
進階技巧
docx-preview 的進階配置
renderAsync(docxBlob, container, styleContainer, {
className: 'custom-docx',
inWrapper: true,
ignoreWidth: false,
ignoreHeight: false,
breakPages: true,
renderHeaders: true,
renderFooters: true,
renderFootnotes: true,
renderEndnotes: true,
renderComments: true,
useBase64URL: false,
});
超實用技巧:如果只想把文檔渲染成一整頁(不分頁),只需設置breakPages: false
!
mammoth 的自定義圖片處理
默認情況下,mammoth 會把圖片轉成 base64 嵌入 HTML。
在大型文檔中,這會導致 HTML 特別大。
更好的方案:
const options = {
convertImage: mammoth.images.imgElement(function (image) {
return image.readAsArrayBuffer().then(function (imageBuffer) {
// 創建blob URL而不是base64
const blob = newBlob([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 預覽問題,而且不需要依賴外部服務,完全可以在前端實現。