├── .editorconfig ├── .github ├── ISSUE_TEMPLATE │ └── document-rendering-bug-report.md └── workflows │ └── webpack.yml ├── .gitignore ├── LICENSE ├── README.md ├── demo ├── thumbnail.example.css ├── thumbnail.example.js └── tiff-preprocessor.js ├── dist ├── docx-preview.d.ts ├── docx-preview.js ├── docx-preview.js.map ├── docx-preview.min.js ├── docx-preview.min.js.map ├── docx-preview.min.mjs ├── docx-preview.min.mjs.map ├── docx-preview.mjs └── docx-preview.mjs.map ├── index.html ├── karma.conf.cjs ├── package.json ├── rollup.config.mjs ├── src ├── comments │ ├── comments-extended-part.ts │ ├── comments-part.ts │ └── elements.ts ├── common │ ├── open-xml-package.ts │ ├── part.ts │ └── relationship.ts ├── document-parser.ts ├── document-props │ ├── core-props-part.ts │ ├── core-props.ts │ ├── custom-props-part.ts │ ├── custom-props.ts │ ├── extended-props-part.ts │ └── extended-props.ts ├── document │ ├── bookmarks.ts │ ├── border.ts │ ├── common.ts │ ├── document-part.ts │ ├── document.ts │ ├── dom.ts │ ├── fields.ts │ ├── line-spacing.ts │ ├── paragraph.ts │ ├── run.ts │ ├── section.ts │ └── style.ts ├── docx-preview.ts ├── font-table │ ├── font-table.ts │ └── fonts.ts ├── header-footer │ ├── elements.ts │ └── parts.ts ├── html-renderer.ts ├── javascript.ts ├── length.ts ├── notes │ ├── elements.ts │ └── parts.ts ├── numbering │ ├── numbering-part.ts │ └── numbering.ts ├── parser │ └── xml-parser.ts ├── settings │ ├── settings-part.ts │ └── settings.ts ├── styles │ └── styles-part.ts ├── theme │ ├── theme-part.ts │ └── theme.ts ├── typings.d.ts ├── utils.ts ├── vml │ └── vml.ts └── word-document.ts ├── tests ├── extended-props-test │ ├── document.docx │ └── extended-props.spec.js └── render-test │ ├── equation │ ├── document.docx │ └── result.html │ ├── footnote │ ├── document.docx │ └── result.html │ ├── header-footer │ ├── document.docx │ └── result.html │ ├── line-spacing │ ├── document.docx │ └── result.html │ ├── numbering │ ├── document.docx │ └── result.html │ ├── page-layout │ ├── document.docx │ └── result.html │ ├── revision │ ├── document.docx │ └── result.html │ ├── table-spans │ ├── document.docx │ └── result.html │ ├── table │ ├── document.docx │ └── result.html │ ├── test.spec.js │ ├── text-break │ ├── document.docx │ └── result.html │ ├── text │ ├── document.docx │ └── result.html │ └── underlines │ ├── document.docx │ └── result.html └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.ts] 2 | indent_style = tab 3 | indent_size = 4 -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/document-rendering-bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Document rendering bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **Document** 14 | If applicable, add *.docx document to help explain your problem. 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | **Screenshots** 20 | If applicable, add screenshots to help explain your problem. 21 | 22 | **Desktop (please complete the following information):** 23 | - OS: [e.g. iOS] 24 | - Browser [e.g. chrome, safari] 25 | - Version [e.g. 22] 26 | 27 | **Additional context** 28 | Add any other context about the problem here. 29 | -------------------------------------------------------------------------------- /.github/workflows/webpack.yml: -------------------------------------------------------------------------------- 1 | name: NodeJS with Webpack 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | node-version: ['16.x'] 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | 20 | - name: Use Node.js ${{ matrix.node-version }} 21 | uses: actions/setup-node@v1 22 | with: 23 | node-version: ${{ matrix.node-version }} 24 | 25 | - name: Build 26 | run: | 27 | npm install 28 | npm run build 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vs 3 | bin 4 | obj 5 | docx.js.map 6 | /*.json 7 | /*.config 8 | *.log 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright (c) 2016-2023 Volodymyr Baydalka 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![npm version](https://badge.fury.io/js/docx-preview.svg)](https://www.npmjs.com/package/docx-preview) 2 | [![Support Ukraine](https://img.shields.io/badge/Support-Ukraine-blue?style=flat&logo=adguard)](https://war.ukraine.ua/) 3 | 4 | # docxjs 5 | Docx rendering library 6 | 7 | Demo - https://volodymyrbaydalka.github.io/docxjs/ 8 | 9 | Goal 10 | ---- 11 | Goal of this project is to render/convert DOCX document into HTML document with keeping HTML semantic as much as possible. 12 | That means library is limited by HTML capabilities (for example Google Docs renders *.docx document on canvas as an image). 13 | 14 | Installation 15 | ----- 16 | ``` 17 | npm install docx-preview 18 | ``` 19 | 20 | Usage 21 | ----- 22 | ```html 23 | 24 | 25 | 26 | 32 | 33 | ... 34 |
35 | ... 36 | 37 | ``` 38 | API 39 | --- 40 | ```ts 41 | // renders document into specified element 42 | renderAsync( 43 | document: Blob | ArrayBuffer | Uint8Array, // could be any type that supported by JSZip.loadAsync 44 | bodyContainer: HTMLElement, //element to render document content, 45 | styleContainer: HTMLElement, //element to render document styles, numbeings, fonts. If null, bodyContainer will be used. 46 | options: { 47 | className: string = "docx", //class name/prefix for default and document style classes 48 | inWrapper: boolean = true, //enables rendering of wrapper around document content 49 | hideWrapperOnPrint: boolean = false, //disable wrapper styles on print 50 | ignoreWidth: boolean = false, //disables rendering width of page 51 | ignoreHeight: boolean = false, //disables rendering height of page 52 | ignoreFonts: boolean = false, //disables fonts rendering 53 | breakPages: boolean = true, //enables page breaking on page breaks 54 | ignoreLastRenderedPageBreak: boolean = true, //disables page breaking on lastRenderedPageBreak elements 55 | experimental: boolean = false, //enables experimental features (tab stops calculation) 56 | trimXmlDeclaration: boolean = true, //if true, xml declaration will be removed from xml documents before parsing 57 | useBase64URL: boolean = false, //if true, images, fonts, etc. will be converted to base 64 URL, otherwise URL.createObjectURL is used 58 | renderChanges: false, //enables experimental rendering of document changes (inserions/deletions) 59 | renderHeaders: true, //enables headers rendering 60 | renderFooters: true, //enables footers rendering 61 | renderFootnotes: true, //enables footnotes rendering 62 | renderEndnotes: true, //enables endnotes rendering 63 | renderComments: false, //enables experimental comments rendering 64 | renderAltChunks: true, //enables altChunks (html parts) rendering 65 | debug: boolean = false, //enables additional logging 66 | }): Promise 67 | 68 | /// ==== experimental / internal API === 69 | // this API could be used to modify document before rendering 70 | // renderAsync = parseAsync + renderDocument 71 | 72 | // parse document and return internal document object 73 | parseAsync( 74 | document: Blob | ArrayBuffer | Uint8Array, 75 | options: Options 76 | ): Promise 77 | 78 | // render internal document object into specified container 79 | renderDocument( 80 | wordDocument: WordDocument, 81 | bodyContainer: HTMLElement, 82 | styleContainer: HTMLElement, 83 | options: Options 84 | ): Promise 85 | ``` 86 | 87 | Thumbnails, TOC and etc. 88 | ------ 89 | Thumbnails is added only for example and it's not part of library. Library renders DOCX into HTML, so it can't be efficiently used for thumbnails. 90 | 91 | Table of contents is built using the TOC fields and there is no efficient way to get table of contents at this point, since fields is not supported yet (http://officeopenxml.com/WPtableOfContents.php) 92 | 93 | Breaks 94 | ------ 95 | Currently library does break pages: 96 | - if user/manual page break `` is inserted - when user insert page break 97 | - if application page break `` is inserted - could be inserted by editor application like MS word (`ignoreLastRenderedPageBreak` should be set to false) 98 | - if page settings for paragraph is changed - ex: user change settings from portrait to landscape page 99 | 100 | Realtime page breaking is not implemented because it's requires re-calculation of sizes on each insertion and that could affect performance a lot. 101 | 102 | If page breaking is crutual for you, I would recommend: 103 | - try to insert manual break point as much as you could 104 | - try use editors like MS Word, that inserts `` break points 105 | 106 | NOTE: by default `ignoreLastRenderedPageBreak` is set to `true`. You may need to set it to `false`, to make library break by `` break points 107 | 108 | Status and stability 109 | ------ 110 | So far I can't come up with final approach of parsing documents and final structure of API. Only **renderAsync** function is stable and definition shouldn't be changed in future. Inner implementation of parsing and rendering may be changed at any point of time. 111 | -------------------------------------------------------------------------------- /demo/thumbnail.example.css: -------------------------------------------------------------------------------- 1 | details.docx-thumbnails { 2 | position: relative; 3 | background-color: rgb(101, 101, 101); 4 | border-right: 1px solid black; 5 | min-width: 1rem; 6 | } 7 | 8 | details.docx-thumbnails[open] { 9 | min-width: 120px; 10 | } 11 | 12 | details.docx-thumbnails summary { 13 | position: absolute; 14 | top: 0; 15 | left: 0; 16 | bottom: 0; 17 | width: 1rem; 18 | padding-left: 3px; 19 | } 20 | 21 | details.docx-thumbnails summary:hover { 22 | background-color: rgb(0 0 0 / 50%); 23 | } 24 | 25 | details.docx-thumbnails summary::marker { 26 | color: white; 27 | } 28 | 29 | .docx-thumbnails:empty { 30 | display: none; 31 | } 32 | 33 | .docx-thumbnails-container { 34 | height: 100%; 35 | overflow: auto; 36 | scrollbar-gutter: stable both-edges; 37 | padding: 0.25rem; 38 | } 39 | 40 | .docx-thumbnail-item { 41 | display: flex; 42 | background-color: white; 43 | text-decoration: none; 44 | color: black; 45 | align-items: center; 46 | justify-content: center; 47 | font-size: 3rem; 48 | aspect-ratio: 6 / 8; 49 | width: 100px; 50 | box-shadow: 0 0 10px rgb(0 0 0 / 50%); 51 | margin: 1rem; 52 | } -------------------------------------------------------------------------------- /demo/thumbnail.example.js: -------------------------------------------------------------------------------- 1 | function renderThumbnails(docxContainer, thumbnailsContainer) { 2 | const sections = docxContainer.querySelectorAll('.docx-wrapper>section'); 3 | 4 | thumbnailsContainer.innerHTML = ""; 5 | 6 | for (let i = 0; i < sections.length; i ++) { 7 | const id = `docx-page-${i + 1}`; 8 | const thumbnail = document.createElement('a'); 9 | 10 | thumbnail.className = 'docx-thumbnail-item'; 11 | thumbnail.href = `#${id}`; 12 | thumbnail.innerText = `${i + 1}`; 13 | thumbnailsContainer.appendChild(thumbnail); 14 | 15 | sections[i].setAttribute("id", id); 16 | } 17 | } -------------------------------------------------------------------------------- /demo/tiff-preprocessor.js: -------------------------------------------------------------------------------- 1 | async function preprocessTiff(blob) { 2 | let zip = await JSZip.loadAsync(blob); 3 | const tiffs = zip.file(/[.]tiff?$/); 4 | 5 | if (tiffs.length == 0) 6 | return blob; 7 | 8 | for (let f of tiffs) { 9 | const buffer = await f.async("uint8array"); 10 | const tiff = new Tiff({ buffer }); 11 | const blob = await new Promise(res => tiff.toCanvas().toBlob(blob => res(blob), "image/png")); 12 | zip.file(f.name, blob); 13 | } 14 | 15 | return await zip.generateAsync({ type: "blob" }); 16 | } -------------------------------------------------------------------------------- /dist/docx-preview.d.ts: -------------------------------------------------------------------------------- 1 | export interface Options { 2 | inWrapper: boolean; 3 | hideWrapperOnPrint: boolean; 4 | ignoreWidth: boolean; 5 | ignoreHeight: boolean; 6 | ignoreFonts: boolean; 7 | breakPages: boolean; 8 | debug: boolean; 9 | experimental: boolean; 10 | className: string; 11 | trimXmlDeclaration: boolean; 12 | renderHeaders: boolean; 13 | renderFooters: boolean; 14 | renderFootnotes: boolean; 15 | renderEndnotes: boolean; 16 | ignoreLastRenderedPageBreak: boolean; 17 | useBase64URL: boolean; 18 | renderChanges: boolean; 19 | renderComments: boolean; 20 | renderAltChunks: boolean; 21 | } 22 | //stub 23 | export type WordDocument = any; 24 | export declare const defaultOptions: Options; 25 | export declare function parseAsync(data: Blob | any, userOptions?: Partial): Promise; 26 | export declare function renderDocument(document: WordDocument, bodyContainer: HTMLElement, styleContainer?: HTMLElement, userOptions?: Partial): Promise; 27 | export declare function renderAsync(data: Blob | any, bodyContainer: HTMLElement, styleContainer?: HTMLElement, userOptions?: Partial): Promise; 28 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 33 | 34 | 35 | 36 | 39 | 40 |
41 | 42 | 43 |
44 | 47 |
48 | 49 | 57 | 58 |
59 | 60 |
61 |
62 | 63 |
64 |
65 |
66 |
67 | 68 | 159 | 160 | 161 | -------------------------------------------------------------------------------- /karma.conf.cjs: -------------------------------------------------------------------------------- 1 | module.exports = (config) => { 2 | config.set({ 3 | basePath: '', 4 | frameworks: ['jasmine'], 5 | files: [ 6 | 'node_modules/jszip/dist/jszip.js', 7 | 'node_modules/diff/dist/diff.js', 8 | 'dist/docx-preview.js', 9 | 'tests/**/*spec.js', 10 | { pattern: 'tests/**/*.docx', included: false }, 11 | { pattern: 'tests/**/*.html', included: false } 12 | ], 13 | reporters: ['progress'], 14 | port: 9876, 15 | colors: true, 16 | logLevel: config.LOG_INFO, 17 | autoWatch: true, 18 | browsers: ['Chrome'], 19 | singleRun: false, 20 | concurrency: Infinity, 21 | crossOriginAttribute: false 22 | }) 23 | } 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "docx-preview", 3 | "version": "0.3.5", 4 | "license": "Apache-2.0", 5 | "keywords": [ 6 | "word", 7 | "docx" 8 | ], 9 | "author": { 10 | "name": "Volodymyr Baydalka" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/zVolodymyr/docxjs.git" 15 | }, 16 | "dependencies": { 17 | "jszip": ">=3.0.0" 18 | }, 19 | "devDependencies": { 20 | "rollup": "^4.9.1", 21 | "@rollup/plugin-terser": "^0.4.4", 22 | "@rollup/plugin-typescript": "^11.1.5", 23 | "diff": "^5.0.0", 24 | "jasmine-core": "^5.1.0", 25 | "karma": "^6.3.9", 26 | "karma-chrome-launcher": "^3.1.0", 27 | "karma-firefox-launcher": "^2.1.2", 28 | "karma-jasmine": "^5.0.0", 29 | "tslib": "^2.4.0", 30 | "typescript": "^5.0.3" 31 | }, 32 | "scripts": { 33 | "build": "rollup --config rollup.config.mjs", 34 | "build-prod": "rollup --config rollup.config.mjs --environment BUILD:production", 35 | "watch": "rollup --config rollup.config.mjs --watch", 36 | "e2e": "karma start karma.conf.cjs --single-run", 37 | "e2e-watch": "karma start karma.conf.cjs" 38 | }, 39 | "files": [ 40 | "dist" 41 | ], 42 | "exports": { 43 | ".": { 44 | "import": "./dist/docx-preview.mjs", 45 | "require": "./dist/docx-preview.js", 46 | "types": "./dist/docx-preview.d.ts" 47 | } 48 | }, 49 | "types": "dist/docx-preview.d.ts" 50 | } 51 | -------------------------------------------------------------------------------- /rollup.config.mjs: -------------------------------------------------------------------------------- 1 | import typescript from '@rollup/plugin-typescript'; 2 | import terser from '@rollup/plugin-terser'; 3 | 4 | const umdOutput = { 5 | name: "docx", 6 | file: 'dist/docx-preview.js', 7 | sourcemap: true, 8 | format: 'umd', 9 | globals: { 10 | jszip: 'JSZip' 11 | } 12 | }; 13 | 14 | export default args => { 15 | const config = { 16 | input: 'src/docx-preview.ts', 17 | output: [umdOutput], 18 | plugins: [typescript()] 19 | } 20 | 21 | if (args.environment == 'BUILD:production') 22 | config.output = [umdOutput, 23 | { 24 | ...umdOutput, 25 | file: 'dist/docx-preview.min.js', 26 | plugins: [terser()] 27 | }, 28 | { 29 | file: 'dist/docx-preview.mjs', 30 | sourcemap: true, 31 | format: 'es', 32 | }, 33 | { 34 | file: 'dist/docx-preview.min.mjs', 35 | sourcemap: true, 36 | format: 'es', 37 | plugins: [terser()] 38 | }]; 39 | 40 | return config 41 | }; -------------------------------------------------------------------------------- /src/comments/comments-extended-part.ts: -------------------------------------------------------------------------------- 1 | import { Part } from "../common/part"; 2 | import { OpenXmlPackage } from "../common/open-xml-package"; 3 | import { keyBy } from "../utils"; 4 | 5 | export type CommentsExtended = { 6 | paraId: string; 7 | paraIdParent?: string; 8 | done: boolean; 9 | } 10 | 11 | export class CommentsExtendedPart extends Part { 12 | comments: CommentsExtended[] = []; 13 | commentMap: Record; 14 | 15 | constructor(pkg: OpenXmlPackage, path: string) { 16 | super(pkg, path); 17 | } 18 | 19 | parseXml(root: Element) { 20 | const xml = this._package.xmlParser; 21 | 22 | for (let el of xml.elements(root, "commentEx")) { 23 | this.comments.push({ 24 | paraId: xml.attr(el, 'paraId'), 25 | paraIdParent: xml.attr(el, 'paraIdParent'), 26 | done: xml.boolAttr(el, 'done') 27 | }); 28 | } 29 | 30 | this.commentMap = keyBy(this.comments, x => x.paraId); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/comments/comments-part.ts: -------------------------------------------------------------------------------- 1 | import { Part } from "../common/part"; 2 | import { OpenXmlPackage } from "../common/open-xml-package"; 3 | import { DocumentParser } from "../document-parser"; 4 | import { WmlComment } from "./elements"; 5 | import { keyBy } from "../utils"; 6 | 7 | export class CommentsPart extends Part { 8 | protected _documentParser: DocumentParser; 9 | 10 | comments: WmlComment[] 11 | commentMap: Record; 12 | 13 | constructor(pkg: OpenXmlPackage, path: string, parser: DocumentParser) { 14 | super(pkg, path); 15 | this._documentParser = parser; 16 | } 17 | 18 | parseXml(root: Element) { 19 | this.comments = this._documentParser.parseComments(root); 20 | this.commentMap = keyBy(this.comments, x => x.id); 21 | } 22 | } -------------------------------------------------------------------------------- /src/comments/elements.ts: -------------------------------------------------------------------------------- 1 | import { DomType, OpenXmlElementBase } from "../document/dom"; 2 | 3 | export class WmlComment extends OpenXmlElementBase { 4 | type = DomType.Comment; 5 | id: string; 6 | author: string; 7 | initials: string; 8 | date: string; 9 | } 10 | 11 | export class WmlCommentReference extends OpenXmlElementBase { 12 | type = DomType.CommentReference; 13 | 14 | constructor(public id?: string) { 15 | super(); 16 | } 17 | } 18 | 19 | export class WmlCommentRangeStart extends OpenXmlElementBase { 20 | type = DomType.CommentRangeStart; 21 | 22 | constructor(public id?: string) { 23 | super(); 24 | } 25 | } 26 | export class WmlCommentRangeEnd extends OpenXmlElementBase { 27 | type = DomType.CommentRangeEnd; 28 | 29 | constructor(public id?: string) { 30 | super(); 31 | } 32 | } -------------------------------------------------------------------------------- /src/common/open-xml-package.ts: -------------------------------------------------------------------------------- 1 | import JSZip from "jszip"; 2 | import { parseXmlString, XmlParser } from "../parser/xml-parser"; 3 | import { splitPath } from "../utils"; 4 | import { parseRelationships, Relationship } from "./relationship"; 5 | 6 | export interface OpenXmlPackageOptions { 7 | trimXmlDeclaration: boolean, 8 | keepOrigin: boolean, 9 | } 10 | 11 | export class OpenXmlPackage { 12 | xmlParser: XmlParser = new XmlParser(); 13 | 14 | constructor(private _zip: JSZip, public options: OpenXmlPackageOptions) { 15 | } 16 | 17 | get(path: string): any { 18 | const p = normalizePath(path); 19 | return this._zip.files[p] ?? this._zip.files[p.replace(/\//g, '\\')]; 20 | } 21 | 22 | update(path: string, content: any) { 23 | this._zip.file(path, content); 24 | } 25 | 26 | static async load(input: Blob | any, options: OpenXmlPackageOptions): Promise { 27 | const zip = await JSZip.loadAsync(input); 28 | return new OpenXmlPackage(zip, options); 29 | } 30 | 31 | save(type: any = "blob"): Promise { 32 | return this._zip.generateAsync({ type }); 33 | } 34 | 35 | load(path: string, type: JSZip.OutputType = "string"): Promise { 36 | return this.get(path)?.async(type) ?? Promise.resolve(null); 37 | } 38 | 39 | async loadRelationships(path: string = null): Promise { 40 | let relsPath = `_rels/.rels`; 41 | 42 | if (path != null) { 43 | const [f, fn] = splitPath(path); 44 | relsPath = `${f}_rels/${fn}.rels`; 45 | } 46 | 47 | const txt = await this.load(relsPath); 48 | return txt ? parseRelationships(this.parseXmlDocument(txt).firstElementChild, this.xmlParser) : null; 49 | } 50 | 51 | /** @internal */ 52 | parseXmlDocument(txt: string): Document { 53 | return parseXmlString(txt, this.options.trimXmlDeclaration); 54 | } 55 | } 56 | 57 | function normalizePath(path: string) { 58 | return path.startsWith('/') ? path.substr(1) : path; 59 | } -------------------------------------------------------------------------------- /src/common/part.ts: -------------------------------------------------------------------------------- 1 | import { serializeXmlString } from "../parser/xml-parser"; 2 | import { OpenXmlPackage } from "./open-xml-package"; 3 | import { Relationship } from "./relationship"; 4 | 5 | export class Part { 6 | protected _xmlDocument: Document; 7 | 8 | rels: Relationship[]; 9 | 10 | constructor(protected _package: OpenXmlPackage, public path: string) { 11 | } 12 | 13 | async load(): Promise { 14 | this.rels = await this._package.loadRelationships(this.path); 15 | 16 | const xmlText = await this._package.load(this.path); 17 | const xmlDoc = this._package.parseXmlDocument(xmlText); 18 | 19 | if (this._package.options.keepOrigin) { 20 | this._xmlDocument = xmlDoc; 21 | } 22 | 23 | this.parseXml(xmlDoc.firstElementChild); 24 | } 25 | 26 | save() { 27 | this._package.update(this.path, serializeXmlString(this._xmlDocument)); 28 | } 29 | 30 | protected parseXml(root: Element) { 31 | } 32 | } -------------------------------------------------------------------------------- /src/common/relationship.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | 3 | export interface Relationship { 4 | id: string, 5 | type: RelationshipTypes | string, 6 | target: string 7 | targetMode: "" | "External" | string 8 | } 9 | 10 | export enum RelationshipTypes { 11 | OfficeDocument = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", 12 | FontTable = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable", 13 | Image = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", 14 | Numbering = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering", 15 | Styles = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles", 16 | StylesWithEffects = "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects", 17 | Theme = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme", 18 | Settings = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings", 19 | WebSettings = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings", 20 | Hyperlink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", 21 | Footnotes = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes", 22 | Endnotes = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes", 23 | Footer = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer", 24 | Header = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header", 25 | ExtendedProperties = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", 26 | CoreProperties = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", 27 | CustomProperties = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/custom-properties", 28 | Comments = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments", 29 | CommentsExtended = "http://schemas.microsoft.com/office/2011/relationships/commentsExtended", 30 | AltChunk = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" 31 | } 32 | 33 | export function parseRelationships(root: Element, xml: XmlParser): Relationship[] { 34 | return xml.elements(root).map(e => { 35 | id: xml.attr(e, "Id"), 36 | type: xml.attr(e, "Type"), 37 | target: xml.attr(e, "Target"), 38 | targetMode: xml.attr(e, "TargetMode") 39 | }); 40 | } -------------------------------------------------------------------------------- /src/document-props/core-props-part.ts: -------------------------------------------------------------------------------- 1 | import { Part } from "../common/part"; 2 | import { CorePropsDeclaration, parseCoreProps } from "./core-props"; 3 | 4 | export class CorePropsPart extends Part { 5 | props: CorePropsDeclaration; 6 | 7 | parseXml(root: Element) { 8 | this.props = parseCoreProps(root, this._package.xmlParser); 9 | } 10 | } -------------------------------------------------------------------------------- /src/document-props/core-props.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | 3 | export interface CorePropsDeclaration { 4 | title: string, 5 | description: string, 6 | subject: string, 7 | creator: string, 8 | keywords: string, 9 | language: string, 10 | lastModifiedBy: string, 11 | revision: number, 12 | } 13 | 14 | export function parseCoreProps(root: Element, xmlParser: XmlParser): CorePropsDeclaration { 15 | const result = {}; 16 | 17 | for (let el of xmlParser.elements(root)) { 18 | switch (el.localName) { 19 | case "title": result.title = el.textContent; break; 20 | case "description": result.description = el.textContent; break; 21 | case "subject": result.subject = el.textContent; break; 22 | case "creator": result.creator = el.textContent; break; 23 | case "keywords": result.keywords = el.textContent; break; 24 | case "language": result.language = el.textContent; break; 25 | case "lastModifiedBy": result.lastModifiedBy = el.textContent; break; 26 | case "revision": el.textContent && (result.revision = parseInt(el.textContent)); break; 27 | } 28 | } 29 | 30 | return result; 31 | } -------------------------------------------------------------------------------- /src/document-props/custom-props-part.ts: -------------------------------------------------------------------------------- 1 | import { Part } from "../common/part"; 2 | import { CustomProperty, parseCustomProps } from "./custom-props"; 3 | 4 | export class CustomPropsPart extends Part { 5 | props: CustomProperty[]; 6 | 7 | parseXml(root: Element) { 8 | this.props = parseCustomProps(root, this._package.xmlParser); 9 | } 10 | } -------------------------------------------------------------------------------- /src/document-props/custom-props.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | 3 | export interface CustomProperty { 4 | formatId: string; 5 | name: string; 6 | type: string; 7 | value: string; 8 | } 9 | 10 | export function parseCustomProps(root: Element, xml: XmlParser): CustomProperty[] { 11 | return xml.elements(root, "property").map(e => { 12 | const firstChild = e.firstChild; 13 | 14 | return { 15 | formatId: xml.attr(e, "fmtid"), 16 | name: xml.attr(e, "name"), 17 | type: firstChild.nodeName, 18 | value: firstChild.textContent 19 | }; 20 | }); 21 | } -------------------------------------------------------------------------------- /src/document-props/extended-props-part.ts: -------------------------------------------------------------------------------- 1 | import { Part } from "../common/part"; 2 | import { ExtendedPropsDeclaration, parseExtendedProps } from "./extended-props"; 3 | 4 | export class ExtendedPropsPart extends Part { 5 | props: ExtendedPropsDeclaration; 6 | 7 | parseXml(root: Element) { 8 | this.props = parseExtendedProps(root, this._package.xmlParser); 9 | } 10 | } -------------------------------------------------------------------------------- /src/document-props/extended-props.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | 3 | export interface ExtendedPropsDeclaration { 4 | template: string, 5 | totalTime: number, 6 | pages: number, 7 | words: number, 8 | characters: number, 9 | application: string, 10 | lines: number, 11 | paragraphs: number, 12 | company: string, 13 | appVersion: string 14 | } 15 | 16 | export function parseExtendedProps(root: Element, xmlParser: XmlParser): ExtendedPropsDeclaration { 17 | const result = { 18 | 19 | }; 20 | 21 | for (let el of xmlParser.elements(root)) { 22 | switch (el.localName) { 23 | case "Template": 24 | result.template = el.textContent; 25 | break; 26 | case "Pages": 27 | result.pages = safeParseToInt(el.textContent); 28 | break; 29 | case "Words": 30 | result.words = safeParseToInt(el.textContent); 31 | break; 32 | case "Characters": 33 | result.characters = safeParseToInt(el.textContent); 34 | break; 35 | case "Application": 36 | result.application = el.textContent; 37 | break; 38 | case "Lines": 39 | result.lines = safeParseToInt(el.textContent); 40 | break; 41 | case "Paragraphs": 42 | result.paragraphs = safeParseToInt(el.textContent); 43 | break; 44 | case "Company": 45 | result.company = el.textContent; 46 | break; 47 | case "AppVersion": 48 | result.appVersion = el.textContent; 49 | break; 50 | } 51 | } 52 | 53 | return result; 54 | } 55 | 56 | function safeParseToInt(value: string): number { 57 | if (typeof value === 'undefined') 58 | return; 59 | return parseInt(value); 60 | } -------------------------------------------------------------------------------- /src/document/bookmarks.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | import { DomType, OpenXmlElement } from "./dom"; 3 | 4 | export interface WmlBookmarkStart extends OpenXmlElement { 5 | id: string; 6 | name: string; 7 | colFirst: number; 8 | colLast: number; 9 | } 10 | 11 | export interface WmlBookmarkEnd extends OpenXmlElement { 12 | id: string; 13 | } 14 | 15 | export function parseBookmarkStart(elem: Element, xml: XmlParser): WmlBookmarkStart { 16 | return { 17 | type: DomType.BookmarkStart, 18 | id: xml.attr(elem, "id"), 19 | name: xml.attr(elem, "name"), 20 | colFirst: xml.intAttr(elem, "colFirst"), 21 | colLast: xml.intAttr(elem, "colLast") 22 | } 23 | } 24 | 25 | export function parseBookmarkEnd(elem: Element, xml: XmlParser): WmlBookmarkEnd { 26 | return { 27 | type: DomType.BookmarkEnd, 28 | id: xml.attr(elem, "id") 29 | } 30 | } -------------------------------------------------------------------------------- /src/document/border.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | import { Length, LengthUsage } from "./common"; 3 | 4 | export interface Border { 5 | color: string; 6 | type: string; 7 | size: Length; 8 | frame: boolean; 9 | shadow: boolean; 10 | offset: Length; 11 | } 12 | 13 | export interface Borders { 14 | top: Border; 15 | left: Border; 16 | right: Border; 17 | bottom: Border; 18 | } 19 | 20 | export function parseBorder(elem: Element, xml: XmlParser): Border { 21 | return { 22 | type: xml.attr(elem, "val"), 23 | color: xml.attr(elem, "color"), 24 | size: xml.lengthAttr(elem, "sz", LengthUsage.Border), 25 | offset: xml.lengthAttr(elem, "space", LengthUsage.Point), 26 | frame: xml.boolAttr(elem, 'frame'), 27 | shadow: xml.boolAttr(elem, 'shadow') 28 | }; 29 | } 30 | 31 | export function parseBorders(elem: Element, xml: XmlParser): Borders { 32 | var result = {}; 33 | 34 | for (let e of xml.elements(elem)) { 35 | switch (e.localName) { 36 | case "left": result.left = parseBorder(e, xml); break; 37 | case "top": result.top = parseBorder(e, xml); break; 38 | case "right": result.right = parseBorder(e, xml); break; 39 | case "bottom": result.bottom = parseBorder(e, xml); break; 40 | } 41 | } 42 | 43 | return result; 44 | } -------------------------------------------------------------------------------- /src/document/common.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | import { clamp } from "../utils"; 3 | 4 | export const ns = { 5 | wordml: "http://schemas.openxmlformats.org/wordprocessingml/2006/main", 6 | drawingml: "http://schemas.openxmlformats.org/drawingml/2006/main", 7 | picture: "http://schemas.openxmlformats.org/drawingml/2006/picture", 8 | compatibility: "http://schemas.openxmlformats.org/markup-compatibility/2006", 9 | math: "http://schemas.openxmlformats.org/officeDocument/2006/math" 10 | } 11 | 12 | export type LengthType = "px" | "pt" | "%" | ""; 13 | export type Length = string; 14 | 15 | export interface Font { 16 | name: string; 17 | family: string; 18 | } 19 | 20 | export interface CommonProperties { 21 | fontSize: Length; 22 | color: string; 23 | } 24 | 25 | export type LengthUsageType = { mul: number, unit: LengthType, min?: number, max?: number }; 26 | 27 | export const LengthUsage: Record = { 28 | Dxa: { mul: 0.05, unit: "pt" }, //twips 29 | Emu: { mul: 1 / 12700, unit: "pt" }, 30 | FontSize: { mul: 0.5, unit: "pt" }, 31 | Border: { mul: 0.125, unit: "pt", min: 0.25, max: 12 }, //NOTE: http://officeopenxml.com/WPtextBorders.php 32 | Point: { mul: 1, unit: "pt" }, 33 | Percent: { mul: 0.02, unit: "%" }, 34 | LineHeight: { mul: 1 / 240, unit: "" }, 35 | VmlEmu: { mul: 1 / 12700, unit: "" }, 36 | } 37 | 38 | export function convertLength(val: string, usage: LengthUsageType = LengthUsage.Dxa): string { 39 | //"simplified" docx documents use pt's as units 40 | if (val == null || /.+(p[xt]|[%])$/.test(val)) { 41 | return val; 42 | } 43 | 44 | var num = parseInt(val) * usage.mul; 45 | 46 | if (usage.min && usage.max) 47 | num = clamp(num, usage.min, usage.max); 48 | 49 | return `${num.toFixed(2)}${usage.unit}`; 50 | } 51 | 52 | export function convertBoolean(v: string, defaultValue = false): boolean { 53 | switch (v) { 54 | case "1": return true; 55 | case "0": return false; 56 | case "on": return true; 57 | case "off": return false; 58 | case "true": return true; 59 | case "false": return false; 60 | default: return defaultValue; 61 | } 62 | } 63 | 64 | export function convertPercentage(val: string): number { 65 | return val ? parseInt(val) / 100 : null; 66 | } 67 | 68 | export function parseCommonProperty(elem: Element, props: CommonProperties, xml: XmlParser): boolean { 69 | if(elem.namespaceURI != ns.wordml) 70 | return false; 71 | 72 | switch(elem.localName) { 73 | case "color": 74 | props.color = xml.attr(elem, "val"); 75 | break; 76 | 77 | case "sz": 78 | props.fontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize); 79 | break; 80 | 81 | default: 82 | return false; 83 | } 84 | 85 | return true; 86 | } -------------------------------------------------------------------------------- /src/document/document-part.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlPackage } from "../common/open-xml-package"; 2 | import { Part } from "../common/part"; 3 | import { DocumentParser } from "../document-parser"; 4 | import { DocumentElement } from "./document"; 5 | 6 | export class DocumentPart extends Part { 7 | private _documentParser: DocumentParser; 8 | 9 | constructor(pkg: OpenXmlPackage, path: string, parser: DocumentParser) { 10 | super(pkg, path); 11 | this._documentParser = parser; 12 | } 13 | 14 | body: DocumentElement 15 | 16 | parseXml(root: Element) { 17 | this.body = this._documentParser.parseDocumentFile(root); 18 | } 19 | } -------------------------------------------------------------------------------- /src/document/document.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlElement } from "./dom"; 2 | import { SectionProperties } from "./section"; 3 | 4 | export interface DocumentElement extends OpenXmlElement { 5 | props: SectionProperties; 6 | } -------------------------------------------------------------------------------- /src/document/dom.ts: -------------------------------------------------------------------------------- 1 | export enum DomType { 2 | Document = "document", 3 | Paragraph = "paragraph", 4 | Run = "run", 5 | Break = "break", 6 | NoBreakHyphen = "noBreakHyphen", 7 | Table = "table", 8 | Row = "row", 9 | Cell = "cell", 10 | Hyperlink = "hyperlink", 11 | SmartTag = "smartTag", 12 | Drawing = "drawing", 13 | Image = "image", 14 | Text = "text", 15 | Tab = "tab", 16 | Symbol = "symbol", 17 | BookmarkStart = "bookmarkStart", 18 | BookmarkEnd = "bookmarkEnd", 19 | Footer = "footer", 20 | Header = "header", 21 | FootnoteReference = "footnoteReference", 22 | EndnoteReference = "endnoteReference", 23 | Footnote = "footnote", 24 | Endnote = "endnote", 25 | SimpleField = "simpleField", 26 | ComplexField = "complexField", 27 | Instruction = "instruction", 28 | VmlPicture = "vmlPicture", 29 | MmlMath = "mmlMath", 30 | MmlMathParagraph = "mmlMathParagraph", 31 | MmlFraction = "mmlFraction", 32 | MmlFunction = "mmlFunction", 33 | MmlFunctionName = "mmlFunctionName", 34 | MmlNumerator = "mmlNumerator", 35 | MmlDenominator = "mmlDenominator", 36 | MmlRadical = "mmlRadical", 37 | MmlBase = "mmlBase", 38 | MmlDegree = "mmlDegree", 39 | MmlSuperscript = "mmlSuperscript", 40 | MmlSubscript = "mmlSubscript", 41 | MmlPreSubSuper = "mmlPreSubSuper", 42 | MmlSubArgument = "mmlSubArgument", 43 | MmlSuperArgument = "mmlSuperArgument", 44 | MmlNary = "mmlNary", 45 | MmlDelimiter = "mmlDelimiter", 46 | MmlRun = "mmlRun", 47 | MmlEquationArray = "mmlEquationArray", 48 | MmlLimit = "mmlLimit", 49 | MmlLimitLower = "mmlLimitLower", 50 | MmlMatrix = "mmlMatrix", 51 | MmlMatrixRow = "mmlMatrixRow", 52 | MmlBox = "mmlBox", 53 | MmlBar = "mmlBar", 54 | MmlGroupChar = "mmlGroupChar", 55 | VmlElement = "vmlElement", 56 | Inserted = "inserted", 57 | Deleted = "deleted", 58 | DeletedText = "deletedText", 59 | Comment = "comment", 60 | CommentReference = "commentReference", 61 | CommentRangeStart = "commentRangeStart", 62 | CommentRangeEnd = "commentRangeEnd", 63 | AltChunk = "altChunk" 64 | } 65 | 66 | export interface OpenXmlElement { 67 | type: DomType; 68 | children?: OpenXmlElement[]; 69 | cssStyle?: Record; 70 | props?: Record; 71 | 72 | styleName?: string; //style name 73 | className?: string; //class mods 74 | 75 | parent?: OpenXmlElement; 76 | } 77 | 78 | export abstract class OpenXmlElementBase implements OpenXmlElement { 79 | type: DomType; 80 | children?: OpenXmlElement[] = []; 81 | cssStyle?: Record = {}; 82 | props?: Record; 83 | 84 | className?: string; 85 | styleName?: string; 86 | 87 | parent?: OpenXmlElement; 88 | } 89 | 90 | export interface WmlHyperlink extends OpenXmlElement { 91 | id?: string; 92 | anchor?: string; 93 | } 94 | 95 | export interface WmlAltChunk extends OpenXmlElement { 96 | id?: string; 97 | } 98 | 99 | export interface WmlSmartTag extends OpenXmlElement { 100 | uri?: string; 101 | element?: string; 102 | } 103 | 104 | export interface WmlNoteReference extends OpenXmlElement { 105 | id: string; 106 | } 107 | 108 | export interface WmlBreak extends OpenXmlElement{ 109 | break: "page" | "lastRenderedPageBreak" | "textWrapping"; 110 | } 111 | 112 | export interface WmlText extends OpenXmlElement{ 113 | text: string; 114 | } 115 | 116 | export interface WmlSymbol extends OpenXmlElement { 117 | font: string; 118 | char: string; 119 | } 120 | 121 | export interface WmlTable extends OpenXmlElement { 122 | columns?: WmlTableColumn[]; 123 | cellStyle?: Record; 124 | 125 | colBandSize?: number; 126 | rowBandSize?: number; 127 | } 128 | 129 | export interface WmlTableRow extends OpenXmlElement { 130 | isHeader?: boolean; 131 | gridBefore?: number; 132 | gridAfter?: number; 133 | } 134 | 135 | export interface WmlTableCell extends OpenXmlElement { 136 | verticalMerge?: 'restart' | 'continue' | string; 137 | span?: number; 138 | } 139 | 140 | export interface IDomImage extends OpenXmlElement { 141 | src: string; 142 | } 143 | 144 | export interface WmlTableColumn { 145 | width?: string; 146 | } 147 | 148 | export interface IDomNumbering { 149 | id: string; 150 | level: number; 151 | start: number; 152 | pStyleName: string; 153 | pStyle: Record; 154 | rStyle: Record; 155 | levelText?: string; 156 | suff: string; 157 | format?: string; 158 | bullet?: NumberingPicBullet; 159 | } 160 | 161 | export interface NumberingPicBullet { 162 | id: number; 163 | src: string; 164 | style?: string; 165 | } 166 | -------------------------------------------------------------------------------- /src/document/fields.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlElement } from "./dom"; 2 | 3 | export interface WmlInstructionText extends OpenXmlElement { 4 | text: string; 5 | } 6 | 7 | export interface WmlFieldChar extends OpenXmlElement { 8 | charType: 'begin' | 'end' | 'separate' | string; 9 | lock: boolean; 10 | } 11 | 12 | export interface WmlFieldSimple extends OpenXmlElement { 13 | instruction: string; 14 | lock: boolean; 15 | dirty: boolean; 16 | } -------------------------------------------------------------------------------- /src/document/line-spacing.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | import { Length } from "./common"; 3 | 4 | export interface LineSpacing { 5 | after: Length; 6 | before: Length; 7 | line: number; 8 | lineRule: "atLeast" | "exactly" | "auto"; 9 | } 10 | 11 | export function parseLineSpacing(elem: Element, xml: XmlParser): LineSpacing { 12 | return { 13 | before: xml.lengthAttr(elem, "before"), 14 | after: xml.lengthAttr(elem, "after"), 15 | line: xml.intAttr(elem, "line"), 16 | lineRule: xml.attr(elem, "lineRule") 17 | } as LineSpacing; 18 | } -------------------------------------------------------------------------------- /src/document/paragraph.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlElement } from "./dom"; 2 | import { CommonProperties, Length, ns, parseCommonProperty } from "./common"; 3 | import { Borders } from "./border"; 4 | import { parseSectionProperties, SectionProperties } from "./section"; 5 | import { LineSpacing, parseLineSpacing } from "./line-spacing"; 6 | import { XmlParser } from "../parser/xml-parser"; 7 | import { parseRunProperties, RunProperties } from "./run"; 8 | 9 | export interface WmlParagraph extends OpenXmlElement, ParagraphProperties { 10 | } 11 | 12 | export interface ParagraphProperties extends CommonProperties { 13 | sectionProps: SectionProperties; 14 | tabs: ParagraphTab[]; 15 | numbering: ParagraphNumbering; 16 | 17 | border: Borders; 18 | textAlignment: "auto" | "baseline" | "bottom" | "center" | "top" | string; 19 | lineSpacing: LineSpacing; 20 | keepLines: boolean; 21 | keepNext: boolean; 22 | pageBreakBefore: boolean; 23 | outlineLevel: number; 24 | styleName?: string; 25 | 26 | runProps: RunProperties; 27 | } 28 | 29 | export interface ParagraphTab { 30 | style: "bar" | "center" | "clear" | "decimal" | "end" | "num" | "start" | "left" | "right"; 31 | leader: "none" | "dot" | "heavy" | "hyphen" | "middleDot" | "underscore"; 32 | position: Length; 33 | } 34 | 35 | export interface ParagraphNumbering { 36 | id: string; 37 | level: number; 38 | } 39 | 40 | export function parseParagraphProperties(elem: Element, xml: XmlParser): ParagraphProperties { 41 | let result = {}; 42 | 43 | for(let el of xml.elements(elem)) { 44 | parseParagraphProperty(el, result, xml); 45 | } 46 | 47 | return result; 48 | } 49 | 50 | export function parseParagraphProperty(elem: Element, props: ParagraphProperties, xml: XmlParser) { 51 | if (elem.namespaceURI != ns.wordml) 52 | return false; 53 | 54 | if(parseCommonProperty(elem, props, xml)) 55 | return true; 56 | 57 | switch (elem.localName) { 58 | case "tabs": 59 | props.tabs = parseTabs(elem, xml); 60 | break; 61 | 62 | case "sectPr": 63 | props.sectionProps = parseSectionProperties(elem, xml); 64 | break; 65 | 66 | case "numPr": 67 | props.numbering = parseNumbering(elem, xml); 68 | break; 69 | 70 | case "spacing": 71 | props.lineSpacing = parseLineSpacing(elem, xml); 72 | return false; // TODO 73 | break; 74 | 75 | case "textAlignment": 76 | props.textAlignment = xml.attr(elem, "val"); 77 | return false; //TODO 78 | break; 79 | 80 | case "keepLines": 81 | props.keepLines = xml.boolAttr(elem, "val", true); 82 | break; 83 | 84 | case "keepNext": 85 | props.keepNext = xml.boolAttr(elem, "val", true); 86 | break; 87 | 88 | case "pageBreakBefore": 89 | props.pageBreakBefore = xml.boolAttr(elem, "val", true); 90 | break; 91 | 92 | case "outlineLvl": 93 | props.outlineLevel = xml.intAttr(elem, "val"); 94 | break; 95 | 96 | case "pStyle": 97 | props.styleName = xml.attr(elem, "val"); 98 | break; 99 | 100 | case "rPr": 101 | props.runProps = parseRunProperties(elem, xml); 102 | break; 103 | 104 | default: 105 | return false; 106 | } 107 | 108 | return true; 109 | } 110 | 111 | export function parseTabs(elem: Element, xml: XmlParser): ParagraphTab[] { 112 | return xml.elements(elem, "tab") 113 | .map(e => { 114 | position: xml.lengthAttr(e, "pos"), 115 | leader: xml.attr(e, "leader"), 116 | style: xml.attr(e, "val") 117 | }); 118 | } 119 | 120 | export function parseNumbering(elem: Element, xml: XmlParser): ParagraphNumbering { 121 | var result = {}; 122 | 123 | for (let e of xml.elements(elem)) { 124 | switch (e.localName) { 125 | case "numId": 126 | result.id = xml.attr(e, "val"); 127 | break; 128 | 129 | case "ilvl": 130 | result.level = xml.intAttr(e, "val"); 131 | break; 132 | } 133 | } 134 | 135 | return result; 136 | } -------------------------------------------------------------------------------- /src/document/run.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | import { CommonProperties, parseCommonProperty } from "./common"; 3 | import { OpenXmlElement } from "./dom"; 4 | 5 | export interface WmlRun extends OpenXmlElement, RunProperties { 6 | id?: string; 7 | verticalAlign?: string; 8 | fieldRun?: boolean; 9 | } 10 | 11 | export interface RunProperties extends CommonProperties { 12 | 13 | } 14 | 15 | export function parseRunProperties(elem: Element, xml: XmlParser): RunProperties { 16 | let result = {}; 17 | 18 | for(let el of xml.elements(elem)) { 19 | parseRunProperty(el, result, xml); 20 | } 21 | 22 | return result; 23 | } 24 | 25 | export function parseRunProperty(elem: Element, props: RunProperties, xml: XmlParser) { 26 | if (parseCommonProperty(elem, props, xml)) 27 | return true; 28 | 29 | return false; 30 | } -------------------------------------------------------------------------------- /src/document/section.ts: -------------------------------------------------------------------------------- 1 | import globalXmlParser, { XmlParser } from "../parser/xml-parser"; 2 | import { Borders, parseBorders } from "./border"; 3 | import { Length } from "./common"; 4 | 5 | export interface Column { 6 | space: Length; 7 | width: Length; 8 | } 9 | 10 | export interface Columns { 11 | space: Length; 12 | numberOfColumns: number; 13 | separator: boolean; 14 | equalWidth: boolean; 15 | columns: Column[]; 16 | } 17 | 18 | export interface PageSize { 19 | width: Length, 20 | height: Length, 21 | orientation: "landscape" | string 22 | } 23 | 24 | export interface PageNumber { 25 | start: number; 26 | chapSep: "colon" | "emDash" | "endash" | "hyphen" | "period" | string; 27 | chapStyle: string; 28 | format: "none" | "cardinalText" | "decimal" | "decimalEnclosedCircle" | "decimalEnclosedFullstop" 29 | | "decimalEnclosedParen" | "decimalZero" | "lowerLetter" | "lowerRoman" 30 | | "ordinalText" | "upperLetter" | "upperRoman" | string; 31 | } 32 | 33 | export interface PageMargins { 34 | top: Length; 35 | right: Length; 36 | bottom: Length; 37 | left: Length; 38 | header: Length; 39 | footer: Length; 40 | gutter: Length; 41 | } 42 | 43 | export enum SectionType { 44 | Continuous = "continuous", 45 | NextPage = "nextPage", 46 | NextColumn = "nextColumn", 47 | EvenPage = "evenPage", 48 | OddPage = "oddPage", 49 | } 50 | 51 | export interface FooterHeaderReference { 52 | id: string; 53 | type: string | "first" | "even" | "default"; 54 | } 55 | 56 | export interface SectionProperties { 57 | type: SectionType | string; 58 | pageSize: PageSize, 59 | pageMargins: PageMargins, 60 | pageBorders: Borders; 61 | pageNumber: PageNumber; 62 | columns: Columns; 63 | footerRefs: FooterHeaderReference[]; 64 | headerRefs: FooterHeaderReference[]; 65 | titlePage: boolean; 66 | } 67 | 68 | export function parseSectionProperties(elem: Element, xml: XmlParser = globalXmlParser): SectionProperties { 69 | var section = {}; 70 | 71 | for (let e of xml.elements(elem)) { 72 | switch (e.localName) { 73 | case "pgSz": 74 | section.pageSize = { 75 | width: xml.lengthAttr(e, "w"), 76 | height: xml.lengthAttr(e, "h"), 77 | orientation: xml.attr(e, "orient") 78 | } 79 | break; 80 | 81 | case "type": 82 | section.type = xml.attr(e, "val"); 83 | break; 84 | 85 | case "pgMar": 86 | section.pageMargins = { 87 | left: xml.lengthAttr(e, "left"), 88 | right: xml.lengthAttr(e, "right"), 89 | top: xml.lengthAttr(e, "top"), 90 | bottom: xml.lengthAttr(e, "bottom"), 91 | header: xml.lengthAttr(e, "header"), 92 | footer: xml.lengthAttr(e, "footer"), 93 | gutter: xml.lengthAttr(e, "gutter"), 94 | }; 95 | break; 96 | 97 | case "cols": 98 | section.columns = parseColumns(e, xml); 99 | break; 100 | 101 | case "headerReference": 102 | (section.headerRefs ?? (section.headerRefs = [])).push(parseFooterHeaderReference(e, xml)); 103 | break; 104 | 105 | case "footerReference": 106 | (section.footerRefs ?? (section.footerRefs = [])).push(parseFooterHeaderReference(e, xml)); 107 | break; 108 | 109 | case "titlePg": 110 | section.titlePage = xml.boolAttr(e, "val", true); 111 | break; 112 | 113 | case "pgBorders": 114 | section.pageBorders = parseBorders(e, xml); 115 | break; 116 | 117 | case "pgNumType": 118 | section.pageNumber = parsePageNumber(e, xml); 119 | break; 120 | } 121 | } 122 | 123 | return section; 124 | } 125 | 126 | function parseColumns(elem: Element, xml: XmlParser): Columns { 127 | return { 128 | numberOfColumns: xml.intAttr(elem, "num"), 129 | space: xml.lengthAttr(elem, "space"), 130 | separator: xml.boolAttr(elem, "sep"), 131 | equalWidth: xml.boolAttr(elem, "equalWidth", true), 132 | columns: xml.elements(elem, "col") 133 | .map(e => { 134 | width: xml.lengthAttr(e, "w"), 135 | space: xml.lengthAttr(e, "space") 136 | }) 137 | }; 138 | } 139 | 140 | function parsePageNumber(elem: Element, xml: XmlParser): PageNumber { 141 | return { 142 | chapSep: xml.attr(elem, "chapSep"), 143 | chapStyle: xml.attr(elem, "chapStyle"), 144 | format: xml.attr(elem, "fmt"), 145 | start: xml.intAttr(elem, "start") 146 | }; 147 | } 148 | 149 | function parseFooterHeaderReference(elem: Element, xml: XmlParser): FooterHeaderReference { 150 | return { 151 | id: xml.attr(elem, "id"), 152 | type: xml.attr(elem, "type"), 153 | } 154 | } -------------------------------------------------------------------------------- /src/document/style.ts: -------------------------------------------------------------------------------- 1 | import { ParagraphProperties } from "./paragraph"; 2 | import { RunProperties } from "./run"; 3 | 4 | export interface IDomStyle { 5 | id: string; 6 | name?: string; 7 | cssName?: string; 8 | aliases?: string[]; 9 | target: string; 10 | basedOn?: string; 11 | isDefault?: boolean; 12 | styles: IDomSubStyle[]; 13 | linked?: string; 14 | next?: string; 15 | 16 | paragraphProps: ParagraphProperties; 17 | runProps: RunProperties; 18 | } 19 | 20 | export interface IDomSubStyle { 21 | target: string; 22 | mod?: string; 23 | values: Record; 24 | } -------------------------------------------------------------------------------- /src/docx-preview.ts: -------------------------------------------------------------------------------- 1 | import { WordDocument } from './word-document'; 2 | import { DocumentParser } from './document-parser'; 3 | import { HtmlRenderer } from './html-renderer'; 4 | 5 | export interface Options { 6 | inWrapper: boolean; 7 | hideWrapperOnPrint: boolean; 8 | ignoreWidth: boolean; 9 | ignoreHeight: boolean; 10 | ignoreFonts: boolean; 11 | breakPages: boolean; 12 | debug: boolean; 13 | experimental: boolean; 14 | className: string; 15 | trimXmlDeclaration: boolean; 16 | renderHeaders: boolean; 17 | renderFooters: boolean; 18 | renderFootnotes: boolean; 19 | renderEndnotes: boolean; 20 | ignoreLastRenderedPageBreak: boolean; 21 | useBase64URL: boolean; 22 | renderChanges: boolean; 23 | renderComments: boolean; 24 | renderAltChunks: boolean; 25 | } 26 | 27 | export const defaultOptions: Options = { 28 | ignoreHeight: false, 29 | ignoreWidth: false, 30 | ignoreFonts: false, 31 | breakPages: true, 32 | debug: false, 33 | experimental: false, 34 | className: "docx", 35 | inWrapper: true, 36 | hideWrapperOnPrint: false, 37 | trimXmlDeclaration: true, 38 | ignoreLastRenderedPageBreak: true, 39 | renderHeaders: true, 40 | renderFooters: true, 41 | renderFootnotes: true, 42 | renderEndnotes: true, 43 | useBase64URL: false, 44 | renderChanges: false, 45 | renderComments: false, 46 | renderAltChunks: true 47 | } 48 | 49 | export function parseAsync(data: Blob | any, userOptions?: Partial): Promise { 50 | const ops = { ...defaultOptions, ...userOptions }; 51 | return WordDocument.load(data, new DocumentParser(ops), ops); 52 | } 53 | 54 | export async function renderDocument(document: any, bodyContainer: HTMLElement, styleContainer?: HTMLElement, userOptions?: Partial): Promise { 55 | const ops = { ...defaultOptions, ...userOptions }; 56 | const renderer = new HtmlRenderer(window.document); 57 | return await renderer.render(document, bodyContainer, styleContainer, ops); 58 | } 59 | 60 | export async function renderAsync(data: Blob | any, bodyContainer: HTMLElement, styleContainer?: HTMLElement, userOptions?: Partial): Promise { 61 | const doc = await parseAsync(data, userOptions); 62 | await renderDocument(doc, bodyContainer, styleContainer, userOptions); 63 | return doc; 64 | } -------------------------------------------------------------------------------- /src/font-table/font-table.ts: -------------------------------------------------------------------------------- 1 | import { Part } from "../common/part"; 2 | import { FontDeclaration, parseFonts } from "./fonts"; 3 | 4 | export class FontTablePart extends Part { 5 | fonts: FontDeclaration[]; 6 | 7 | parseXml(root: Element) { 8 | this.fonts = parseFonts(root, this._package.xmlParser); 9 | } 10 | } -------------------------------------------------------------------------------- /src/font-table/fonts.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | 3 | const embedFontTypeMap = { 4 | embedRegular: 'regular', 5 | embedBold: 'bold', 6 | embedItalic: 'italic', 7 | embedBoldItalic: 'boldItalic', 8 | } 9 | 10 | export interface FontDeclaration { 11 | name: string, 12 | altName: string, 13 | family: string, 14 | embedFontRefs: EmbedFontRef[]; 15 | } 16 | 17 | export interface EmbedFontRef { 18 | id: string; 19 | key: string; 20 | type: 'regular' | 'bold' | 'italic' | 'boldItalic'; 21 | } 22 | 23 | export function parseFonts(root: Element, xml: XmlParser): FontDeclaration[] { 24 | return xml.elements(root).map(el => parseFont(el, xml)); 25 | } 26 | 27 | export function parseFont(elem: Element, xml: XmlParser): FontDeclaration { 28 | let result = { 29 | name: xml.attr(elem, "name"), 30 | embedFontRefs: [] 31 | }; 32 | 33 | for (let el of xml.elements(elem)) { 34 | switch (el.localName) { 35 | case "family": 36 | result.family = xml.attr(el, "val"); 37 | break; 38 | 39 | case "altName": 40 | result.altName = xml.attr(el, "val"); 41 | break; 42 | 43 | case "embedRegular": 44 | case "embedBold": 45 | case "embedItalic": 46 | case "embedBoldItalic": 47 | result.embedFontRefs.push(parseEmbedFontRef(el, xml)); 48 | break; 49 | } 50 | } 51 | 52 | return result; 53 | } 54 | 55 | export function parseEmbedFontRef(elem: Element, xml: XmlParser): EmbedFontRef { 56 | return { 57 | id: xml.attr(elem, "id"), 58 | key: xml.attr(elem, "fontKey"), 59 | type: embedFontTypeMap[elem.localName] 60 | }; 61 | } -------------------------------------------------------------------------------- /src/header-footer/elements.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlElementBase, DomType } from "../document/dom"; 2 | 3 | export class WmlHeader extends OpenXmlElementBase { 4 | type: DomType = DomType.Header; 5 | } 6 | 7 | export class WmlFooter extends OpenXmlElementBase { 8 | type: DomType = DomType.Footer; 9 | } -------------------------------------------------------------------------------- /src/header-footer/parts.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlPackage } from "../common/open-xml-package"; 2 | import { Part } from "../common/part"; 3 | import { DocumentParser } from "../document-parser"; 4 | import { OpenXmlElement } from "../document/dom"; 5 | import { WmlHeader, WmlFooter } from "./elements"; 6 | 7 | export abstract class BaseHeaderFooterPart extends Part { 8 | rootElement: T; 9 | 10 | private _documentParser: DocumentParser; 11 | 12 | constructor(pkg: OpenXmlPackage, path: string, parser: DocumentParser) { 13 | super(pkg, path); 14 | this._documentParser = parser; 15 | } 16 | 17 | parseXml(root: Element) { 18 | this.rootElement = this.createRootElement(); 19 | this.rootElement.children = this._documentParser.parseBodyElements(root); 20 | } 21 | 22 | protected abstract createRootElement(): T; 23 | } 24 | 25 | export class HeaderPart extends BaseHeaderFooterPart { 26 | protected createRootElement(): WmlHeader { 27 | return new WmlHeader(); 28 | } 29 | } 30 | 31 | export class FooterPart extends BaseHeaderFooterPart { 32 | protected createRootElement(): WmlFooter { 33 | return new WmlFooter(); 34 | } 35 | } -------------------------------------------------------------------------------- /src/javascript.ts: -------------------------------------------------------------------------------- 1 | import { Length } from "./document/common"; 2 | import { ParagraphTab } from "./document/paragraph"; 3 | 4 | interface TabStop { 5 | pos: number; 6 | leader: string; 7 | style: string; 8 | } 9 | 10 | const defaultTab: TabStop = { pos: 0, leader: "none", style: "left" }; 11 | const maxTabs = 50; 12 | 13 | export function computePixelToPoint(container: HTMLElement = document.body) { 14 | const temp = document.createElement("div"); 15 | temp.style.width = '100pt'; 16 | 17 | container.appendChild(temp); 18 | const result = 100 / temp.offsetWidth; 19 | container.removeChild(temp); 20 | 21 | return result 22 | } 23 | 24 | export function updateTabStop(elem: HTMLElement, tabs: ParagraphTab[], defaultTabSize: Length, pixelToPoint: number = 72 / 96) { 25 | const p = elem.closest("p"); 26 | 27 | const ebb = elem.getBoundingClientRect(); 28 | const pbb = p.getBoundingClientRect(); 29 | const pcs = getComputedStyle(p); 30 | 31 | const tabStops = tabs?.length > 0 ? tabs.map(t => ({ 32 | pos: lengthToPoint(t.position), 33 | leader: t.leader, 34 | style: t.style 35 | })).sort((a, b) => a.pos - b.pos) : [defaultTab]; 36 | 37 | const lastTab = tabStops[tabStops.length - 1]; 38 | const pWidthPt = pbb.width * pixelToPoint; 39 | const size = lengthToPoint(defaultTabSize); 40 | let pos = lastTab.pos + size; 41 | 42 | if (pos < pWidthPt) { 43 | for (; pos < pWidthPt && tabStops.length < maxTabs; pos += size) { 44 | tabStops.push({ ...defaultTab, pos: pos }); 45 | } 46 | } 47 | 48 | const marginLeft = parseFloat(pcs.marginLeft); 49 | const pOffset = pbb.left + marginLeft; 50 | const left = (ebb.left - pOffset) * pixelToPoint; 51 | const tab = tabStops.find(t => t.style != "clear" && t.pos > left); 52 | 53 | if(tab == null) 54 | return; 55 | 56 | let width: number = 1; 57 | 58 | if (tab.style == "right" || tab.style == "center") { 59 | const tabStops = Array.from(p.querySelectorAll(`.${elem.className}`)); 60 | const nextIdx = tabStops.indexOf(elem) + 1; 61 | const range = document.createRange(); 62 | range.setStart(elem, 1); 63 | 64 | if (nextIdx < tabStops.length) { 65 | range.setEndBefore(tabStops[nextIdx]); 66 | } else { 67 | range.setEndAfter(p); 68 | } 69 | 70 | const mul = tab.style == "center" ? 0.5 : 1; 71 | const nextBB = range.getBoundingClientRect(); 72 | const offset = nextBB.left + mul * nextBB.width - (pbb.left - marginLeft); 73 | 74 | width = tab.pos - offset * pixelToPoint; 75 | } else { 76 | width = tab.pos - left; 77 | } 78 | 79 | elem.innerHTML = " "; 80 | elem.style.textDecoration = "inherit"; 81 | elem.style.wordSpacing = `${width.toFixed(0)}pt`; 82 | 83 | switch (tab.leader) { 84 | case "dot": 85 | case "middleDot": 86 | elem.style.textDecoration = "underline"; 87 | elem.style.textDecorationStyle = "dotted"; 88 | break; 89 | 90 | case "hyphen": 91 | case "heavy": 92 | case "underscore": 93 | elem.style.textDecoration = "underline"; 94 | break; 95 | } 96 | } 97 | 98 | function lengthToPoint(length: Length): number { 99 | return parseFloat(length); 100 | } -------------------------------------------------------------------------------- /src/length.ts: -------------------------------------------------------------------------------- 1 | import { isString } from "./utils"; 2 | 3 | export class Length { 4 | constructor(readonly value: number, readonly type?: string) {} 5 | 6 | static parse(text: string): Length { 7 | const value = parseFloat(text); 8 | const type = /p[tx]$/i.exec(text)?.[0]; 9 | return new Length(value, type); 10 | } 11 | 12 | static from(val: any): Length { 13 | if (isString(val)) return Length.parse(val); 14 | if (val instanceof Length) return val; 15 | 16 | return null; 17 | } 18 | 19 | add(length: Length): Length { 20 | if (length.type !== this.type) 21 | throw new Error("Can't do math on different types"); 22 | 23 | return new Length(this.value + length.value, this.type); 24 | } 25 | 26 | mul(val: number): Length { 27 | return new Length(this.value * val, this.type); 28 | } 29 | 30 | valueOf() { 31 | return this.value; 32 | } 33 | 34 | toString(): string { 35 | return `${this.value.toFixed(2)}${this.type ?? ''}`; 36 | } 37 | } -------------------------------------------------------------------------------- /src/notes/elements.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlElementBase, DomType } from "../document/dom"; 2 | 3 | export abstract class WmlBaseNote implements OpenXmlElementBase { 4 | type: DomType; 5 | id: string; 6 | noteType: string; 7 | } 8 | 9 | export class WmlFootnote extends WmlBaseNote { 10 | type = DomType.Footnote 11 | } 12 | 13 | export class WmlEndnote extends WmlBaseNote { 14 | type = DomType.Endnote 15 | } -------------------------------------------------------------------------------- /src/notes/parts.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlPackage } from "../common/open-xml-package"; 2 | import { Part } from "../common/part"; 3 | import { DocumentParser } from "../document-parser"; 4 | import { WmlBaseNote, WmlEndnote, WmlFootnote } from "./elements"; 5 | 6 | export class BaseNotePart extends Part { 7 | protected _documentParser: DocumentParser; 8 | 9 | notes: T[] 10 | 11 | constructor(pkg: OpenXmlPackage, path: string, parser: DocumentParser) { 12 | super(pkg, path); 13 | this._documentParser = parser; 14 | } 15 | } 16 | 17 | export class FootnotesPart extends BaseNotePart { 18 | constructor(pkg: OpenXmlPackage, path: string, parser: DocumentParser) { 19 | super(pkg, path, parser); 20 | } 21 | 22 | parseXml(root: Element) { 23 | this.notes = this._documentParser.parseNotes(root, "footnote", WmlFootnote); 24 | } 25 | } 26 | 27 | export class EndnotesPart extends BaseNotePart { 28 | constructor(pkg: OpenXmlPackage, path: string, parser: DocumentParser) { 29 | super(pkg, path, parser); 30 | } 31 | 32 | parseXml(root: Element) { 33 | this.notes = this._documentParser.parseNotes(root, "endnote", WmlEndnote); 34 | } 35 | } -------------------------------------------------------------------------------- /src/numbering/numbering-part.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlPackage } from "../common/open-xml-package"; 2 | import { Part } from "../common/part"; 3 | import { DocumentParser } from "../document-parser"; 4 | import { IDomNumbering } from "../document/dom"; 5 | import { AbstractNumbering, Numbering, NumberingBulletPicture, NumberingPartProperties, parseNumberingPart } from "./numbering"; 6 | 7 | export class NumberingPart extends Part implements NumberingPartProperties { 8 | private _documentParser: DocumentParser; 9 | 10 | constructor(pkg: OpenXmlPackage, path: string, parser: DocumentParser) { 11 | super(pkg, path); 12 | this._documentParser = parser; 13 | } 14 | 15 | numberings: Numbering[]; 16 | abstractNumberings: AbstractNumbering[]; 17 | bulletPictures: NumberingBulletPicture[]; 18 | 19 | domNumberings: IDomNumbering[]; 20 | 21 | parseXml(root: Element) { 22 | Object.assign(this, parseNumberingPart(root, this._package.xmlParser)); 23 | this.domNumberings = this._documentParser.parseNumberingFile(root); 24 | } 25 | } -------------------------------------------------------------------------------- /src/numbering/numbering.ts: -------------------------------------------------------------------------------- 1 | import { NumberingPicBullet } from "../document/dom"; 2 | import { ParagraphProperties, parseParagraphProperties } from "../document/paragraph"; 3 | import { parseRunProperties, RunProperties } from "../document/run"; 4 | import { XmlParser } from "../parser/xml-parser"; 5 | 6 | export interface NumberingPartProperties { 7 | numberings: Numbering[]; 8 | abstractNumberings: AbstractNumbering[]; 9 | bulletPictures: NumberingBulletPicture[]; 10 | } 11 | 12 | export interface Numbering { 13 | id: string; 14 | abstractId: string; 15 | overrides: NumberingLevelOverride[]; 16 | } 17 | 18 | export interface NumberingLevelOverride { 19 | level: number; 20 | start: number; 21 | numberingLevel: NumberingLevel; 22 | } 23 | 24 | export interface AbstractNumbering { 25 | id: string; 26 | name: string; 27 | multiLevelType: "singleLevel" | "multiLevel" | "hybridMultilevel" | string; 28 | levels: NumberingLevel[]; 29 | numberingStyleLink: string; 30 | styleLink: string; 31 | } 32 | 33 | export interface NumberingLevel { 34 | level: number; 35 | start: string; 36 | restart: number; 37 | format: 'lowerRoman' | 'lowerLetter' | string; 38 | text: string; 39 | justification: string; 40 | bulletPictureId: string; 41 | paragraphStyle: string; 42 | paragraphProps: ParagraphProperties; 43 | runProps: RunProperties; 44 | } 45 | 46 | export interface NumberingBulletPicture { 47 | id: string; 48 | referenceId: string; 49 | style: string; 50 | } 51 | 52 | export function parseNumberingPart(elem: Element, xml: XmlParser): NumberingPartProperties { 53 | let result: NumberingPartProperties = { 54 | numberings: [], 55 | abstractNumberings: [], 56 | bulletPictures: [] 57 | } 58 | 59 | for (let e of xml.elements(elem)) { 60 | switch (e.localName) { 61 | case "num": 62 | result.numberings.push(parseNumbering(e, xml)); 63 | break; 64 | case "abstractNum": 65 | result.abstractNumberings.push(parseAbstractNumbering(e, xml)); 66 | break; 67 | case "numPicBullet": 68 | result.bulletPictures.push(parseNumberingBulletPicture(e, xml)); 69 | break; 70 | } 71 | } 72 | 73 | return result; 74 | } 75 | 76 | export function parseNumbering(elem: Element, xml: XmlParser): Numbering { 77 | let result = { 78 | id: xml.attr(elem, 'numId'), 79 | overrides: [] 80 | }; 81 | 82 | for (let e of xml.elements(elem)) { 83 | switch (e.localName) { 84 | case "abstractNumId": 85 | result.abstractId = xml.attr(e, "val"); 86 | break; 87 | case "lvlOverride": 88 | result.overrides.push(parseNumberingLevelOverrride(e, xml)); 89 | break; 90 | } 91 | } 92 | 93 | return result; 94 | } 95 | 96 | export function parseAbstractNumbering(elem: Element, xml: XmlParser): AbstractNumbering { 97 | let result = { 98 | id: xml.attr(elem, 'abstractNumId'), 99 | levels: [] 100 | }; 101 | 102 | for (let e of xml.elements(elem)) { 103 | switch (e.localName) { 104 | case "name": 105 | result.name = xml.attr(e, "val"); 106 | break; 107 | case "multiLevelType": 108 | result.multiLevelType = xml.attr(e, "val"); 109 | break; 110 | case "numStyleLink": 111 | result.numberingStyleLink = xml.attr(e, "val"); 112 | break; 113 | case "styleLink": 114 | result.styleLink = xml.attr(e, "val"); 115 | break; 116 | case "lvl": 117 | result.levels.push(parseNumberingLevel(e, xml)); 118 | break; 119 | } 120 | } 121 | 122 | return result; 123 | } 124 | 125 | export function parseNumberingLevel(elem: Element, xml: XmlParser): NumberingLevel { 126 | let result = { 127 | level: xml.intAttr(elem, 'ilvl') 128 | }; 129 | 130 | for (let e of xml.elements(elem)) { 131 | switch (e.localName) { 132 | case "start": 133 | result.start = xml.attr(e, "val"); 134 | break; 135 | case "lvlRestart": 136 | result.restart = xml.intAttr(e, "val"); 137 | break; 138 | case "numFmt": 139 | result.format = xml.attr(e, "val"); 140 | break; 141 | case "lvlText": 142 | result.text = xml.attr(e, "val"); 143 | break; 144 | case "lvlJc": 145 | result.justification = xml.attr(e, "val"); 146 | break; 147 | case "lvlPicBulletId": 148 | result.bulletPictureId = xml.attr(e, "val"); 149 | break; 150 | case "pStyle": 151 | result.paragraphStyle = xml.attr(e, "val"); 152 | break; 153 | case "pPr": 154 | result.paragraphProps = parseParagraphProperties(e, xml); 155 | break; 156 | case "rPr": 157 | result.runProps = parseRunProperties(e, xml); 158 | break; 159 | } 160 | } 161 | 162 | return result; 163 | } 164 | 165 | export function parseNumberingLevelOverrride(elem: Element, xml: XmlParser): NumberingLevelOverride { 166 | let result = { 167 | level: xml.intAttr(elem, 'ilvl') 168 | }; 169 | 170 | for (let e of xml.elements(elem)) { 171 | switch (e.localName) { 172 | case "startOverride": 173 | result.start = xml.intAttr(e, "val"); 174 | break; 175 | case "lvl": 176 | result.numberingLevel = parseNumberingLevel(e, xml); 177 | break; 178 | } 179 | } 180 | 181 | return result; 182 | } 183 | 184 | export function parseNumberingBulletPicture(elem: Element, xml: XmlParser): NumberingBulletPicture { 185 | //TODO 186 | var pict = xml.element(elem, "pict"); 187 | var shape = pict && xml.element(pict, "shape"); 188 | var imagedata = shape && xml.element(shape, "imagedata"); 189 | 190 | return imagedata ? { 191 | id: xml.attr(elem, "numPicBulletId"), 192 | referenceId: xml.attr(imagedata, "id"), 193 | style: xml.attr(shape, "style") 194 | } : null; 195 | } -------------------------------------------------------------------------------- /src/parser/xml-parser.ts: -------------------------------------------------------------------------------- 1 | import { Length, LengthUsage, LengthUsageType, convertLength, convertBoolean } from "../document/common"; 2 | 3 | export function parseXmlString(xmlString: string, trimXmlDeclaration: boolean = false): Document { 4 | if (trimXmlDeclaration) 5 | xmlString = xmlString.replace(/<[?].*[?]>/, ""); 6 | 7 | xmlString = removeUTF8BOM(xmlString); 8 | 9 | const result = new DOMParser().parseFromString(xmlString, "application/xml"); 10 | const errorText = hasXmlParserError(result); 11 | 12 | if (errorText) 13 | throw new Error(errorText); 14 | 15 | return result; 16 | } 17 | 18 | function hasXmlParserError(doc: Document) { 19 | return doc.getElementsByTagName("parsererror")[0]?.textContent; 20 | } 21 | 22 | function removeUTF8BOM(data: string) { 23 | return data.charCodeAt(0) === 0xFEFF ? data.substring(1) : data; 24 | } 25 | 26 | export function serializeXmlString(elem: Node): string { 27 | return new XMLSerializer().serializeToString(elem); 28 | } 29 | 30 | export class XmlParser { 31 | elements(elem: Element, localName: string = null): Element[] { 32 | const result = []; 33 | 34 | for (let i = 0, l = elem.childNodes.length; i < l; i++) { 35 | let c = elem.childNodes.item(i); 36 | 37 | if (c.nodeType == 1 && (localName == null || (c as Element).localName == localName)) 38 | result.push(c); 39 | } 40 | 41 | return result; 42 | } 43 | 44 | element(elem: Element, localName: string): Element { 45 | for (let i = 0, l = elem.childNodes.length; i < l; i++) { 46 | let c = elem.childNodes.item(i); 47 | 48 | if (c.nodeType == 1 && (c as Element).localName == localName) 49 | return c as Element; 50 | } 51 | 52 | return null; 53 | } 54 | 55 | elementAttr(elem: Element, localName: string, attrLocalName: string): string { 56 | var el = this.element(elem, localName); 57 | return el ? this.attr(el, attrLocalName) : undefined; 58 | } 59 | 60 | attrs(elem: Element) { 61 | return Array.from(elem.attributes); 62 | } 63 | 64 | attr(elem: Element, localName: string): string { 65 | for (let i = 0, l = elem.attributes.length; i < l; i++) { 66 | let a = elem.attributes.item(i); 67 | 68 | if (a.localName == localName) 69 | return a.value; 70 | } 71 | 72 | return null; 73 | } 74 | 75 | intAttr(node: Element, attrName: string, defaultValue: number = null): number { 76 | var val = this.attr(node, attrName); 77 | return val ? parseInt(val) : defaultValue; 78 | } 79 | 80 | hexAttr(node: Element, attrName: string, defaultValue: number = null): number { 81 | var val = this.attr(node, attrName); 82 | return val ? parseInt(val, 16) : defaultValue; 83 | } 84 | 85 | floatAttr(node: Element, attrName: string, defaultValue: number = null): number { 86 | var val = this.attr(node, attrName); 87 | return val ? parseFloat(val) : defaultValue; 88 | } 89 | 90 | boolAttr(node: Element, attrName: string, defaultValue: boolean = null) { 91 | return convertBoolean(this.attr(node, attrName), defaultValue); 92 | } 93 | 94 | lengthAttr(node: Element, attrName: string, usage: LengthUsageType = LengthUsage.Dxa): Length { 95 | return convertLength(this.attr(node, attrName), usage); 96 | } 97 | } 98 | 99 | const globalXmlParser = new XmlParser(); 100 | 101 | export default globalXmlParser; -------------------------------------------------------------------------------- /src/settings/settings-part.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlPackage } from "../common/open-xml-package"; 2 | import { Part } from "../common/part"; 3 | import { WmlSettings, parseSettings } from "./settings"; 4 | 5 | export class SettingsPart extends Part { 6 | settings: WmlSettings; 7 | 8 | constructor(pkg: OpenXmlPackage, path: string) { 9 | super(pkg, path); 10 | } 11 | 12 | parseXml(root: Element) { 13 | this.settings = parseSettings(root, this._package.xmlParser); 14 | } 15 | } -------------------------------------------------------------------------------- /src/settings/settings.ts: -------------------------------------------------------------------------------- 1 | import { DocumentParser } from "../document-parser"; 2 | import { Length } from "../document/common"; 3 | import { XmlParser } from "../parser/xml-parser"; 4 | 5 | export interface WmlSettings { 6 | defaultTabStop: Length; 7 | footnoteProps: NoteProperties; 8 | endnoteProps: NoteProperties; 9 | autoHyphenation: boolean; 10 | } 11 | 12 | export interface NoteProperties { 13 | nummeringFormat: string; 14 | defaultNoteIds: string[]; 15 | } 16 | 17 | export function parseSettings(elem: Element, xml: XmlParser) { 18 | var result = {} as WmlSettings; 19 | 20 | for (let el of xml.elements(elem)) { 21 | switch(el.localName) { 22 | case "defaultTabStop": result.defaultTabStop = xml.lengthAttr(el, "val"); break; 23 | case "footnotePr": result.footnoteProps = parseNoteProperties(el, xml); break; 24 | case "endnotePr": result.endnoteProps = parseNoteProperties(el, xml); break; 25 | case "autoHyphenation": result.autoHyphenation = xml.boolAttr(el, "val"); break; 26 | } 27 | } 28 | 29 | return result; 30 | } 31 | 32 | export function parseNoteProperties(elem: Element, xml: XmlParser) { 33 | var result = { 34 | defaultNoteIds: [] 35 | } as NoteProperties; 36 | 37 | for (let el of xml.elements(elem)) { 38 | switch(el.localName) { 39 | case "numFmt": 40 | result.nummeringFormat = xml.attr(el, "val"); 41 | break; 42 | 43 | case "footnote": 44 | case "endnote": 45 | result.defaultNoteIds.push(xml.attr(el, "id")); 46 | break; 47 | } 48 | } 49 | 50 | return result; 51 | } -------------------------------------------------------------------------------- /src/styles/styles-part.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlPackage } from "../common/open-xml-package"; 2 | import { Part } from "../common/part"; 3 | import { DocumentParser } from "../document-parser"; 4 | import { IDomStyle } from "../document/style"; 5 | 6 | export class StylesPart extends Part { 7 | styles: IDomStyle[]; 8 | 9 | private _documentParser: DocumentParser; 10 | 11 | constructor(pkg: OpenXmlPackage, path: string, parser: DocumentParser) { 12 | super(pkg, path); 13 | this._documentParser = parser; 14 | } 15 | 16 | parseXml(root: Element) { 17 | this.styles = this._documentParser.parseStylesFile(root); 18 | } 19 | } -------------------------------------------------------------------------------- /src/theme/theme-part.ts: -------------------------------------------------------------------------------- 1 | import { OpenXmlPackage } from "../common/open-xml-package"; 2 | import { Part } from "../common/part"; 3 | import { DmlTheme, parseTheme } from "./theme"; 4 | 5 | export class ThemePart extends Part { 6 | theme: DmlTheme; 7 | 8 | constructor(pkg: OpenXmlPackage, path: string) { 9 | super(pkg, path); 10 | } 11 | 12 | parseXml(root: Element) { 13 | this.theme = parseTheme(root, this._package.xmlParser); 14 | } 15 | } -------------------------------------------------------------------------------- /src/theme/theme.ts: -------------------------------------------------------------------------------- 1 | import { XmlParser } from "../parser/xml-parser"; 2 | 3 | export class DmlTheme { 4 | colorScheme: DmlColorScheme; 5 | fontScheme: DmlFontScheme; 6 | } 7 | 8 | export interface DmlColorScheme { 9 | name: string; 10 | colors: Record; 11 | } 12 | 13 | export interface DmlFontScheme { 14 | name: string; 15 | majorFont: DmlFormInfo, 16 | minorFont: DmlFormInfo 17 | } 18 | 19 | export interface DmlFormInfo { 20 | latinTypeface: string; 21 | eaTypeface: string; 22 | csTypeface: string; 23 | } 24 | 25 | export function parseTheme(elem: Element, xml: XmlParser) { 26 | var result = new DmlTheme(); 27 | var themeElements = xml.element(elem, "themeElements"); 28 | 29 | for (let el of xml.elements(themeElements)) { 30 | switch(el.localName) { 31 | case "clrScheme": result.colorScheme = parseColorScheme(el, xml); break; 32 | case "fontScheme": result.fontScheme = parseFontScheme(el, xml); break; 33 | } 34 | } 35 | 36 | return result; 37 | } 38 | 39 | export function parseColorScheme(elem: Element, xml: XmlParser) { 40 | var result: DmlColorScheme = { 41 | name: xml.attr(elem, "name"), 42 | colors: {} 43 | }; 44 | 45 | for (let el of xml.elements(elem)) { 46 | var srgbClr = xml.element(el, "srgbClr"); 47 | var sysClr = xml.element(el, "sysClr"); 48 | 49 | if (srgbClr) { 50 | result.colors[el.localName] = xml.attr(srgbClr, "val"); 51 | } 52 | else if (sysClr) { 53 | result.colors[el.localName] = xml.attr(sysClr, "lastClr"); 54 | } 55 | } 56 | 57 | return result; 58 | } 59 | 60 | export function parseFontScheme(elem: Element, xml: XmlParser) { 61 | var result: DmlFontScheme = { 62 | name: xml.attr(elem, "name"), 63 | } as DmlFontScheme; 64 | 65 | for (let el of xml.elements(elem)) { 66 | switch (el.localName) { 67 | case "majorFont": result.majorFont = parseFontInfo(el, xml); break; 68 | case "minorFont": result.minorFont = parseFontInfo(el, xml); break; 69 | } 70 | } 71 | 72 | return result; 73 | } 74 | 75 | export function parseFontInfo(elem: Element, xml: XmlParser): DmlFormInfo { 76 | return { 77 | latinTypeface: xml.elementAttr(elem, "latin", "typeface"), 78 | eaTypeface: xml.elementAttr(elem, "ea", "typeface"), 79 | csTypeface: xml.elementAttr(elem, "cs", "typeface"), 80 | }; 81 | } -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | declare module'*.scss'; -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | export function escapeClassName(className: string) { 2 | return className?.replace(/[ .]+/g, '-').replace(/[&]+/g, 'and').toLowerCase(); 3 | } 4 | 5 | export function encloseFontFamily(fontFamily: string): string { 6 | return /^[^"'].*\s.*[^"']$/.test(fontFamily) ? `'${fontFamily}'` : fontFamily; 7 | } 8 | 9 | export function splitPath(path: string): [string, string] { 10 | let si = path.lastIndexOf('/') + 1; 11 | let folder = si == 0 ? "" : path.substring(0, si); 12 | let fileName = si == 0 ? path : path.substring(si); 13 | 14 | return [folder, fileName]; 15 | } 16 | 17 | export function resolvePath(path: string, base: string): string { 18 | try { 19 | const prefix = "http://docx/"; 20 | const url = new URL(path, prefix + base).toString(); 21 | return url.substring(prefix.length); 22 | } catch { 23 | return `${base}${path}`; 24 | } 25 | } 26 | 27 | export function keyBy(array: T[], by: (x: T) => any): Record { 28 | return array.reduce((a, x) => { 29 | a[by(x)] = x; 30 | return a; 31 | }, {}); 32 | } 33 | 34 | export function blobToBase64(blob: Blob): Promise { 35 | return new Promise((resolve, reject) => { 36 | const reader = new FileReader(); 37 | reader.onloadend = () => resolve(reader.result as string); 38 | reader.onerror = () => reject(); 39 | reader.readAsDataURL(blob); 40 | }); 41 | } 42 | 43 | export function isObject(item) { 44 | return item && typeof item === 'object' && !Array.isArray(item); 45 | } 46 | 47 | export function isString(item: unknown): item is string { 48 | return typeof item === 'string' || item instanceof String; 49 | } 50 | 51 | export function mergeDeep(target, ...sources) { 52 | if (!sources.length) 53 | return target; 54 | 55 | const source = sources.shift(); 56 | 57 | if (isObject(target) && isObject(source)) { 58 | for (const key in source) { 59 | if (isObject(source[key])) { 60 | const val = target[key] ?? (target[key] = {}); 61 | mergeDeep(val, source[key]); 62 | } else { 63 | target[key] = source[key]; 64 | } 65 | } 66 | } 67 | 68 | return mergeDeep(target, ...sources); 69 | } 70 | 71 | export function parseCssRules(text: string): Record { 72 | const result: Record = {}; 73 | 74 | for (const rule of text.split(';')) { 75 | const [key, val] = rule.split(':'); 76 | result[key] = val; 77 | } 78 | 79 | return result 80 | } 81 | 82 | export function formatCssRules(style: Record): string { 83 | return Object.entries(style).map((k, v) => `${k}: ${v}`).join(';'); 84 | } 85 | 86 | export function asArray(val: T | T[]): T[] { 87 | return Array.isArray(val) ? val : [val]; 88 | } 89 | 90 | export function clamp(val, min, max) { 91 | return min > val ? min : (max < val ? max : val); 92 | } -------------------------------------------------------------------------------- /src/vml/vml.ts: -------------------------------------------------------------------------------- 1 | import { DocumentParser } from '../document-parser'; 2 | import { convertLength, LengthUsage } from '../document/common'; 3 | import { OpenXmlElementBase, DomType } from '../document/dom'; 4 | import xml from '../parser/xml-parser'; 5 | import { formatCssRules, parseCssRules } from '../utils'; 6 | 7 | export class VmlElement extends OpenXmlElementBase { 8 | type: DomType = DomType.VmlElement; 9 | tagName: string; 10 | cssStyleText?: string; 11 | attrs: Record = {}; 12 | wrapType?: string; 13 | imageHref?: { 14 | id: string, 15 | title: string 16 | } 17 | } 18 | 19 | export function parseVmlElement(elem: Element, parser: DocumentParser): VmlElement { 20 | var result = new VmlElement(); 21 | 22 | switch (elem.localName) { 23 | case "rect": 24 | result.tagName = "rect"; 25 | Object.assign(result.attrs, { width: '100%', height: '100%' }); 26 | break; 27 | 28 | case "oval": 29 | result.tagName = "ellipse"; 30 | Object.assign(result.attrs, { cx: "50%", cy: "50%", rx: "50%", ry: "50%" }); 31 | break; 32 | 33 | case "line": 34 | result.tagName = "line"; 35 | break; 36 | 37 | case "shape": 38 | result.tagName = "g"; 39 | break; 40 | 41 | case "textbox": 42 | result.tagName = "foreignObject"; 43 | Object.assign(result.attrs, { width: '100%', height: '100%' }); 44 | break; 45 | 46 | default: 47 | return null; 48 | } 49 | 50 | for (const at of xml.attrs(elem)) { 51 | switch(at.localName) { 52 | case "style": 53 | result.cssStyleText = at.value; 54 | break; 55 | 56 | case "fillcolor": 57 | result.attrs.fill = at.value; 58 | break; 59 | 60 | case "from": 61 | const [x1, y1] = parsePoint(at.value); 62 | Object.assign(result.attrs, { x1, y1 }); 63 | break; 64 | 65 | case "to": 66 | const [x2, y2] = parsePoint(at.value); 67 | Object.assign(result.attrs, { x2, y2 }); 68 | break; 69 | } 70 | } 71 | 72 | for (const el of xml.elements(elem)) { 73 | switch (el.localName) { 74 | case "stroke": 75 | Object.assign(result.attrs, parseStroke(el)); 76 | break; 77 | 78 | case "fill": 79 | Object.assign(result.attrs, parseFill(el)); 80 | break; 81 | 82 | case "imagedata": 83 | result.tagName = "image"; 84 | Object.assign(result.attrs, { width: '100%', height: '100%' }); 85 | result.imageHref = { 86 | id: xml.attr(el, "id"), 87 | title: xml.attr(el, "title"), 88 | } 89 | break; 90 | 91 | case "txbxContent": 92 | result.children.push(...parser.parseBodyElements(el)); 93 | break; 94 | 95 | default: 96 | const child = parseVmlElement(el, parser); 97 | child && result.children.push(child); 98 | break; 99 | } 100 | } 101 | 102 | return result; 103 | } 104 | 105 | function parseStroke(el: Element): Record { 106 | return { 107 | 'stroke': xml.attr(el, "color"), 108 | 'stroke-width': xml.lengthAttr(el, "weight", LengthUsage.Emu) ?? '1px' 109 | }; 110 | } 111 | 112 | function parseFill(el: Element): Record { 113 | return { 114 | //'fill': xml.attr(el, "color2") 115 | }; 116 | } 117 | 118 | function parsePoint(val: string): string[] { 119 | return val.split(","); 120 | } 121 | 122 | function convertPath(path: string): string { 123 | return path.replace(/([mlxe])|([-\d]+)|([,])/g, (m) => { 124 | if (/[-\d]/.test(m)) return convertLength(m, LengthUsage.VmlEmu); 125 | if (/[ml,]/.test(m)) return m; 126 | 127 | return ''; 128 | }); 129 | } -------------------------------------------------------------------------------- /src/word-document.ts: -------------------------------------------------------------------------------- 1 | import { OutputType } from "jszip"; 2 | 3 | import { DocumentParser } from './document-parser'; 4 | import { Relationship, RelationshipTypes } from './common/relationship'; 5 | import { Part } from './common/part'; 6 | import { FontTablePart } from './font-table/font-table'; 7 | import { OpenXmlPackage } from './common/open-xml-package'; 8 | import { DocumentPart } from './document/document-part'; 9 | import { blobToBase64, resolvePath, splitPath } from './utils'; 10 | import { NumberingPart } from './numbering/numbering-part'; 11 | import { StylesPart } from './styles/styles-part'; 12 | import { FooterPart, HeaderPart } from "./header-footer/parts"; 13 | import { ExtendedPropsPart } from "./document-props/extended-props-part"; 14 | import { CorePropsPart } from "./document-props/core-props-part"; 15 | import { ThemePart } from "./theme/theme-part"; 16 | import { EndnotesPart, FootnotesPart } from "./notes/parts"; 17 | import { SettingsPart } from "./settings/settings-part"; 18 | import { CustomPropsPart } from "./document-props/custom-props-part"; 19 | import { CommentsPart } from "./comments/comments-part"; 20 | import { CommentsExtendedPart } from "./comments/comments-extended-part"; 21 | 22 | const topLevelRels = [ 23 | { type: RelationshipTypes.OfficeDocument, target: "word/document.xml" }, 24 | { type: RelationshipTypes.ExtendedProperties, target: "docProps/app.xml" }, 25 | { type: RelationshipTypes.CoreProperties, target: "docProps/core.xml" }, 26 | { type: RelationshipTypes.CustomProperties, target: "docProps/custom.xml" }, 27 | ]; 28 | 29 | export class WordDocument { 30 | private _package: OpenXmlPackage; 31 | private _parser: DocumentParser; 32 | private _options: any; 33 | 34 | rels: Relationship[]; 35 | parts: Part[] = []; 36 | partsMap: Record = {}; 37 | 38 | documentPart: DocumentPart; 39 | fontTablePart: FontTablePart; 40 | numberingPart: NumberingPart; 41 | stylesPart: StylesPart; 42 | footnotesPart: FootnotesPart; 43 | endnotesPart: EndnotesPart; 44 | themePart: ThemePart; 45 | corePropsPart: CorePropsPart; 46 | extendedPropsPart: ExtendedPropsPart; 47 | settingsPart: SettingsPart; 48 | commentsPart: CommentsPart; 49 | commentsExtendedPart: CommentsExtendedPart; 50 | 51 | static async load(blob: Blob | any, parser: DocumentParser, options: any): Promise { 52 | var d = new WordDocument(); 53 | 54 | d._options = options; 55 | d._parser = parser; 56 | d._package = await OpenXmlPackage.load(blob, options); 57 | d.rels = await d._package.loadRelationships(); 58 | 59 | await Promise.all(topLevelRels.map(rel => { 60 | const r = d.rels.find(x => x.type === rel.type) ?? rel; //fallback 61 | return d.loadRelationshipPart(r.target, r.type); 62 | })); 63 | 64 | return d; 65 | } 66 | 67 | save(type = "blob"): Promise { 68 | return this._package.save(type); 69 | } 70 | 71 | private async loadRelationshipPart(path: string, type: string): Promise { 72 | if (this.partsMap[path]) 73 | return this.partsMap[path]; 74 | 75 | if (!this._package.get(path)) 76 | return null; 77 | 78 | let part: Part = null; 79 | 80 | switch (type) { 81 | case RelationshipTypes.OfficeDocument: 82 | this.documentPart = part = new DocumentPart(this._package, path, this._parser); 83 | break; 84 | 85 | case RelationshipTypes.FontTable: 86 | this.fontTablePart = part = new FontTablePart(this._package, path); 87 | break; 88 | 89 | case RelationshipTypes.Numbering: 90 | this.numberingPart = part = new NumberingPart(this._package, path, this._parser); 91 | break; 92 | 93 | case RelationshipTypes.Styles: 94 | this.stylesPart = part = new StylesPart(this._package, path, this._parser); 95 | break; 96 | 97 | case RelationshipTypes.Theme: 98 | this.themePart = part = new ThemePart(this._package, path); 99 | break; 100 | 101 | case RelationshipTypes.Footnotes: 102 | this.footnotesPart = part = new FootnotesPart(this._package, path, this._parser); 103 | break; 104 | 105 | case RelationshipTypes.Endnotes: 106 | this.endnotesPart = part = new EndnotesPart(this._package, path, this._parser); 107 | break; 108 | 109 | case RelationshipTypes.Footer: 110 | part = new FooterPart(this._package, path, this._parser); 111 | break; 112 | 113 | case RelationshipTypes.Header: 114 | part = new HeaderPart(this._package, path, this._parser); 115 | break; 116 | 117 | case RelationshipTypes.CoreProperties: 118 | this.corePropsPart = part = new CorePropsPart(this._package, path); 119 | break; 120 | 121 | case RelationshipTypes.ExtendedProperties: 122 | this.extendedPropsPart = part = new ExtendedPropsPart(this._package, path); 123 | break; 124 | 125 | case RelationshipTypes.CustomProperties: 126 | part = new CustomPropsPart(this._package, path); 127 | break; 128 | 129 | case RelationshipTypes.Settings: 130 | this.settingsPart = part = new SettingsPart(this._package, path); 131 | break; 132 | 133 | case RelationshipTypes.Comments: 134 | this.commentsPart = part = new CommentsPart(this._package, path, this._parser); 135 | break; 136 | 137 | case RelationshipTypes.CommentsExtended: 138 | this.commentsExtendedPart = part = new CommentsExtendedPart(this._package, path); 139 | break; 140 | } 141 | 142 | if (part == null) 143 | return Promise.resolve(null); 144 | 145 | this.partsMap[path] = part; 146 | this.parts.push(part); 147 | 148 | await part.load(); 149 | 150 | if (part.rels?.length > 0) { 151 | const [folder] = splitPath(part.path); 152 | await Promise.all(part.rels.map(rel => this.loadRelationshipPart(resolvePath(rel.target, folder), rel.type))); 153 | } 154 | 155 | return part; 156 | } 157 | 158 | async loadDocumentImage(id: string, part?: Part): Promise { 159 | const x = await this.loadResource(part ?? this.documentPart, id, "blob"); 160 | return this.blobToURL(x); 161 | } 162 | 163 | async loadNumberingImage(id: string): Promise { 164 | const x = await this.loadResource(this.numberingPart, id, "blob"); 165 | return this.blobToURL(x); 166 | } 167 | 168 | async loadFont(id: string, key: string): Promise { 169 | const x = await this.loadResource(this.fontTablePart, id, "uint8array"); 170 | return x ? this.blobToURL(new Blob([deobfuscate(x, key)])) : x; 171 | } 172 | 173 | async loadAltChunk(id: string, part?: Part): Promise { 174 | return await this.loadResource(part ?? this.documentPart, id, "string"); 175 | } 176 | 177 | private blobToURL(blob: Blob): string | Promise { 178 | if (!blob) 179 | return null; 180 | 181 | if (this._options.useBase64URL) { 182 | return blobToBase64(blob); 183 | } 184 | 185 | return URL.createObjectURL(blob); 186 | } 187 | 188 | findPartByRelId(id: string, basePart: Part = null) { 189 | var rel = (basePart.rels ?? this.rels).find(r => r.id == id); 190 | const folder = basePart ? splitPath(basePart.path)[0] : ''; 191 | return rel ? this.partsMap[resolvePath(rel.target, folder)] : null; 192 | } 193 | 194 | getPathById(part: Part, id: string): string { 195 | const rel = part.rels.find(x => x.id == id); 196 | const [folder] = splitPath(part.path); 197 | return rel ? resolvePath(rel.target, folder) : null; 198 | } 199 | 200 | private loadResource(part: Part, id: string, outputType: OutputType) { 201 | const path = this.getPathById(part, id); 202 | return path ? this._package.load(path, outputType) : Promise.resolve(null); 203 | } 204 | } 205 | 206 | export function deobfuscate(data: Uint8Array, guidKey: string): Uint8Array { 207 | const len = 16; 208 | const trimmed = guidKey.replace(/{|}|-/g, ""); 209 | const numbers = new Array(len); 210 | 211 | for (let i = 0; i < len; i++) 212 | numbers[len - i - 1] = parseInt(trimmed.substr(i * 2, 2), 16); 213 | 214 | for (let i = 0; i < 32; i++) 215 | data[i] = data[i] ^ numbers[i % len] 216 | 217 | return data; 218 | } -------------------------------------------------------------------------------- /tests/extended-props-test/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/extended-props-test/document.docx -------------------------------------------------------------------------------- /tests/extended-props-test/extended-props.spec.js: -------------------------------------------------------------------------------- 1 | describe("extended-props", function () { 2 | it("loads extended props", async () => { 3 | let docBlob = await fetch(`/base/tests/extended-props-test/document.docx`).then(r => r.blob()); 4 | 5 | let div = document.createElement("div"); 6 | 7 | document.body.appendChild(div); 8 | 9 | let docParsed = await docx.renderAsync(docBlob, div); 10 | 11 | expect(!!docParsed.extendedPropsPart == true) 12 | expect(docParsed.extendedPropsPart.appVersion == "16.0000"); 13 | expect(docParsed.extendedPropsPart.application == "Microsoft Office Word"); 14 | expect(docParsed.extendedPropsPart.characters == 393); 15 | expect(docParsed.extendedPropsPart.company == ""); 16 | expect(docParsed.extendedPropsPart.lines == 3); 17 | expect(docParsed.extendedPropsPart.pages == 3); 18 | expect(docParsed.extendedPropsPart.paragraphs == 1); 19 | expect(docParsed.extendedPropsPart.template == "Normal.dotm"); 20 | expect(docParsed.extendedPropsPart.words == 68); 21 | }) 22 | }) -------------------------------------------------------------------------------- /tests/render-test/equation/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/equation/document.docx -------------------------------------------------------------------------------- /tests/render-test/equation/result.html: -------------------------------------------------------------------------------- 1 |

{1÷2=x3+4=y5*6=z73=wxy2e-iωtx21nYdydxΔyΔx∂y∂xδyδxπ2-b±b2-4ac2adx21dy21k(nk)0≤ i ≤ m0<j<n P(i,j)k=1nAkn=1m(XnYn)f(x)={-x, &x<0x, &x≥0(nk)nktanθ=sinθcosθAABCx⊕ylimn→∞(1+1n)nmax0≤x≤1xe-x2yields(1102030)

-------------------------------------------------------------------------------- /tests/render-test/footnote/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/footnote/document.docx -------------------------------------------------------------------------------- /tests/render-test/footnote/result.html: -------------------------------------------------------------------------------- 1 |

1content

  1. footnote

content21

  1. footnote2

-------------------------------------------------------------------------------- /tests/render-test/header-footer/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/header-footer/document.docx -------------------------------------------------------------------------------- /tests/render-test/header-footer/result.html: -------------------------------------------------------------------------------- 1 |

First Header

That bigger than top margin

Header end

Content

Even Header

Odd Header

-------------------------------------------------------------------------------- /tests/render-test/line-spacing/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/line-spacing/document.docx -------------------------------------------------------------------------------- /tests/render-test/line-spacing/result.html: -------------------------------------------------------------------------------- 1 |

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

-------------------------------------------------------------------------------- /tests/render-test/numbering/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/numbering/document.docx -------------------------------------------------------------------------------- /tests/render-test/page-layout/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/page-layout/document.docx -------------------------------------------------------------------------------- /tests/render-test/page-layout/result.html: -------------------------------------------------------------------------------- 1 |

page1

page2

-------------------------------------------------------------------------------- /tests/render-test/revision/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/revision/document.docx -------------------------------------------------------------------------------- /tests/render-test/revision/result.html: -------------------------------------------------------------------------------- 1 |

Original text insered

-------------------------------------------------------------------------------- /tests/render-test/table-spans/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/table-spans/document.docx -------------------------------------------------------------------------------- /tests/render-test/table-spans/result.html: -------------------------------------------------------------------------------- 1 |

Test

Test

Test

Test

Test

Test

Test

Test

Test

Test

Test

Test

Test

Test Test

Test

Test

Test

Test

Test

Test

Test

Test Test Test Test Test

Test Test

Test Test

Test Test Test

Test Test Test

Test Test Test

Test

Test

-------------------------------------------------------------------------------- /tests/render-test/table/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/table/document.docx -------------------------------------------------------------------------------- /tests/render-test/table/result.html: -------------------------------------------------------------------------------- 1 |

Test

Test

Test

Test

Test

Test

-------------------------------------------------------------------------------- /tests/render-test/test.spec.js: -------------------------------------------------------------------------------- 1 | describe("Render document", function () { 2 | const tests = [ 3 | 'text', 4 | 'underlines', 5 | 'text-break', 6 | 'table', 7 | 'page-layout', 8 | 'revision', 9 | 'numbering', 10 | 'line-spacing', 11 | 'header-footer', 12 | 'footnote', 13 | 'equation' 14 | ]; 15 | 16 | for (let path of tests) { 17 | it(`from ${path} should be correct`, async () => { 18 | 19 | const docBlob = await fetch(`/base/tests/render-test/${path}/document.docx`).then(r => r.blob()); 20 | const resultText = await fetch(`/base/tests/render-test/${path}/result.html`).then(r => r.text()); 21 | 22 | const div = document.createElement("div"); 23 | 24 | document.body.appendChild(div); 25 | 26 | await docx.renderAsync(docBlob, div); 27 | 28 | const actual = formatHTML(div.innerHTML); 29 | const expected = formatHTML(resultText); 30 | 31 | expect(actual).toBe(expected); 32 | 33 | if(actual != expected) { 34 | const diffs = Diff.diffLines(expected, actual); 35 | 36 | for(const diff of diffs) { 37 | if(diff.added) 38 | console.log('[+] ' + diff.value); 39 | 40 | if(diff.removed) 41 | console.log('[-] ' + diff.value); 42 | } 43 | } 44 | 45 | div.remove(); 46 | }); 47 | } 48 | }); 49 | 50 | function formatHTML(text) { 51 | return text.replace(/\t+|\s+/ig, ' ').replace(/>\n<'); 52 | } -------------------------------------------------------------------------------- /tests/render-test/text-break/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/text-break/document.docx -------------------------------------------------------------------------------- /tests/render-test/text-break/result.html: -------------------------------------------------------------------------------- 1 |

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

-------------------------------------------------------------------------------- /tests/render-test/text/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/text/document.docx -------------------------------------------------------------------------------- /tests/render-test/text/result.html: -------------------------------------------------------------------------------- 1 |

Test

Test color

Tab text

Text center

Text right

text text text

-------------------------------------------------------------------------------- /tests/render-test/underlines/document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolodymyrBaydalka/docxjs/436ec8dba696ef9c0dcf81800e369572852ed288/tests/render-test/underlines/document.docx -------------------------------------------------------------------------------- /tests/render-test/underlines/result.html: -------------------------------------------------------------------------------- 1 |

Underlines

Lorem ipsum dolor sit amet consectetur adipiscing elit

Lorem ipsum dolor sit amet consectetur adipiscing elit

Lorem ipsum dolor sit amet consectetur adipiscing elit

Lorem ipsum dolor sit amet consectetur adipiscing elit

Lorem ipsum dolor sit amet consectetur adipiscing elit

Lorem ipsum dolor sit amet consectetur adipiscing elit

Lorem ipsum dolor sit amet consectetur adipiscing elit

Lorem ipsum dolor sit amet consectetur adipiscing elit

Lorem ipsum dolor sit amet consectetur adipiscing elit

Lorem ipsum dolor sit amet consectetur adipiscing elit

-------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "ES2022", 4 | "moduleResolution": "bundler", 5 | "declaration": false, 6 | "noImplicitAny": false, 7 | "noEmitOnError": true, 8 | "pretty": true, 9 | "removeComments": true, 10 | "preserveConstEnums": true, 11 | "sourceMap": true, 12 | "noEmitHelpers": false, 13 | "importHelpers": false, 14 | "esModuleInterop": true, 15 | "target": "ES2020", 16 | "noEmit": true, 17 | "lib": [ 18 | "ES2017", 19 | "dom" 20 | ], 21 | }, 22 | "exclude": [ 23 | "node_modules" 24 | ] 25 | } --------------------------------------------------------------------------------