做Docx在線WEB瀏覽器預覽,一定要做docx-preview和mammoth這兩個神庫?。?/h3>
|
![]() |
![]() 2025年4月21日 17:23 本文熱度 692 |
只需幾行代碼,你就能在瀏覽器中完美預覽 Word 文檔,甚至連表格樣式、頁眉頁腳都原汁原味地呈現(xiàn)出來。
接下來,給大家分享兩個 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 打開的一模一樣!連段落格式、表格樣式、甚至是分頁效果,都完美呈現(xiàn)。
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>
標簽。
要實現(xiàn)在線預覽 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);
}
}
效果很贊!文檔分頁顯示,目錄、頁眉頁腳、表格邊框樣式都完美呈現(xiàn)。
不過也有些小坑:
文檔特別大時,渲染速度會變慢
一些復雜的 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 的優(yōu)點在這個場景下完全發(fā)揮出來:
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) {
// 創(chuàng)建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 Server 或 Microsoft 365 的在線服務,通過嵌入 WebView
或 <iframe>
實現(xiàn) DOCX 的在線渲染。
示例代碼:?
<iframe src="https://view.officeapps.live.com/op/embed.aspx?src=文檔URL"></iframe>
折騰一圈,還是docx-preview
和mammoth
這倆兄弟最實用。
它們提供了輕量級的解決方案,僅需幾十 KB 就能搞定 Word 預覽問題,而且不需要依賴外部服務,完全可以在前端實現(xiàn)。