docxjs是一個word docx文檔在線渲染庫,使用docx可以使你的docx文檔用瀏覽器打開在線閱讀,這在某些文檔在線閱讀的開發場景非常實用!
我們都知道pdf有js庫可以使pdf文檔用瀏覽器在線閱讀,Excel文檔也有在線生成的js庫,word docx文檔在線閱讀,以前用過微軟提功能的在線閱讀web工具。這里推薦一個能自主部署的docx文檔在線渲染js庫:docxjs。

在線渲染效果
docxjs使用
這個js庫使用方法非常簡單,直接使用cdn方式引用,注意為了兼容性要引用polyfill哦:
<!--optional polyfill for promise-->
<script src="https://unpkg.com/promise-polyfill/dist/polyfill.min.js"></script>
<!--lib uses jszip-->
<script src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
<script src="docx-preview.min.js"></script>
<script>
var docData = <document Blob>;
docx.renderAsync(docData, document.getElementById("container"))
.then(x => console.log("docx: finished"));
</script>
<body>
...
<div id="container"></div>
...
</body>
應用程序接口
renderAsync(
document: Blob | ArrayBuffer | Uint8Array, // could be any type that supported by JSZip.loadAsync
bodyContainer: HTMLElement, //element to render document content,
styleContainer: HTMLElement, //element to render document styles, numbeings, fonts. If null, bodyContainer will be used.
options: {
className: string = "docx", //class name/prefix for default and document style classes
inWrapper: boolean = true, //enables rendering of wrapper around document content
ignoreWidth: boolean = false, //disables rendering width of page
ignoreHeight: boolean = false, //disables rendering height of page
ignoreFonts: boolean = false, //disables fonts rendering
breakPages: boolean = true, //enables page breaking on page breaks
ignoreLastRenderedPageBreak: boolean = true, //disables page breaking on lastRenderedPageBreak elements
experimental: boolean = false, //enables experimental features (tab stops calculation)
trimXmlDeclaration: boolean = true, //if true, xml declaration will be removed from xml documents before parsing
useBase64URL: boolean = false, //if true, images, fonts, etc. will be converted to base 64 URL, otherwise URL.createObjectURL is used
useMathMLPolyfill: boolean = false, //includes MathML polyfills for chrome, edge, etc.
showChanges: false, //enables experimental rendering of document changes (inserions/deletions)
debug: boolean = false, //enables additional logging
}
): Promise<any>
縮略圖、目錄相關
例如,僅添加縮略圖,它不是庫的一部分。庫將 DOCX 渲染為 HTML,因此無法有效地將其用于縮略圖。
目錄是使用 TOC 字段構建的,此時沒有有效的方法來獲取目錄,因為尚不支持字段
注意事項
當前庫確實會中斷頁面:
- 如果插入了用戶/手動分頁符 - 當用戶插入分頁符時<w:br w:type="page"/>
- 如果插入了應用程序分頁符 - 可以通過編輯器應用程序(如MS Word)插入(應設置為false)<w:lastRenderedPageBreak/>ignoreLastRenderedPageBreak
- 如果段落的頁面設置已更改 - 例如:用戶將設置從縱向頁面更改為橫向頁面
未實現實時分頁符,因為它需要重新計算每次插入的大小,這可能會對性能產生很大影響。
如果分頁對您來說很困難,我建議您:
- 嘗試盡可能多地插入手動斷點
- 嘗試使用像MS Word這樣的編輯器,插入斷點<w:lastRenderedPageBreak/>
注:缺省設置為 。您可能需要將其設置為 ,以使庫按斷點中斷ignoreLastRenderedPageBreaktruetrue<w:lastRenderedPageBreak/>
狀態和穩定性
到目前為止,我無法提出解析文檔的最終方法和 API 的最終結構。只有 renderAsync 函數是穩定的,將來不應更改定義。解析和呈現的內部實現可以隨時更改。
在線體驗演示地址:
https://volodymyrbaydalka.github.io/docxjs/
#從今天起記錄我的2023#
轉載自頭條號:Git風去云往。(侵刪)