@bnsights/bbsf-utilities 1.0.69-beta.1 → 1.0.69-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,20 +18,6 @@ import { JwtHelperService } from '@auth0/angular-jwt';
18
18
  import { __decorate } from 'tslib';
19
19
  import { plainToClass } from 'class-transformer';
20
20
  import { takeUntil, tap, map } from 'rxjs/operators';
21
- import JSZip from 'jszip';
22
- import { fragment, create } from 'xmlbuilder2';
23
- import VNode$1 from 'virtual-dom/vnode/vnode';
24
- import VText from 'virtual-dom/vnode/vtext';
25
- import HTMLToVDOM from 'html-to-vdom';
26
- import { cloneDeep } from 'lodash';
27
- import { nanoid } from 'nanoid';
28
- import isVNode from 'virtual-dom/vnode/is-vnode';
29
- import isVText from 'virtual-dom/vnode/is-vtext';
30
- import escape from 'escape-html';
31
- import colorNames from 'color-name';
32
- import imageToBase64 from 'image-to-base64';
33
- import mimeTypes from 'mime-types';
34
- import sizeOf from 'image-size';
35
21
 
36
22
  class User {
37
23
  }
@@ -894,3527 +880,28 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImpo
894
880
  }]
895
881
  }], ctorParameters: () => [{ type: BBSFTranslateService }, { type: EnvironmentService }, { type: i0.Injector }], propDecorators: { blockUI: [] } });
896
882
 
897
- const contentTypesXML = `
898
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
899
-
900
- <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
901
- <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />
902
- <Default Extension="jpeg" ContentType="image/jpeg"/>
903
- <Default Extension="png" ContentType="image/png"/>
904
- <Default Extension="xml" ContentType="application/xml"/>
905
- <Override PartName="/_rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
906
- <Override PartName="/word/_rels/document.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
907
- <Override PartName="/word/_rels/footer1.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
908
- <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
909
- <Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
910
- <Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>
911
- <Override PartName="/word/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>
912
- <Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/>
913
- <Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>
914
- <Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/>
915
- <Override PartName="/word/webSettings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"/>
916
- <Override PartName="/word/afchunk.mht" ContentType="message/rfc822"/>
917
- <Override PartName="/word/afchunkheader.mht" ContentType="message/rfc822"/>
918
- <Override PartName="/word/afchunkfooter.mht" ContentType="message/rfc822"/>
919
- </Types>
920
- `;
921
-
922
- const namespaces = {
923
- a: 'http://schemas.openxmlformats.org/drawingml/2006/main',
924
- b: 'http://schemas.openxmlformats.org/officeDocument/2006/bibliography',
925
- cdr: 'http://schemas.openxmlformats.org/drawingml/2006/chartDrawing',
926
- dc: 'http://purl.org/dc/elements/1.1/',
927
- dcmitype: 'http://purl.org/dc/dcmitype/',
928
- dcterms: 'http://purl.org/dc/terms/',
929
- o: 'urn:schemas-microsoft-com:office:office',
930
- pic: 'http://schemas.openxmlformats.org/drawingml/2006/picture',
931
- r: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
932
- v: 'urn:schemas-microsoft-com:vml',
933
- ve: 'http://schemas.openxmlformats.org/markup-compatibility/2006',
934
- vt: 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
935
- w: 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
936
- w10: 'urn:schemas-microsoft-com:office:word',
937
- wp: 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing',
938
- wne: 'http://schemas.microsoft.com/office/word/2006/wordml',
939
- xsd: 'http://www.w3.org/2001/XMLSchema',
940
- xsi: 'http://www.w3.org/2001/XMLSchema-instance',
941
- numbering: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering',
942
- hyperlinks: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
943
- images: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
944
- styles: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
945
- headers: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/header',
946
- footers: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer',
947
- themes: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
948
- coreProperties: 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties',
949
- officeDocumentRelation: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
950
- corePropertiesRelation: 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
951
- settingsRelation: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings',
952
- webSettingsRelation: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings',
953
- sl: 'http://schemas.openxmlformats.org/schemaLibrary/2006/main',
954
- contentTypes: 'http://schemas.openxmlformats.org/package/2006/content-types',
955
- relationship: 'http://schemas.openxmlformats.org/package/2006/relationships',
956
- };
957
-
958
- const applicationName = 'html-to-docx';
959
- const defaultOrientation = 'portrait';
960
- const landscapeWidth = 15840;
961
- const landscapeHeight = 12240;
962
- const landscapeMargins = {
963
- top: 1800,
964
- right: 1440,
965
- bottom: 1800,
966
- left: 1440,
967
- header: 720,
968
- footer: 720,
969
- gutter: 0,
970
- };
971
- const portraitMargins = {
972
- top: 1440,
973
- right: 1800,
974
- bottom: 1440,
975
- left: 1800,
976
- header: 720,
977
- footer: 720,
978
- gutter: 0,
979
- };
980
- const defaultFont = 'Times New Roman';
981
- const defaultFontSize = 22;
982
- const defaultDocumentOptions = {
983
- orientation: defaultOrientation,
984
- margins: cloneDeep(portraitMargins),
985
- title: '',
986
- subject: '',
987
- creator: applicationName,
988
- keywords: [applicationName],
989
- description: '',
990
- lastModifiedBy: applicationName,
991
- revision: 1,
992
- createdAt: new Date(),
993
- modifiedAt: new Date(),
994
- headerType: 'default',
995
- header: false,
996
- footerType: 'default',
997
- footer: false,
998
- font: defaultFont,
999
- fontSize: defaultFontSize,
1000
- complexScriptFontSize: defaultFontSize,
1001
- table: {
1002
- row: {
1003
- cantSplit: false,
1004
- },
1005
- },
1006
- pageSize: {
1007
- width: landscapeHeight,
1008
- height: landscapeWidth,
1009
- },
1010
- pageNumber: false,
1011
- skipFirstHeaderFooter: false,
1012
- lineNumber: false,
1013
- lineNumberOptions: {
1014
- countBy: 1,
1015
- start: 0,
1016
- restart: 'continuous',
1017
- },
1018
- numbering: {
1019
- defaultOrderedListStyleType: 'decimal',
1020
- },
1021
- };
1022
- const defaultHTMLString = '<p></p>';
1023
- const relsFolderName = '_rels';
1024
- const headerFileName = 'header1';
1025
- const footerFileName = 'footer1';
1026
- const themeFileName = 'theme1';
1027
- const documentFileName = 'document';
1028
- const headerType = 'header';
1029
- const footerType = 'footer';
1030
- const themeType = 'theme';
1031
- const hyperlinkType = 'hyperlink';
1032
- const imageType = 'image';
1033
- const internalRelationship = 'Internal';
1034
- const wordFolder = 'word';
1035
- const themeFolder = 'theme';
1036
- const paragraphBordersObject = {
1037
- top: {
1038
- size: 0,
1039
- spacing: 3,
1040
- color: 'FFFFFF',
1041
- },
1042
- left: {
1043
- size: 0,
1044
- spacing: 3,
1045
- color: 'FFFFFF',
1046
- },
1047
- bottom: {
1048
- size: 0,
1049
- spacing: 3,
1050
- color: 'FFFFFF',
1051
- },
1052
- right: {
1053
- size: 0,
1054
- spacing: 3,
1055
- color: 'FFFFFF',
1056
- },
1057
- };
1058
- const colorlessColors = ['transparent', 'auto'];
1059
- const verticalAlignValues = ['top', 'middle', 'bottom'];
1060
-
1061
- const generateCoreXML = (title = '', subject = '', creator = applicationName, keywords = [applicationName], description = '', lastModifiedBy = applicationName, revision = 1, createdAt = new Date(), modifiedAt = new Date()) => `
1062
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1063
-
1064
- <cp:coreProperties
1065
- xmlns:cp="${namespaces.coreProperties}"
1066
- xmlns:dc="${namespaces.dc}"
1067
- xmlns:dcterms="${namespaces.dcterms}"
1068
- xmlns:dcmitype="${namespaces.dcmitype}"
1069
- xmlns:xsi="${namespaces.xsi}"
1070
- >
1071
- <dc:title>${title}</dc:title>
1072
- <dc:subject>${subject}</dc:subject>
1073
- <dc:creator>${creator}</dc:creator>
1074
- ${keywords && Array.isArray(keywords)
1075
- ? `<cp:keywords>${keywords.join(', ')}</cp:keywords>`
1076
- : ''}
1077
- <dc:description>${description}</dc:description>
1078
- <cp:lastModifiedBy>${lastModifiedBy}</cp:lastModifiedBy>
1079
- <cp:revision>${revision}</cp:revision>
1080
- <dcterms:created xsi:type="dcterms:W3CDTF">${createdAt instanceof Date ? createdAt.toISOString() : new Date().toISOString()}</dcterms:created>
1081
- <dcterms:modified xsi:type="dcterms:W3CDTF">${modifiedAt instanceof Date ? modifiedAt.toISOString() : new Date().toISOString()}</dcterms:modified>
1082
- </cp:coreProperties>
1083
- `;
1084
-
1085
- const documentRelsXML = `
1086
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1087
-
1088
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
1089
- <Relationship Id="rId1" Type="${namespaces.numbering}" Target="numbering.xml"/>
1090
- <Relationship Id="rId2" Type="${namespaces.styles}" Target="styles.xml"/>
1091
- <Relationship Id="rId3" Type="${namespaces.settingsRelation}" Target="settings.xml"/>
1092
- <Relationship Id="rId4" Type="${namespaces.webSettingsRelation}" Target="webSettings.xml"/>
1093
- <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunk.mht" Id="htmlChunk" />
1094
- <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunkheader.mht" Id="htmlChunkHeader" />
1095
- <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunkfooter.mht" Id="htmlChunkFooter" />
1096
- </Relationships>
1097
- `;
1098
-
1099
- const relsXML = `
1100
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1101
-
1102
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
1103
- <Relationship Id="rId1" Type="${namespaces.officeDocumentRelation}" Target="word/document.xml"/>
1104
- <Relationship Id="rId2" Type="${namespaces.corePropertiesRelation}" Target="docProps/core.xml"/>
1105
- </Relationships>
1106
- `;
1107
-
1108
- const generateNumberingXMLTemplate = () => `
1109
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1110
-
1111
- <w:numbering
1112
- xmlns:w="${namespaces.w}"
1113
- xmlns:ve="${namespaces.ve}"
1114
- xmlns:o="${namespaces.o}"
1115
- xmlns:r="${namespaces.r}"
1116
- xmlns:v="${namespaces.v}"
1117
- xmlns:wp="${namespaces.wp}"
1118
- xmlns:w10="${namespaces.w10}"
1119
- xmlns:wne="${namespaces.wne}">
1120
- </w:numbering>
1121
- `;
1122
-
1123
- const generateStylesXML = (font = defaultFont, fontSize = defaultFontSize, complexScriptFontSize = defaultFontSize) => `
1124
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1125
-
1126
- <w:styles xmlns:w="${namespaces.w}" xmlns:r="${namespaces.r}">
1127
- <w:docDefaults>
1128
- <w:rPrDefault>
1129
- <w:rPr>
1130
- <w:rFonts w:ascii="${font}" w:eastAsiaTheme="minorHAnsi" w:hAnsiTheme="minorHAnsi" w:cstheme="minorBidi" />
1131
- <w:sz w:val="${fontSize}" />
1132
- <w:szCs w:val="${complexScriptFontSize}" />
1133
- <w:lang w:val="en-US" w:eastAsia="en-US" w:bidi="ar-SA" />
1134
- </w:rPr>
1135
- </w:rPrDefault>
1136
- <w:pPrDefault>
1137
- <w:pPr>
1138
- <w:spacing w:after="120" w:line="240" w:lineRule="atLeast" />
1139
- </w:pPr>
1140
- </w:pPrDefault>
1141
- </w:docDefaults>
1142
- <w:style w:type="character" w:styleId="Hyperlink">
1143
- <w:name w:val="Hyperlink" />
1144
- <w:rPr>
1145
- <w:color w:val="0000FF" />
1146
- <w:u w:val="single" />
1147
- </w:rPr>
1148
- </w:style>
1149
- <w:style w:type="paragraph" w:styleId="Heading1">
1150
- <w:name w:val="heading 1" />
1151
- <w:basedOn w:val="Normal" />
1152
- <w:next w:val="Normal" />
1153
- <w:uiPriority w:val="9" />
1154
- <w:qFormat />
1155
- <w:pPr>
1156
- <w:keepNext />
1157
- <w:keepLines />
1158
- <w:spacing w:before="480" />
1159
- <w:outlineLvl w:val="0" />
1160
- </w:pPr>
1161
- <w:rPr>
1162
- <w:b />
1163
- <w:sz w:val="48" />
1164
- <w:szCs w:val="48" />
1165
- </w:rPr>
1166
- </w:style>
1167
- <w:style w:type="paragraph" w:styleId="Heading2">
1168
- <w:name w:val="heading 2" />
1169
- <w:basedOn w:val="Normal" />
1170
- <w:next w:val="Normal" />
1171
- <w:uiPriority w:val="9" />
1172
- <w:unhideWhenUsed />
1173
- <w:qFormat />
1174
- <w:pPr>
1175
- <w:keepNext />
1176
- <w:keepLines />
1177
- <w:spacing w:before="360" w:after="80" />
1178
- <w:outlineLvl w:val="1" />
1179
- </w:pPr>
1180
- <w:rPr>
1181
- <w:b />
1182
- <w:sz w:val="36" />
1183
- <w:szCs w:val="36" />
1184
- </w:rPr>
1185
- </w:style>
1186
- <w:style w:type="paragraph" w:styleId="Heading3">
1187
- <w:name w:val="heading 3" />
1188
- <w:basedOn w:val="Normal" />
1189
- <w:next w:val="Normal" />
1190
- <w:uiPriority w:val="9" />
1191
- <w:semiHidden />
1192
- <w:unhideWhenUsed />
1193
- <w:qFormat />
1194
- <w:pPr>
1195
- <w:keepNext />
1196
- <w:keepLines />
1197
- <w:spacing w:before="280" w:after="80" />
1198
- <w:outlineLvl w:val="2" />
1199
- </w:pPr>
1200
- <w:rPr>
1201
- <w:b />
1202
- <w:sz w:val="28" />
1203
- <w:szCs w:val="28" />
1204
- </w:rPr>
1205
- </w:style>
1206
- <w:style w:type="paragraph" w:styleId="Heading4">
1207
- <w:name w:val="heading 4" />
1208
- <w:basedOn w:val="Normal" />
1209
- <w:next w:val="Normal" />
1210
- <w:uiPriority w:val="9" />
1211
- <w:semiHidden />
1212
- <w:unhideWhenUsed />
1213
- <w:qFormat />
1214
- <w:pPr>
1215
- <w:keepNext />
1216
- <w:keepLines />
1217
- <w:spacing w:before="240" w:after="40" />
1218
- <w:outlineLvl w:val="3" />
1219
- </w:pPr>
1220
- <w:rPr>
1221
- <w:b />
1222
- <w:sz w:val="24" />
1223
- <w:szCs w:val="24" />
1224
- </w:rPr>
1225
- </w:style>
1226
- <w:style w:type="paragraph" w:styleId="Heading5">
1227
- <w:name w:val="heading 5" />
1228
- <w:basedOn w:val="Normal" />
1229
- <w:next w:val="Normal" />
1230
- <w:uiPriority w:val="9" />
1231
- <w:semiHidden />
1232
- <w:unhideWhenUsed />
1233
- <w:qFormat />
1234
- <w:pPr>
1235
- <w:keepNext />
1236
- <w:keepLines />
1237
- <w:spacing w:before="220" w:after="40" />
1238
- <w:outlineLvl w:val="4" />
1239
- </w:pPr>
1240
- <w:rPr>
1241
- <w:b />
1242
- </w:rPr>
1243
- </w:style>
1244
- <w:style w:type="paragraph" w:styleId="Heading6">
1245
- <w:name w:val="heading 6" />
1246
- <w:basedOn w:val="Normal" />
1247
- <w:next w:val="Normal" />
1248
- <w:uiPriority w:val="9" />
1249
- <w:semiHidden />
1250
- <w:unhideWhenUsed />
1251
- <w:qFormat />
1252
- <w:pPr>
1253
- <w:keepNext />
1254
- <w:keepLines />
1255
- <w:spacing w:before="200" w:after="40" />
1256
- <w:outlineLvl w:val="5" />
1257
- </w:pPr>
1258
- <w:rPr>
1259
- <w:b />
1260
- <w:sz w:val="20" />
1261
- <w:szCs w:val="20" />
1262
- </w:rPr>
1263
- </w:style>
1264
- </w:styles>
1265
- `;
1266
-
1267
- const fontTableXML = `
1268
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1269
-
1270
- <w:fonts
1271
- xmlns:r="${namespaces.r}"
1272
- xmlns:w="${namespaces.w}"
1273
- >
1274
- <w:font w:name="Symbol">
1275
- <w:panose1 w:val="05050102010706020507"/>
1276
- <w:charset w:val="02"/>
1277
- <w:family w:val="decorative"/>
1278
- <w:pitch w:val="variable"/>
1279
- <w:sig w:usb0="00000000" w:usb1="10000000" w:usb2="00000000" w:usb3="00000000" w:csb0="80000000" w:csb1="00000000"/>
1280
- </w:font>
1281
- <w:font w:name="Calibri">
1282
- <w:panose1 w:val="020F0502020204030204"/>
1283
- <w:charset w:val="00"/>
1284
- <w:family w:val="swiss"/>
1285
- <w:pitch w:val="variable"/>
1286
- <w:sig w:usb0="E4002EFF" w:usb1="C000247B" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/>
1287
- </w:font>
1288
- <w:font w:name="Times New Roman">
1289
- <w:panose1 w:val="02020603050405020304"/>
1290
- <w:charset w:val="00"/>
1291
- <w:family w:val="roman"/>
1292
- <w:pitch w:val="variable"/>
1293
- <w:sig w:usb0="E0002EFF" w:usb1="C000785B" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/>
1294
- </w:font>
1295
- <w:font w:name="Calibri Light">
1296
- <w:panose1 w:val="020F0302020204030204"/>
1297
- <w:charset w:val="00"/>
1298
- <w:family w:val="swiss"/>
1299
- <w:pitch w:val="variable"/>
1300
- <w:sig w:usb0="E4002EFF" w:usb1="C000247B" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/>
1301
- </w:font>
1302
- </w:fonts>
1303
- `;
1304
-
1305
- const generateThemeXML = (font = defaultFont) => `
1306
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1307
-
1308
- <a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">
1309
- <a:themeElements>
1310
- <a:clrScheme name="Office">
1311
- <a:dk1>
1312
- <a:sysClr val="windowText" lastClr="000000"/>
1313
- </a:dk1>
1314
- <a:lt1>
1315
- <a:sysClr val="window" lastClr="FFFFFF"/>
1316
- </a:lt1>
1317
- <a:dk2>
1318
- <a:srgbClr val="44546A"/>
1319
- </a:dk2>
1320
- <a:lt2>
1321
- <a:srgbClr val="E7E6E6"/>
1322
- </a:lt2>
1323
- <a:accent1>
1324
- <a:srgbClr val="4472C4"/>
1325
- </a:accent1>
1326
- <a:accent2>
1327
- <a:srgbClr val="ED7D31"/>
1328
- </a:accent2>
1329
- <a:accent3>
1330
- <a:srgbClr val="A5A5A5"/>
1331
- </a:accent3>
1332
- <a:accent4>
1333
- <a:srgbClr val="FFC000"/>
1334
- </a:accent4>
1335
- <a:accent5>
1336
- <a:srgbClr val="5B9BD5"/>
1337
- </a:accent5>
1338
- <a:accent6>
1339
- <a:srgbClr val="70AD47"/>
1340
- </a:accent6>
1341
- <a:hlink>
1342
- <a:srgbClr val="0563C1"/>
1343
- </a:hlink>
1344
- <a:folHlink>
1345
- <a:srgbClr val="954F72"/>
1346
- </a:folHlink>
1347
- </a:clrScheme>
1348
- <a:fontScheme name="Office">
1349
- <a:majorFont>
1350
- <a:latin typeface="${font}"/>
1351
- <a:ea typeface="${font}"/>
1352
- <a:cs typeface=""/>
1353
- </a:majorFont>
1354
- <a:minorFont>
1355
- <a:latin typeface="${font}"/>
1356
- <a:ea typeface="${font}"/>
1357
- <a:cs typeface=""/>
1358
- </a:minorFont>
1359
- </a:fontScheme>
1360
- <a:fmtScheme name="Office">
1361
- <a:fillStyleLst>
1362
- <a:solidFill>
1363
- <a:schemeClr val="phClr"/>
1364
- </a:solidFill>
1365
- <a:gradFill rotWithShape="1">
1366
- <a:gsLst>
1367
- <a:gs pos="0">
1368
- <a:schemeClr val="phClr">
1369
- <a:lumMod val="110000"/>
1370
- <a:satMod val="105000"/>
1371
- <a:tint val="67000"/>
1372
- </a:schemeClr>
1373
- </a:gs>
1374
- <a:gs pos="50000">
1375
- <a:schemeClr val="phClr">
1376
- <a:lumMod val="105000"/>
1377
- <a:satMod val="103000"/>
1378
- <a:tint val="73000"/>
1379
- </a:schemeClr>
1380
- </a:gs>
1381
- <a:gs pos="100000">
1382
- <a:schemeClr val="phClr">
1383
- <a:lumMod val="105000"/>
1384
- <a:satMod val="109000"/>
1385
- <a:tint val="81000"/>
1386
- </a:schemeClr>
1387
- </a:gs>
1388
- </a:gsLst>
1389
- <a:lin ang="5400000" scaled="0"/>
1390
- </a:gradFill>
1391
- <a:gradFill rotWithShape="1">
1392
- <a:gsLst>
1393
- <a:gs pos="0">
1394
- <a:schemeClr val="phClr">
1395
- <a:satMod val="103000"/>
1396
- <a:lumMod val="102000"/>
1397
- <a:tint val="94000"/>
1398
- </a:schemeClr>
1399
- </a:gs>
1400
- <a:gs pos="50000">
1401
- <a:schemeClr val="phClr">
1402
- <a:satMod val="110000"/>
1403
- <a:lumMod val="100000"/>
1404
- <a:shade val="100000"/>
1405
- </a:schemeClr>
1406
- </a:gs>
1407
- <a:gs pos="100000">
1408
- <a:schemeClr val="phClr">
1409
- <a:lumMod val="99000"/>
1410
- <a:satMod val="120000"/>
1411
- <a:shade val="78000"/>
1412
- </a:schemeClr>
1413
- </a:gs>
1414
- </a:gsLst>
1415
- <a:lin ang="5400000" scaled="0"/>
1416
- </a:gradFill>
1417
- </a:fillStyleLst>
1418
- <a:lnStyleLst>
1419
- <a:ln w="6350" cap="flat" cmpd="sng" algn="ctr">
1420
- <a:solidFill>
1421
- <a:schemeClr val="phClr"/>
1422
- </a:solidFill>
1423
- <a:prstDash val="solid"/>
1424
- <a:miter lim="800000"/>
1425
- </a:ln>
1426
- <a:ln w="12700" cap="flat" cmpd="sng" algn="ctr">
1427
- <a:solidFill>
1428
- <a:schemeClr val="phClr"/>
1429
- </a:solidFill>
1430
- <a:prstDash val="solid"/>
1431
- <a:miter lim="800000"/>
1432
- </a:ln>
1433
- <a:ln w="19050" cap="flat" cmpd="sng" algn="ctr">
1434
- <a:solidFill>
1435
- <a:schemeClr val="phClr"/>
1436
- </a:solidFill>
1437
- <a:prstDash val="solid"/>
1438
- <a:miter lim="800000"/>
1439
- </a:ln>
1440
- </a:lnStyleLst>
1441
- <a:effectStyleLst>
1442
- <a:effectStyle>
1443
- <a:effectLst/>
1444
- </a:effectStyle>
1445
- <a:effectStyle>
1446
- <a:effectLst/>
1447
- </a:effectStyle>
1448
- <a:effectStyle>
1449
- <a:effectLst>
1450
- <a:outerShdw blurRad="57150" dist="19050" dir="5400000" algn="ctr" rotWithShape="0">
1451
- <a:srgbClr val="000000">
1452
- <a:alpha val="63000"/>
1453
- </a:srgbClr>
1454
- </a:outerShdw>
1455
- </a:effectLst>
1456
- </a:effectStyle>
1457
- </a:effectStyleLst>
1458
- <a:bgFillStyleLst>
1459
- <a:solidFill>
1460
- <a:schemeClr val="phClr"/>
1461
- </a:solidFill>
1462
- <a:solidFill>
1463
- <a:schemeClr val="phClr">
1464
- <a:tint val="95000"/>
1465
- <a:satMod val="170000"/>
1466
- </a:schemeClr>
1467
- </a:solidFill>
1468
- <a:gradFill rotWithShape="1">
1469
- <a:gsLst>
1470
- <a:gs pos="0">
1471
- <a:schemeClr val="phClr">
1472
- <a:tint val="93000"/>
1473
- <a:satMod val="150000"/>
1474
- <a:shade val="98000"/>
1475
- <a:lumMod val="102000"/>
1476
- </a:schemeClr>
1477
- </a:gs>
1478
- <a:gs pos="50000">
1479
- <a:schemeClr val="phClr">
1480
- <a:tint val="98000"/>
1481
- <a:satMod val="130000"/>
1482
- <a:shade val="90000"/>
1483
- <a:lumMod val="103000"/>
1484
- </a:schemeClr>
1485
- </a:gs>
1486
- <a:gs pos="100000">
1487
- <a:schemeClr val="phClr">
1488
- <a:shade val="63000"/>
1489
- <a:satMod val="120000"/>
1490
- </a:schemeClr>
1491
- </a:gs>
1492
- </a:gsLst>
1493
- <a:lin ang="5400000" scaled="0"/>
1494
- </a:gradFill>
1495
- </a:bgFillStyleLst>
1496
- </a:fmtScheme>
1497
- </a:themeElements>
1498
- </a:theme>
1499
- `;
1500
-
1501
- const settingsXML = `
1502
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1503
-
1504
- <w:settings xmlns:w="${namespaces.w}" xmlns:o="${namespaces.o}" xmlns:r="${namespaces.r}" xmlns:v="${namespaces.v}" xmlns:w10="${namespaces.w10}" xmlns:sl="${namespaces.sl}">
1505
- <w:zoom w:percent="100"/>
1506
- <w:defaultTabStop w:val="720"/>
1507
- <w:decimalSymbol w:val="."/>
1508
- <w:listSeparator w:val=","/>
1509
- </w:settings>
1510
- `;
1511
-
1512
- const webSettingsXML = `
1513
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1514
-
1515
- <w:webSettings xmlns:w="${namespaces.w}" xmlns:r="${namespaces.r}">
1516
- </w:webSettings>
1517
- `;
1518
-
1519
- const genericRelsXML = `
1520
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1521
-
1522
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
1523
- <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunk.mht" Id="htmlChunk" />
1524
- <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunkheader.mht" Id="htmlChunkHeader" />
1525
- <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunkfooter.mht" Id="htmlChunkFooter" />
1526
- </Relationships>
1527
- `;
1528
-
1529
- const generateDocumentTemplate = (width, height, orientation, margins) => `
1530
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1531
- <w:document
1532
- xmlns:a="${namespaces.a}"
1533
- xmlns:cdr="${namespaces.cdr}"
1534
- xmlns:o="${namespaces.o}"
1535
- xmlns:pic="${namespaces.pic}"
1536
- xmlns:r="${namespaces.r}"
1537
- xmlns:v="${namespaces.v}"
1538
- xmlns:ve="${namespaces.ve}"
1539
- xmlns:vt="${namespaces.vt}"
1540
- xmlns:w="${namespaces.w}"
1541
- xmlns:w10="${namespaces.w10}"
1542
- xmlns:wp="${namespaces.wp}"
1543
- xmlns:wne="${namespaces.wne}"
1544
- >
1545
- <w:body>
1546
-
1547
- <w:altChunk r:id="htmlChunk" />
1548
- <w:sectPr>
1549
- <w:pgSz w:w="${width}" w:h="${height}" w:orient="${orientation}" />
1550
- <w:pgMar w:top="${margins.top}"
1551
- w:right="${margins.right}"
1552
- w:bottom="${margins.bottom}"
1553
- w:left="${margins.left}"
1554
- w:header="${margins.header}"
1555
- w:footer="${margins.footer}"
1556
- w:gutter="${margins.gutter}"/>
1557
- </w:sectPr>
1558
- </w:body>
1559
- </w:document>
1560
- `;
1561
- const generateDocumentTemplateHeader = `
1562
- <w:hdr
1563
- xmlns:a="${namespaces.a}"
1564
- xmlns:cdr="${namespaces.cdr}"
1565
- xmlns:o="${namespaces.o}"
1566
- xmlns:pic="${namespaces.pic}"
1567
- xmlns:r="${namespaces.r}"
1568
- xmlns:v="${namespaces.v}"
1569
- xmlns:ve="${namespaces.ve}"
1570
- xmlns:vt="${namespaces.vt}"
1571
- xmlns:w="${namespaces.w}"
1572
- xmlns:w10="${namespaces.w10}"
1573
- xmlns:wp="${namespaces.wp}"
1574
- xmlns:wne="${namespaces.wne}"
1575
- >
1576
- <w:altChunk r:id="htmlChunkHeader" />
1577
- </w:hdr>
1578
- `;
1579
- const generateDocumentTemplateFooter = `
1580
- <w:ftr
1581
- xmlns:a="${namespaces.a}"
1582
- xmlns:cdr="${namespaces.cdr}"
1583
- xmlns:o="${namespaces.o}"
1584
- xmlns:pic="${namespaces.pic}"
1585
- xmlns:r="${namespaces.r}"
1586
- xmlns:v="${namespaces.v}"
1587
- xmlns:ve="${namespaces.ve}"
1588
- xmlns:vt="${namespaces.vt}"
1589
- xmlns:w="${namespaces.w}"
1590
- xmlns:w10="${namespaces.w10}"
1591
- xmlns:wp="${namespaces.wp}"
1592
- >
1593
- <w:altChunk r:id="htmlChunkFooter" />
1594
- <w:p w:rsidR="0014021C" w:rsidRDefault="0014021C" w:rsidP="0014021C">
1595
- <w:pPr>
1596
- <w:pStyle w:val="Footer"/>
1597
- <w:jc w:val="center"/>
1598
- </w:pPr>
1599
- <w:fldSimple xmlns:ns2="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ns2:instr="PAGE">
1600
- <w:r/>
1601
- </w:fldSimple>
1602
- </w:p>
1603
- </w:ftr>
1604
- `;
1605
- const generateDocumentTemplateFooterWithoutPaging = `
1606
- <w:ftr
1607
- xmlns:a="${namespaces.a}"
1608
- xmlns:cdr="${namespaces.cdr}"
1609
- xmlns:o="${namespaces.o}"
1610
- xmlns:pic="${namespaces.pic}"
1611
- xmlns:r="${namespaces.r}"
1612
- xmlns:v="${namespaces.v}"
1613
- xmlns:ve="${namespaces.ve}"
1614
- xmlns:vt="${namespaces.vt}"
1615
- xmlns:w="${namespaces.w}"
1616
- xmlns:w10="${namespaces.w10}"
1617
- xmlns:wp="${namespaces.wp}"
1618
- >
1619
- <w:altChunk r:id="htmlChunkFooter" />
1620
- </w:ftr>
1621
- `;
1622
- { /* <w:altChunk r:id="htmlChunkFooter" /> */ }
1623
- {
1624
- /* <w:altChunk r:id="htmlChunkFooter" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" /> */
1625
- }
1626
- {
1627
- /* <w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
1628
- <fldSimple xmlns:ns2="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ns2:instr="PAGE">
1629
- </fldSimple>
1630
- <w:altChunk r:id="htmlChunkFooter" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" />
1631
- </w:ftr> */
1632
- }
1633
-
1634
- /* eslint-disable no-param-reassign */
1635
- const rgbRegex = /rgb\((\d+),\s*([\d.]+),\s*([\d.]+)\)/i;
1636
- const hslRegex = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/i;
1637
- const hexRegex = /#([0-9A-F]{6})/i;
1638
- const hex3Regex = /#([0-9A-F])([0-9A-F])([0-9A-F])/i;
1639
- // eslint-disable-next-line import/prefer-default-export
1640
- const rgbToHex = (red, green, blue) => {
1641
- const hexColorCode = [red, green, blue]
1642
- .map((x) => {
1643
- // eslint-disable-next-line radix, no-param-reassign
1644
- x = parseInt(x).toString(16);
1645
- return x.length === 1 ? `0${x}` : x;
1646
- })
1647
- .join('');
1648
- return hexColorCode;
1649
- };
1650
- const hslToHex = (hue, saturation, luminosity) => {
1651
- hue /= 360;
1652
- saturation /= 100;
1653
- luminosity /= 100;
1654
- // eslint-disable-next-line one-var
1655
- let red, green, blue;
1656
- if (saturation === 0) {
1657
- // eslint-disable-next-line no-multi-assign
1658
- red = green = blue = luminosity; // achromatic
1659
- }
1660
- else {
1661
- const hue2rgb = (p, q, t) => {
1662
- if (t < 0)
1663
- t += 1;
1664
- if (t > 1)
1665
- t -= 1;
1666
- if (t < 1 / 6)
1667
- return p + (q - p) * 6 * t;
1668
- if (t < 1 / 2)
1669
- return q;
1670
- if (t < 2 / 3)
1671
- return p + (q - p) * (2 / 3 - t) * 6;
1672
- return p;
1673
- };
1674
- const q = luminosity < 0.5
1675
- ? luminosity * (1 + saturation)
1676
- : luminosity + saturation - luminosity * saturation;
1677
- const p = 2 * luminosity - q;
1678
- red = hue2rgb(p, q, hue + 1 / 3);
1679
- green = hue2rgb(p, q, hue);
1680
- blue = hue2rgb(p, q, hue - 1 / 3);
1681
- }
1682
- return [red, green, blue]
1683
- .map((x) => {
1684
- const hex = Math.round(x * 255).toString(16);
1685
- return hex.length === 1 ? `0${hex}` : hex;
1686
- })
1687
- .join('');
1688
- };
1689
- const hex3ToHex = (red, green, blue) => {
1690
- const hexColorCode = [red, green, blue].map((x) => `${x}${x}`).join('');
1691
- return hexColorCode;
1692
- };
1693
-
1694
- const pixelRegex = /([\d.]+)px/i;
1695
- const percentageRegex = /([\d.]+)%/i;
1696
- const pointRegex = /([\d.]+)pt/i;
1697
- const cmRegex = /([\d.]+)cm/i;
1698
- const inchRegex = /([\d.]+)in/i;
1699
- const pixelToEMU = (pixelValue) => Math.round(pixelValue * 9525);
1700
- const EMUToPixel = (EMUValue) => Math.round(EMUValue / 9525);
1701
- const TWIPToEMU = (TWIPValue) => Math.round(TWIPValue * 635);
1702
- const EMUToTWIP = (EMUValue) => Math.round(EMUValue / 635);
1703
- const pointToTWIP = (pointValue) => Math.round(pointValue * 20);
1704
- const TWIPToPoint = (TWIPValue) => Math.round(TWIPValue / 20);
1705
- const pointToHIP = (pointValue) => Math.round(pointValue * 2);
1706
- const HIPToPoint = (HIPValue) => Math.round(HIPValue / 2);
1707
- const HIPToTWIP = (HIPValue) => Math.round(HIPValue * 10);
1708
- const TWIPToHIP = (TWIPValue) => Math.round(TWIPValue / 10);
1709
- const pixelToTWIP = (pixelValue) => EMUToTWIP(pixelToEMU(pixelValue));
1710
- const TWIPToPixel = (TWIPValue) => EMUToPixel(TWIPToEMU(TWIPValue));
1711
- const pixelToHIP = (pixelValue) => TWIPToHIP(EMUToTWIP(pixelToEMU(pixelValue)));
1712
- const HIPToPixel = (HIPValue) => EMUToPixel(TWIPToEMU(HIPToTWIP(HIPValue)));
1713
- const inchToPoint = (inchValue) => Math.round(inchValue * 72);
1714
- const inchToTWIP = (inchValue) => pointToTWIP(inchToPoint(inchValue));
1715
- const cmToInch = (cmValue) => cmValue * 0.3937008;
1716
- const cmToTWIP = (cmValue) => inchToTWIP(cmToInch(cmValue));
1717
- const pixelToPoint = (pixelValue) => HIPToPoint(pixelToHIP(pixelValue));
1718
- const pointToPixel = (pointValue) => HIPToPixel(pointToHIP(pointValue));
1719
- const EIPToPoint = (EIPValue) => Math.round(EIPValue / 8);
1720
- const pointToEIP = (PointValue) => Math.round(PointValue * 8);
1721
- const pixelToEIP = (pixelValue) => pointToEIP(pixelToPoint(pixelValue));
1722
- const EIPToPixel = (EIPValue) => pointToPixel(EIPToPoint(EIPValue));
1723
-
1724
- // eslint-disable-next-line import/prefer-default-export
1725
- const vNodeHasChildren = (vNode) => vNode && vNode.children && Array.isArray(vNode.children) && vNode.children.length;
1726
-
1727
- const isValidUrl = (urlString) => {
1728
- const urlRegex = /http(s)?:\/\/(\w+:?\w*@)?(\S+)(:\d+)?((?<=\.)\w+)+(\/([\w#!:.?+=&%@!\-/])*)?/gi;
1729
- return Boolean(urlRegex.test(urlString));
1730
- };
1731
-
1732
- /* eslint-disable no-await-in-loop */
1733
- /* eslint-disable radix */
1734
- /* eslint-disable no-param-reassign */
1735
- /* eslint-disable no-case-declarations */
1736
- /* eslint-disable no-plusplus */
1737
- /* eslint-disable no-else-return */
1738
- // eslint-disable-next-line consistent-return
1739
- const fixupColorCode = (colorCodeString) => {
1740
- if (Object.prototype.hasOwnProperty.call(colorNames, colorCodeString.toLowerCase())) {
1741
- const [red, green, blue] = colorNames[colorCodeString.toLowerCase()];
1742
- return rgbToHex(red, green, blue);
1743
- }
1744
- else if (rgbRegex.test(colorCodeString)) {
1745
- const matchedParts = colorCodeString.match(rgbRegex);
1746
- const red = matchedParts[1];
1747
- const green = matchedParts[2];
1748
- const blue = matchedParts[3];
1749
- return rgbToHex(red, green, blue);
1750
- }
1751
- else if (hslRegex.test(colorCodeString)) {
1752
- const matchedParts = colorCodeString.match(hslRegex);
1753
- const hue = matchedParts[1];
1754
- const saturation = matchedParts[2];
1755
- const luminosity = matchedParts[3];
1756
- return hslToHex(hue, saturation, luminosity);
1757
- }
1758
- else if (hexRegex.test(colorCodeString)) {
1759
- const matchedParts = colorCodeString.match(hexRegex);
1760
- return matchedParts[1];
1761
- }
1762
- else if (hex3Regex.test(colorCodeString)) {
1763
- const matchedParts = colorCodeString.match(hex3Regex);
1764
- const red = matchedParts[1];
1765
- const green = matchedParts[2];
1766
- const blue = matchedParts[3];
1767
- return hex3ToHex(red, green, blue);
1768
- }
1769
- else {
1770
- return '000000';
1771
- }
1772
- };
1773
- const buildRunFontFragment = (fontName = defaultFont) => fragment({ namespaceAlias: { w: namespaces.w } })
1774
- .ele('@w', 'rFonts')
1775
- .att('@w', 'ascii', fontName)
1776
- .att('@w', 'hAnsi', fontName)
1777
- .up();
1778
- const buildRunStyleFragment = (type = 'Hyperlink') => fragment({ namespaceAlias: { w: namespaces.w } })
1779
- .ele('@w', 'rStyle')
1780
- .att('@w', 'val', type)
1781
- .up();
1782
- const buildTableRowHeight = (tableRowHeight) => fragment({ namespaceAlias: { w: namespaces.w } })
1783
- .ele('@w', 'trHeight')
1784
- .att('@w', 'val', tableRowHeight)
1785
- .att('@w', 'hRule', 'atLeast')
1786
- .up();
1787
- const buildVerticalAlignment = (verticalAlignment) => {
1788
- if (verticalAlignment.toLowerCase() === 'middle') {
1789
- verticalAlignment = 'center';
1790
- }
1791
- return fragment({ namespaceAlias: { w: namespaces.w } })
1792
- .ele('@w', 'vAlign')
1793
- .att('@w', 'val', verticalAlignment)
1794
- .up();
1795
- };
1796
- const buildVerticalMerge = (verticalMerge = 'continue') => fragment({ namespaceAlias: { w: namespaces.w } })
1797
- .ele('@w', 'vMerge')
1798
- .att('@w', 'val', verticalMerge)
1799
- .up();
1800
- const buildColor = (colorCode) => fragment({ namespaceAlias: { w: namespaces.w } })
1801
- .ele('@w', 'color')
1802
- .att('@w', 'val', colorCode)
1803
- .up();
1804
- const buildFontSize = (fontSize) => fragment({ namespaceAlias: { w: namespaces.w } })
1805
- .ele('@w', 'sz')
1806
- .att('@w', 'val', fontSize)
1807
- .up();
1808
- const buildShading = (colorCode) => fragment({ namespaceAlias: { w: namespaces.w } })
1809
- .ele('@w', 'shd')
1810
- .att('@w', 'val', 'clear')
1811
- .att('@w', 'fill', colorCode)
1812
- .up();
1813
- const buildHighlight = (color = 'yellow') => fragment({ namespaceAlias: { w: namespaces.w } })
1814
- .ele('@w', 'highlight')
1815
- .att('@w', 'val', color)
1816
- .up();
1817
- const buildVertAlign = (type = 'baseline') => fragment({ namespaceAlias: { w: namespaces.w } })
1818
- .ele('@w', 'vertAlign')
1819
- .att('@w', 'val', type)
1820
- .up();
1821
- const buildStrike = () => fragment({ namespaceAlias: { w: namespaces.w } })
1822
- .ele('@w', 'strike')
1823
- .att('@w', 'val', true)
1824
- .up();
1825
- const buildBold = () => fragment({ namespaceAlias: { w: namespaces.w } })
1826
- .ele('@w', 'b')
1827
- .up();
1828
- const buildItalics = () => fragment({ namespaceAlias: { w: namespaces.w } })
1829
- .ele('@w', 'i')
1830
- .up();
1831
- const buildUnderline = (type = 'single') => fragment({ namespaceAlias: { w: namespaces.w } })
1832
- .ele('@w', 'u')
1833
- .att('@w', 'val', type)
1834
- .up();
1835
- const buildLineBreak = (type = 'textWrapping') => fragment({ namespaceAlias: { w: namespaces.w } })
1836
- .ele('@w', 'br')
1837
- .att('@w', 'type', type)
1838
- .up();
1839
- const buildBorder = (borderSide = 'top', borderSize = 0, borderSpacing = 0, borderColor = fixupColorCode('black'), borderStroke = 'single') => fragment({ namespaceAlias: { w: namespaces.w } })
1840
- .ele('@w', borderSide)
1841
- .att('@w', 'val', borderStroke)
1842
- .att('@w', 'sz', borderSize)
1843
- .att('@w', 'space', borderSpacing)
1844
- .att('@w', 'color', borderColor)
1845
- .up();
1846
- const buildTextElement = (text) => fragment({ namespaceAlias: { w: namespaces.w } })
1847
- .ele('@w', 't')
1848
- .att('@xml', 'space', 'preserve')
1849
- .txt(text)
1850
- .up();
1851
- // eslint-disable-next-line consistent-return
1852
- const fixupLineHeight = (lineHeight, fontSize) => {
1853
- // FIXME: If line height is anything other than a number
1854
- // eslint-disable-next-line no-restricted-globals
1855
- if (!isNaN(lineHeight)) {
1856
- if (fontSize) {
1857
- const actualLineHeight = +lineHeight * fontSize;
1858
- return HIPToTWIP(actualLineHeight);
1859
- }
1860
- else {
1861
- // 240 TWIP or 12 point is default line height
1862
- return +lineHeight * 240;
1863
- }
1864
- }
1865
- else {
1866
- // 240 TWIP or 12 point is default line height
1867
- return 240;
1868
- }
1869
- };
1870
- // eslint-disable-next-line consistent-return
1871
- const fixupFontSize$1 = (fontSizeString) => {
1872
- if (pointRegex.test(fontSizeString)) {
1873
- const matchedParts = fontSizeString.match(pointRegex);
1874
- // convert point to half point
1875
- return pointToHIP(matchedParts[1]);
1876
- }
1877
- else if (pixelRegex.test(fontSizeString)) {
1878
- const matchedParts = fontSizeString.match(pixelRegex);
1879
- // convert pixels to half point
1880
- return pixelToHIP(matchedParts[1]);
1881
- }
1882
- };
1883
- // eslint-disable-next-line consistent-return
1884
- const fixupRowHeight = (rowHeightString) => {
1885
- if (pointRegex.test(rowHeightString)) {
1886
- const matchedParts = rowHeightString.match(pointRegex);
1887
- // convert point to half point
1888
- return pointToTWIP(matchedParts[1]);
1889
- }
1890
- else if (pixelRegex.test(rowHeightString)) {
1891
- const matchedParts = rowHeightString.match(pixelRegex);
1892
- // convert pixels to half point
1893
- return pixelToTWIP(matchedParts[1]);
1894
- }
1895
- else if (cmRegex.test(rowHeightString)) {
1896
- const matchedParts = rowHeightString.match(cmRegex);
1897
- return cmToTWIP(matchedParts[1]);
1898
- }
1899
- else if (inchRegex.test(rowHeightString)) {
1900
- const matchedParts = rowHeightString.match(inchRegex);
1901
- return inchToTWIP(matchedParts[1]);
1902
- }
1903
- };
1904
- // eslint-disable-next-line consistent-return
1905
- const fixupColumnWidth = (columnWidthString) => {
1906
- if (pointRegex.test(columnWidthString)) {
1907
- const matchedParts = columnWidthString.match(pointRegex);
1908
- return pointToTWIP(matchedParts[1]);
1909
- }
1910
- else if (pixelRegex.test(columnWidthString)) {
1911
- const matchedParts = columnWidthString.match(pixelRegex);
1912
- return pixelToTWIP(matchedParts[1]);
1913
- }
1914
- else if (cmRegex.test(columnWidthString)) {
1915
- const matchedParts = columnWidthString.match(cmRegex);
1916
- return cmToTWIP(matchedParts[1]);
1917
- }
1918
- else if (inchRegex.test(columnWidthString)) {
1919
- const matchedParts = columnWidthString.match(inchRegex);
1920
- return inchToTWIP(matchedParts[1]);
1921
- }
1922
- };
1923
- // eslint-disable-next-line consistent-return
1924
- const fixupMargin = (marginString) => {
1925
- if (pointRegex.test(marginString)) {
1926
- const matchedParts = marginString.match(pointRegex);
1927
- // convert point to half point
1928
- return pointToTWIP(matchedParts[1]);
1929
- }
1930
- else if (pixelRegex.test(marginString)) {
1931
- const matchedParts = marginString.match(pixelRegex);
1932
- // convert pixels to half point
1933
- return pixelToTWIP(matchedParts[1]);
1934
- }
1935
- };
1936
- const modifiedStyleAttributesBuilder = (vNode, attributes, options) => {
1937
- const modifiedAttributes = { ...attributes };
1938
- // styles
1939
- if (isVNode(vNode) && vNode.properties && vNode.properties.style) {
1940
- if (vNode.properties.style.color && !colorlessColors.includes(vNode.properties.style.color)) {
1941
- modifiedAttributes.color = fixupColorCode(vNode.properties.style.color);
1942
- }
1943
- if (vNode.properties.style['background-color'] &&
1944
- !colorlessColors.includes(vNode.properties.style['background-color'])) {
1945
- modifiedAttributes.backgroundColor = fixupColorCode(vNode.properties.style['background-color']);
1946
- }
1947
- if (vNode.properties.style['vertical-align'] &&
1948
- verticalAlignValues.includes(vNode.properties.style['vertical-align'])) {
1949
- modifiedAttributes.verticalAlign = vNode.properties.style['vertical-align'];
1950
- }
1951
- if (vNode.properties.style['text-align'] &&
1952
- ['left', 'right', 'center', 'justify'].includes(vNode.properties.style['text-align'])) {
1953
- modifiedAttributes.textAlign = vNode.properties.style['text-align'];
1954
- }
1955
- // FIXME: remove bold check when other font weights are handled.
1956
- if (vNode.properties.style['font-weight'] && vNode.properties.style['font-weight'] === 'bold') {
1957
- modifiedAttributes.strong = vNode.properties.style['font-weight'];
1958
- }
1959
- if (vNode.properties.style['font-size']) {
1960
- modifiedAttributes.fontSize = fixupFontSize$1(vNode.properties.style['font-size']);
1961
- }
1962
- if (vNode.properties.style['line-height']) {
1963
- modifiedAttributes.lineHeight = fixupLineHeight(vNode.properties.style['line-height'], vNode.properties.style['font-size']
1964
- ? fixupFontSize$1(vNode.properties.style['font-size'])
1965
- : null);
1966
- }
1967
- if (vNode.properties.style['margin-left'] || vNode.properties.style['margin-right']) {
1968
- const leftMargin = fixupMargin(vNode.properties.style['margin-left']);
1969
- const rightMargin = fixupMargin(vNode.properties.style['margin-right']);
1970
- const indentation = {};
1971
- if (leftMargin) {
1972
- indentation.left = leftMargin;
1973
- }
1974
- if (rightMargin) {
1975
- indentation.right = rightMargin;
1976
- }
1977
- if (leftMargin || rightMargin) {
1978
- modifiedAttributes.indentation = indentation;
1979
- }
1980
- }
1981
- if (vNode.properties.style.display) {
1982
- modifiedAttributes.display = vNode.properties.style.display;
1983
- }
1984
- if (vNode.properties.style.width) {
1985
- modifiedAttributes.width = vNode.properties.style.width;
1986
- }
1987
- }
1988
- // paragraph only
1989
- if (options && options.isParagraph) {
1990
- if (isVNode(vNode) && vNode.tagName === 'blockquote') {
1991
- modifiedAttributes.indentation = { left: 284 };
1992
- modifiedAttributes.textAlign = 'justify';
1993
- }
1994
- else if (isVNode(vNode) && vNode.tagName === 'code') {
1995
- modifiedAttributes.highlightColor = 'lightGray';
1996
- }
1997
- else if (isVNode(vNode) && vNode.tagName === 'pre') {
1998
- modifiedAttributes.font = 'Courier';
1999
- }
2000
- }
2001
- return modifiedAttributes;
2002
- };
2003
- // html tag to formatting function
2004
- // options are passed to the formatting function if needed
2005
- const buildFormatting = (htmlTag, options) => {
2006
- switch (htmlTag) {
2007
- case 'strong':
2008
- case 'b':
2009
- return buildBold();
2010
- case 'em':
2011
- case 'i':
2012
- return buildItalics();
2013
- case 'ins':
2014
- case 'u':
2015
- return buildUnderline();
2016
- case 'strike':
2017
- case 'del':
2018
- case 's':
2019
- return buildStrike();
2020
- case 'sub':
2021
- return buildVertAlign('subscript');
2022
- case 'sup':
2023
- return buildVertAlign('superscript');
2024
- case 'mark':
2025
- return buildHighlight();
2026
- case 'code':
2027
- return buildHighlight('lightGray');
2028
- case 'highlightColor':
2029
- return buildHighlight(options && options.color ? options.color : 'lightGray');
2030
- case 'font':
2031
- case 'pre':
2032
- return buildRunFontFragment('Courier');
2033
- case 'color':
2034
- return buildColor(options && options.color ? options.color : 'black');
2035
- case 'backgroundColor':
2036
- return buildShading(options && options.color ? options.color : 'black');
2037
- case 'fontSize':
2038
- // does this need a unit of measure?
2039
- return buildFontSize(options && options.fontSize ? options.fontSize : 10);
2040
- case 'hyperlink':
2041
- return buildRunStyleFragment('Hyperlink');
2042
- }
2043
- return null;
2044
- };
2045
- const buildRunProperties = (attributes) => {
2046
- const runPropertiesFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'rPr');
2047
- if (attributes && attributes.constructor === Object) {
2048
- Object.keys(attributes).forEach((key) => {
2049
- const options = {};
2050
- if (key === 'color' || key === 'backgroundColor' || key === 'highlightColor') {
2051
- options.color = attributes[key];
2052
- }
2053
- if (key === 'fontSize') {
2054
- options.fontSize = attributes[key];
2055
- }
2056
- const formattingFragment = buildFormatting(key, options);
2057
- if (formattingFragment) {
2058
- runPropertiesFragment.import(formattingFragment);
2059
- }
2060
- });
2061
- }
2062
- runPropertiesFragment.up();
2063
- return runPropertiesFragment;
2064
- };
2065
- const buildRun = async (vNode, attributes, docxDocumentInstance) => {
2066
- const runFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'r');
2067
- const runPropertiesFragment = buildRunProperties(cloneDeep(attributes));
2068
- // case where we have recursive spans representing font changes
2069
- if (isVNode(vNode) && vNode.tagName === 'span') {
2070
- // eslint-disable-next-line no-use-before-define
2071
- return buildRunOrRuns(vNode, attributes, docxDocumentInstance);
2072
- }
2073
- if (isVNode(vNode) &&
2074
- [
2075
- 'strong',
2076
- 'b',
2077
- 'em',
2078
- 'i',
2079
- 'u',
2080
- 'ins',
2081
- 'strike',
2082
- 'del',
2083
- 's',
2084
- 'sub',
2085
- 'sup',
2086
- 'mark',
2087
- 'blockquote',
2088
- 'code',
2089
- 'pre',
2090
- ].includes(vNode.tagName)) {
2091
- const runFragmentsArray = [];
2092
- let vNodes = [vNode];
2093
- // create temp run fragments to split the paragraph into different runs
2094
- let tempAttributes = cloneDeep(attributes);
2095
- let tempRunFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'r');
2096
- while (vNodes.length) {
2097
- const tempVNode = vNodes.shift();
2098
- if (isVText(tempVNode)) {
2099
- const textFragment = buildTextElement(tempVNode.text);
2100
- const tempRunPropertiesFragment = buildRunProperties({ ...attributes, ...tempAttributes });
2101
- tempRunFragment.import(tempRunPropertiesFragment);
2102
- tempRunFragment.import(textFragment);
2103
- runFragmentsArray.push(tempRunFragment);
2104
- // re initialize temp run fragments with new fragment
2105
- tempAttributes = cloneDeep(attributes);
2106
- tempRunFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'r');
2107
- }
2108
- else if (isVNode(tempVNode)) {
2109
- if ([
2110
- 'strong',
2111
- 'b',
2112
- 'em',
2113
- 'i',
2114
- 'u',
2115
- 'ins',
2116
- 'strike',
2117
- 'del',
2118
- 's',
2119
- 'sub',
2120
- 'sup',
2121
- 'mark',
2122
- 'code',
2123
- 'pre',
2124
- ].includes(tempVNode.tagName)) {
2125
- tempAttributes = {};
2126
- switch (tempVNode.tagName) {
2127
- case 'strong':
2128
- case 'b':
2129
- tempAttributes.strong = true;
2130
- break;
2131
- case 'i':
2132
- tempAttributes.i = true;
2133
- break;
2134
- case 'u':
2135
- tempAttributes.u = true;
2136
- break;
2137
- case 'sub':
2138
- tempAttributes.sub = true;
2139
- break;
2140
- case 'sup':
2141
- tempAttributes.sup = true;
2142
- break;
2143
- }
2144
- const formattingFragment = buildFormatting(tempVNode);
2145
- if (formattingFragment) {
2146
- runPropertiesFragment.import(formattingFragment);
2147
- }
2148
- // go a layer deeper if there is a span somewhere in the children
2149
- }
2150
- else if (tempVNode.tagName === 'span') {
2151
- // eslint-disable-next-line no-use-before-define
2152
- const spanFragment = await buildRunOrRuns(tempVNode, { ...attributes, ...tempAttributes }, docxDocumentInstance);
2153
- // if spanFragment is an array, we need to add each fragment to the runFragmentsArray. If the fragment is an array, perform a depth first search on the array to add each fragment to the runFragmentsArray
2154
- if (Array.isArray(spanFragment)) {
2155
- spanFragment.flat(Infinity);
2156
- runFragmentsArray.push(...spanFragment);
2157
- }
2158
- else {
2159
- runFragmentsArray.push(spanFragment);
2160
- }
2161
- // do not slice and concat children since this is already accounted for in the buildRunOrRuns function
2162
- // eslint-disable-next-line no-continue
2163
- continue;
2164
- }
2165
- }
2166
- if (tempVNode.children && tempVNode.children.length) {
2167
- if (tempVNode.children.length > 1) {
2168
- attributes = { ...attributes, ...tempAttributes };
2169
- }
2170
- vNodes = tempVNode.children.slice().concat(vNodes);
2171
- }
2172
- }
2173
- if (runFragmentsArray.length) {
2174
- return runFragmentsArray;
2175
- }
2176
- }
2177
- runFragment.import(runPropertiesFragment);
2178
- if (isVText(vNode)) {
2179
- const textFragment = buildTextElement(vNode.text);
2180
- runFragment.import(textFragment);
2181
- }
2182
- else if (attributes && attributes.type === 'picture') {
2183
- let response = null;
2184
- const base64Uri = decodeURIComponent(vNode.properties.src);
2185
- if (base64Uri) {
2186
- response = docxDocumentInstance.createMediaFile(base64Uri);
2187
- }
2188
- if (response) {
2189
- docxDocumentInstance.zip
2190
- .folder('word')
2191
- .folder('media')
2192
- .file(response.fileNameWithExtension, Buffer.from(response.fileContent, 'base64'), {
2193
- createFolders: false,
2194
- });
2195
- const documentRelsId = docxDocumentInstance.createDocumentRelationships(docxDocumentInstance.relationshipFilename, imageType, `media/${response.fileNameWithExtension}`, internalRelationship);
2196
- attributes.inlineOrAnchored = true;
2197
- attributes.relationshipId = documentRelsId;
2198
- attributes.id = response.id;
2199
- attributes.fileContent = response.fileContent;
2200
- attributes.fileNameWithExtension = response.fileNameWithExtension;
2201
- }
2202
- const { type, inlineOrAnchored, ...otherAttributes } = attributes;
2203
- // eslint-disable-next-line no-use-before-define
2204
- const imageFragment = buildDrawing(inlineOrAnchored, type, otherAttributes);
2205
- runFragment.import(imageFragment);
2206
- }
2207
- else if (isVNode(vNode) && vNode.tagName === 'br') {
2208
- const lineBreakFragment = buildLineBreak();
2209
- runFragment.import(lineBreakFragment);
2210
- }
2211
- runFragment.up();
2212
- return runFragment;
2213
- };
2214
- const buildRunOrRuns = async (vNode, attributes, docxDocumentInstance) => {
2215
- if (isVNode(vNode) && vNode.tagName === 'span') {
2216
- let runFragments = [];
2217
- for (let index = 0; index < vNode.children.length; index++) {
2218
- const childVNode = vNode.children[index];
2219
- const modifiedAttributes = modifiedStyleAttributesBuilder(vNode, attributes);
2220
- const tempRunFragments = await buildRun(childVNode, modifiedAttributes, docxDocumentInstance);
2221
- runFragments = runFragments.concat(Array.isArray(tempRunFragments) ? tempRunFragments : [tempRunFragments]);
2222
- }
2223
- return runFragments;
2224
- }
2225
- else {
2226
- const tempRunFragments = await buildRun(vNode, attributes, docxDocumentInstance);
2227
- return tempRunFragments;
2228
- }
2229
- };
2230
- const buildRunOrHyperLink = async (vNode, attributes, docxDocumentInstance) => {
2231
- if (isVNode(vNode) && vNode.tagName === 'a') {
2232
- const relationshipId = docxDocumentInstance.createDocumentRelationships(docxDocumentInstance.relationshipFilename, hyperlinkType, vNode.properties && vNode.properties.href ? vNode.properties.href : '');
2233
- const hyperlinkFragment = fragment({ namespaceAlias: { w: namespaces.w, r: namespaces.r } })
2234
- .ele('@w', 'hyperlink')
2235
- .att('@r', 'id', `rId${relationshipId}`);
2236
- const modifiedAttributes = { ...attributes };
2237
- modifiedAttributes.hyperlink = true;
2238
- const runFragments = await buildRunOrRuns(vNode.children[0], modifiedAttributes, docxDocumentInstance);
2239
- if (Array.isArray(runFragments)) {
2240
- for (let index = 0; index < runFragments.length; index++) {
2241
- const runFragment = runFragments[index];
2242
- hyperlinkFragment.import(runFragment);
2243
- }
2244
- }
2245
- else {
2246
- hyperlinkFragment.import(runFragments);
2247
- }
2248
- hyperlinkFragment.up();
2249
- return hyperlinkFragment;
2250
- }
2251
- const runFragments = await buildRunOrRuns(vNode, attributes, docxDocumentInstance);
2252
- return runFragments;
2253
- };
2254
- const buildNumberingProperties = (levelId, numberingId) => fragment({ namespaceAlias: { w: namespaces.w } })
2255
- .ele('@w', 'numPr')
2256
- .ele('@w', 'ilvl')
2257
- .att('@w', 'val', String(levelId))
2258
- .up()
2259
- .ele('@w', 'numId')
2260
- .att('@w', 'val', String(numberingId))
2261
- .up()
2262
- .up();
2263
- const buildNumberingInstances = () => fragment({ namespaceAlias: { w: namespaces.w } })
2264
- .ele('@w', 'num')
2265
- .ele('@w', 'abstractNumId')
2266
- .up()
2267
- .up();
2268
- const buildSpacing = (lineSpacing, beforeSpacing, afterSpacing) => {
2269
- const spacingFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'spacing');
2270
- if (lineSpacing) {
2271
- spacingFragment.att('@w', 'line', lineSpacing);
2272
- }
2273
- if (beforeSpacing) {
2274
- spacingFragment.att('@w', 'before', beforeSpacing);
2275
- }
2276
- if (afterSpacing) {
2277
- spacingFragment.att('@w', 'after', afterSpacing);
2278
- }
2279
- spacingFragment.att('@w', 'lineRule', 'auto').up();
2280
- return spacingFragment;
2281
- };
2282
- const buildIndentation = ({ left, right }) => {
2283
- const indentationFragment = fragment({
2284
- namespaceAlias: { w: namespaces.w },
2285
- }).ele('@w', 'ind');
2286
- if (left) {
2287
- indentationFragment.att('@w', 'left', left);
2288
- }
2289
- if (right) {
2290
- indentationFragment.att('@w', 'right', right);
2291
- }
2292
- indentationFragment.up();
2293
- return indentationFragment;
2294
- };
2295
- const buildPStyle = (style = 'Normal') => fragment({ namespaceAlias: { w: namespaces.w } })
2296
- .ele('@w', 'pStyle')
2297
- .att('@w', 'val', style)
2298
- .up();
2299
- const buildHorizontalAlignment = (horizontalAlignment) => {
2300
- if (horizontalAlignment === 'justify') {
2301
- horizontalAlignment = 'both';
2302
- }
2303
- return fragment({ namespaceAlias: { w: namespaces.w } })
2304
- .ele('@w', 'jc')
2305
- .att('@w', 'val', horizontalAlignment)
2306
- .up();
2307
- };
2308
- const buildParagraphBorder = () => {
2309
- const paragraphBorderFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'pBdr');
2310
- const bordersObject = cloneDeep(paragraphBordersObject);
2311
- Object.keys(bordersObject).forEach((borderName) => {
2312
- if (bordersObject[borderName]) {
2313
- const { size, spacing, color } = bordersObject[borderName];
2314
- const borderFragment = buildBorder(borderName, size, spacing, color);
2315
- paragraphBorderFragment.import(borderFragment);
2316
- }
2317
- });
2318
- paragraphBorderFragment.up();
2319
- return paragraphBorderFragment;
2320
- };
2321
- const buildParagraphProperties = (attributes) => {
2322
- const paragraphPropertiesFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'pPr');
2323
- if (attributes && attributes.constructor === Object) {
2324
- Object.keys(attributes).forEach((key) => {
2325
- switch (key) {
2326
- case 'numbering':
2327
- const { levelId, numberingId } = attributes[key];
2328
- const numberingPropertiesFragment = buildNumberingProperties(levelId, numberingId);
2329
- paragraphPropertiesFragment.import(numberingPropertiesFragment);
2330
- // eslint-disable-next-line no-param-reassign
2331
- delete attributes.numbering;
2332
- break;
2333
- case 'textAlign':
2334
- const horizontalAlignmentFragment = buildHorizontalAlignment(attributes[key]);
2335
- paragraphPropertiesFragment.import(horizontalAlignmentFragment);
2336
- // eslint-disable-next-line no-param-reassign
2337
- delete attributes.textAlign;
2338
- break;
2339
- case 'backgroundColor':
2340
- // Add shading to Paragraph Properties only if display is block
2341
- // Essentially if background color needs to be across the row
2342
- if (attributes.display === 'block') {
2343
- const shadingFragment = buildShading(attributes[key]);
2344
- paragraphPropertiesFragment.import(shadingFragment);
2345
- // FIXME: Inner padding in case of shaded paragraphs.
2346
- const paragraphBorderFragment = buildParagraphBorder();
2347
- paragraphPropertiesFragment.import(paragraphBorderFragment);
2348
- // eslint-disable-next-line no-param-reassign
2349
- delete attributes.backgroundColor;
2350
- }
2351
- break;
2352
- case 'paragraphStyle':
2353
- const pStyleFragment = buildPStyle(attributes.paragraphStyle);
2354
- paragraphPropertiesFragment.import(pStyleFragment);
2355
- delete attributes.paragraphStyle;
2356
- break;
2357
- case 'indentation':
2358
- const indentationFragment = buildIndentation(attributes[key]);
2359
- paragraphPropertiesFragment.import(indentationFragment);
2360
- // eslint-disable-next-line no-param-reassign
2361
- delete attributes.indentation;
2362
- break;
2363
- }
2364
- });
2365
- const spacingFragment = buildSpacing(attributes.lineHeight, attributes.beforeSpacing, attributes.afterSpacing);
2366
- // eslint-disable-next-line no-param-reassign
2367
- delete attributes.lineHeight;
2368
- // eslint-disable-next-line no-param-reassign
2369
- delete attributes.beforeSpacing;
2370
- // eslint-disable-next-line no-param-reassign
2371
- delete attributes.afterSpacing;
2372
- paragraphPropertiesFragment.import(spacingFragment);
2373
- }
2374
- paragraphPropertiesFragment.up();
2375
- return paragraphPropertiesFragment;
2376
- };
2377
- const computeImageDimensions = (vNode, attributes) => {
2378
- const { maximumWidth, originalWidth, originalHeight } = attributes;
2379
- const aspectRatio = originalWidth / originalHeight;
2380
- const maximumWidthInEMU = TWIPToEMU(maximumWidth);
2381
- let originalWidthInEMU = pixelToEMU(originalWidth);
2382
- let originalHeightInEMU = pixelToEMU(originalHeight);
2383
- if (originalWidthInEMU > maximumWidthInEMU) {
2384
- originalWidthInEMU = maximumWidthInEMU;
2385
- originalHeightInEMU = Math.round(originalWidthInEMU / aspectRatio);
2386
- }
2387
- let modifiedHeight;
2388
- let modifiedWidth;
2389
- if (vNode.properties && vNode.properties.style) {
2390
- if (vNode.properties.style.width) {
2391
- if (vNode.properties.style.width !== 'auto') {
2392
- if (pixelRegex.test(vNode.properties.style.width)) {
2393
- modifiedWidth = pixelToEMU(vNode.properties.style.width.match(pixelRegex)[1]);
2394
- }
2395
- else if (percentageRegex.test(vNode.properties.style.width)) {
2396
- const percentageValue = vNode.properties.style.width.match(percentageRegex)[1];
2397
- modifiedWidth = Math.round((percentageValue / 100) * originalWidthInEMU);
2398
- }
2399
- }
2400
- else {
2401
- // eslint-disable-next-line no-lonely-if
2402
- if (vNode.properties.style.height && vNode.properties.style.height === 'auto') {
2403
- modifiedWidth = originalWidthInEMU;
2404
- modifiedHeight = originalHeightInEMU;
2405
- }
2406
- }
2407
- }
2408
- if (vNode.properties.style.height) {
2409
- if (vNode.properties.style.height !== 'auto') {
2410
- if (pixelRegex.test(vNode.properties.style.height)) {
2411
- modifiedHeight = pixelToEMU(vNode.properties.style.height.match(pixelRegex)[1]);
2412
- }
2413
- else if (percentageRegex.test(vNode.properties.style.height)) {
2414
- const percentageValue = vNode.properties.style.width.match(percentageRegex)[1];
2415
- modifiedHeight = Math.round((percentageValue / 100) * originalHeightInEMU);
2416
- if (!modifiedWidth) {
2417
- modifiedWidth = Math.round(modifiedHeight * aspectRatio);
2418
- }
2419
- }
2420
- }
2421
- else {
2422
- // eslint-disable-next-line no-lonely-if
2423
- if (modifiedWidth) {
2424
- if (!modifiedHeight) {
2425
- modifiedHeight = Math.round(modifiedWidth / aspectRatio);
2426
- }
2427
- }
2428
- else {
2429
- modifiedHeight = originalHeightInEMU;
2430
- modifiedWidth = originalWidthInEMU;
2431
- }
2432
- }
2433
- }
2434
- if (modifiedWidth && !modifiedHeight) {
2435
- modifiedHeight = Math.round(modifiedWidth / aspectRatio);
2436
- }
2437
- else if (modifiedHeight && !modifiedWidth) {
2438
- modifiedWidth = Math.round(modifiedHeight * aspectRatio);
2439
- }
2440
- }
2441
- else {
2442
- modifiedWidth = originalWidthInEMU;
2443
- modifiedHeight = originalHeightInEMU;
2444
- }
2445
- // eslint-disable-next-line no-param-reassign
2446
- attributes.width = modifiedWidth;
2447
- // eslint-disable-next-line no-param-reassign
2448
- attributes.height = modifiedHeight;
2449
- };
2450
- const buildParagraph = async (vNode, attributes, docxDocumentInstance) => {
2451
- const paragraphFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'p');
2452
- const modifiedAttributes = modifiedStyleAttributesBuilder(vNode, attributes, {
2453
- isParagraph: true,
2454
- });
2455
- const paragraphPropertiesFragment = buildParagraphProperties(modifiedAttributes);
2456
- paragraphFragment.import(paragraphPropertiesFragment);
2457
- if (isVNode(vNode) && vNodeHasChildren(vNode)) {
2458
- if ([
2459
- 'span',
2460
- 'strong',
2461
- 'b',
2462
- 'em',
2463
- 'i',
2464
- 'u',
2465
- 'ins',
2466
- 'strike',
2467
- 'del',
2468
- 's',
2469
- 'sub',
2470
- 'sup',
2471
- 'mark',
2472
- 'a',
2473
- 'code',
2474
- 'pre',
2475
- ].includes(vNode.tagName)) {
2476
- const runOrHyperlinkFragments = await buildRunOrHyperLink(vNode, modifiedAttributes, docxDocumentInstance);
2477
- if (Array.isArray(runOrHyperlinkFragments)) {
2478
- for (let iteratorIndex = 0; iteratorIndex < runOrHyperlinkFragments.length; iteratorIndex++) {
2479
- const runOrHyperlinkFragment = runOrHyperlinkFragments[iteratorIndex];
2480
- paragraphFragment.import(runOrHyperlinkFragment);
2481
- }
2482
- }
2483
- else {
2484
- paragraphFragment.import(runOrHyperlinkFragments);
2485
- }
2486
- }
2487
- else if (vNode.tagName === 'blockquote') {
2488
- const runFragmentOrFragments = await buildRun(vNode, attributes);
2489
- if (Array.isArray(runFragmentOrFragments)) {
2490
- for (let index = 0; index < runFragmentOrFragments.length; index++) {
2491
- paragraphFragment.import(runFragmentOrFragments[index]);
2492
- }
2493
- }
2494
- else {
2495
- paragraphFragment.import(runFragmentOrFragments);
2496
- }
2497
- }
2498
- else {
2499
- for (let index = 0; index < vNode.children.length; index++) {
2500
- const childVNode = vNode.children[index];
2501
- if (childVNode.tagName === 'img') {
2502
- let base64String;
2503
- const imageSource = childVNode.properties.src;
2504
- if (isValidUrl(imageSource)) {
2505
- base64String = await imageToBase64(imageSource).catch((error) => {
2506
- // eslint-disable-next-line no-console
2507
- console.warning(`skipping image download and conversion due to ${error}`);
2508
- });
2509
- if (base64String && mimeTypes.lookup(imageSource)) {
2510
- childVNode.properties.src = `data:${mimeTypes.lookup(imageSource)};base64, ${base64String}`;
2511
- }
2512
- else {
2513
- break;
2514
- }
2515
- }
2516
- else {
2517
- // eslint-disable-next-line no-useless-escape, prefer-destructuring
2518
- base64String = imageSource.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)[2];
2519
- }
2520
- const imageBuffer = Buffer.from(decodeURIComponent(base64String), 'base64');
2521
- const imageProperties = sizeOf(imageBuffer);
2522
- modifiedAttributes.maximumWidth =
2523
- modifiedAttributes.maximumWidth || docxDocumentInstance.availableDocumentSpace;
2524
- modifiedAttributes.originalWidth = imageProperties.width;
2525
- modifiedAttributes.originalHeight = imageProperties.height;
2526
- computeImageDimensions(childVNode, modifiedAttributes);
2527
- }
2528
- const runOrHyperlinkFragments = await buildRunOrHyperLink(childVNode, isVNode(childVNode) && childVNode.tagName === 'img'
2529
- ? { ...modifiedAttributes, type: 'picture' }
2530
- : modifiedAttributes, docxDocumentInstance);
2531
- if (Array.isArray(runOrHyperlinkFragments)) {
2532
- for (let iteratorIndex = 0; iteratorIndex < runOrHyperlinkFragments.length; iteratorIndex++) {
2533
- const runOrHyperlinkFragment = runOrHyperlinkFragments[iteratorIndex];
2534
- paragraphFragment.import(runOrHyperlinkFragment);
2535
- }
2536
- }
2537
- else {
2538
- paragraphFragment.import(runOrHyperlinkFragments);
2539
- }
2540
- }
2541
- }
2542
- }
2543
- else {
2544
- // In case paragraphs has to be rendered where vText is present. Eg. table-cell
2545
- // Or in case the vNode is something like img
2546
- if (isVNode(vNode) && vNode.tagName === 'img') {
2547
- const imageSource = vNode.properties.src;
2548
- let base64String = imageSource;
2549
- if (isValidUrl(imageSource)) {
2550
- base64String = await imageToBase64(imageSource).catch((error) => {
2551
- // eslint-disable-next-line no-console
2552
- console.warning(`skipping image download and conversion due to ${error}`);
2553
- });
2554
- if (base64String && mimeTypes.lookup(imageSource)) {
2555
- vNode.properties.src = `data:${mimeTypes.lookup(imageSource)};base64, ${base64String}`;
2556
- }
2557
- else {
2558
- paragraphFragment.up();
2559
- return paragraphFragment;
2560
- }
2561
- }
2562
- else {
2563
- // eslint-disable-next-line no-useless-escape, prefer-destructuring
2564
- base64String = base64String.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)[2];
2565
- }
2566
- const imageBuffer = Buffer.from(decodeURIComponent(base64String), 'base64');
2567
- const imageProperties = sizeOf(imageBuffer);
2568
- modifiedAttributes.maximumWidth =
2569
- modifiedAttributes.maximumWidth || docxDocumentInstance.availableDocumentSpace;
2570
- modifiedAttributes.originalWidth = imageProperties.width;
2571
- modifiedAttributes.originalHeight = imageProperties.height;
2572
- computeImageDimensions(vNode, modifiedAttributes);
2573
- }
2574
- const runFragments = await buildRunOrRuns(vNode, modifiedAttributes, docxDocumentInstance);
2575
- if (Array.isArray(runFragments)) {
2576
- for (let index = 0; index < runFragments.length; index++) {
2577
- const runFragment = runFragments[index];
2578
- paragraphFragment.import(runFragment);
2579
- }
2580
- }
2581
- else {
2582
- paragraphFragment.import(runFragments);
2583
- }
2584
- }
2585
- paragraphFragment.up();
2586
- return paragraphFragment;
2587
- };
2588
- const buildGridSpanFragment = (spanValue) => fragment({ namespaceAlias: { w: namespaces.w } })
2589
- .ele('@w', 'gridSpan')
2590
- .att('@w', 'val', spanValue)
2591
- .up();
2592
- const buildTableCellSpacing = (cellSpacing = 0) => fragment({ namespaceAlias: { w: namespaces.w } })
2593
- .ele('@w', 'tblCellSpacing')
2594
- .att('@w', 'w', cellSpacing)
2595
- .att('@w', 'type', 'dxa')
2596
- .up();
2597
- const buildTableCellBorders = (tableCellBorder) => {
2598
- const tableCellBordersFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tcBorders');
2599
- const { color, stroke, ...borders } = tableCellBorder;
2600
- Object.keys(borders).forEach((border) => {
2601
- if (tableCellBorder[border]) {
2602
- const borderFragment = buildBorder(border, tableCellBorder[border], 0, color, stroke);
2603
- tableCellBordersFragment.import(borderFragment);
2604
- }
2605
- });
2606
- tableCellBordersFragment.up();
2607
- return tableCellBordersFragment;
2608
- };
2609
- const buildTableCellWidth = (tableCellWidth) => fragment({ namespaceAlias: { w: namespaces.w } })
2610
- .ele('@w', 'tcW')
2611
- .att('@w', 'w', fixupColumnWidth(tableCellWidth))
2612
- .att('@w', 'type', 'dxa')
2613
- .up();
2614
- const buildTableCellProperties = (attributes) => {
2615
- const tableCellPropertiesFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tcPr');
2616
- if (attributes && attributes.constructor === Object) {
2617
- Object.keys(attributes).forEach((key) => {
2618
- switch (key) {
2619
- case 'backgroundColor':
2620
- const shadingFragment = buildShading(attributes[key]);
2621
- tableCellPropertiesFragment.import(shadingFragment);
2622
- // eslint-disable-next-line no-param-reassign
2623
- delete attributes.backgroundColor;
2624
- break;
2625
- case 'verticalAlign':
2626
- const verticalAlignmentFragment = buildVerticalAlignment(attributes[key]);
2627
- tableCellPropertiesFragment.import(verticalAlignmentFragment);
2628
- // eslint-disable-next-line no-param-reassign
2629
- delete attributes.verticalAlign;
2630
- break;
2631
- case 'colSpan':
2632
- const gridSpanFragment = buildGridSpanFragment(attributes[key]);
2633
- tableCellPropertiesFragment.import(gridSpanFragment);
2634
- // eslint-disable-next-line no-param-reassign
2635
- delete attributes.colSpan;
2636
- break;
2637
- case 'tableCellBorder':
2638
- const tableCellBorderFragment = buildTableCellBorders(attributes[key]);
2639
- tableCellPropertiesFragment.import(tableCellBorderFragment);
2640
- // eslint-disable-next-line no-param-reassign
2641
- delete attributes.tableCellBorder;
2642
- break;
2643
- case 'rowSpan':
2644
- const verticalMergeFragment = buildVerticalMerge(attributes[key]);
2645
- tableCellPropertiesFragment.import(verticalMergeFragment);
2646
- delete attributes.rowSpan;
2647
- break;
2648
- case 'width':
2649
- const widthFragment = buildTableCellWidth(attributes[key]);
2650
- tableCellPropertiesFragment.import(widthFragment);
2651
- delete attributes.width;
2652
- break;
2653
- }
2654
- });
2655
- }
2656
- tableCellPropertiesFragment.up();
2657
- return tableCellPropertiesFragment;
2658
- };
2659
- const fixupTableCellBorder = (vNode, attributes) => {
2660
- if (Object.prototype.hasOwnProperty.call(vNode.properties.style, 'border')) {
2661
- if (vNode.properties.style.border === 'none' || vNode.properties.style.border === 0) {
2662
- attributes.tableCellBorder = {};
2663
- }
2664
- else {
2665
- // eslint-disable-next-line no-use-before-define
2666
- const [borderSize, borderStroke, borderColor] = cssBorderParser(vNode.properties.style.border);
2667
- attributes.tableCellBorder = {
2668
- top: borderSize,
2669
- left: borderSize,
2670
- bottom: borderSize,
2671
- right: borderSize,
2672
- color: borderColor,
2673
- stroke: borderStroke,
2674
- };
2675
- }
2676
- }
2677
- if (vNode.properties.style['border-top'] && vNode.properties.style['border-top'] === '0') {
2678
- attributes.tableCellBorder = {
2679
- ...attributes.tableCellBorder,
2680
- top: 0,
2681
- };
2682
- }
2683
- else if (vNode.properties.style['border-top'] && vNode.properties.style['border-top'] !== '0') {
2684
- // eslint-disable-next-line no-use-before-define
2685
- const [borderSize, borderStroke, borderColor] = cssBorderParser(vNode.properties.style['border-top']);
2686
- attributes.tableCellBorder = {
2687
- ...attributes.tableCellBorder,
2688
- top: borderSize,
2689
- color: borderColor,
2690
- stroke: borderStroke,
2691
- };
2692
- }
2693
- if (vNode.properties.style['border-left'] && vNode.properties.style['border-left'] === '0') {
2694
- attributes.tableCellBorder = {
2695
- ...attributes.tableCellBorder,
2696
- left: 0,
2697
- };
2698
- }
2699
- else if (vNode.properties.style['border-left'] &&
2700
- vNode.properties.style['border-left'] !== '0') {
2701
- // eslint-disable-next-line no-use-before-define
2702
- const [borderSize, borderStroke, borderColor] = cssBorderParser(vNode.properties.style['border-left']);
2703
- attributes.tableCellBorder = {
2704
- ...attributes.tableCellBorder,
2705
- left: borderSize,
2706
- color: borderColor,
2707
- stroke: borderStroke,
2708
- };
2709
- }
2710
- if (vNode.properties.style['border-bottom'] && vNode.properties.style['border-bottom'] === '0') {
2711
- attributes.tableCellBorder = {
2712
- ...attributes.tableCellBorder,
2713
- bottom: 0,
2714
- };
2715
- }
2716
- else if (vNode.properties.style['border-bottom'] &&
2717
- vNode.properties.style['border-bottom'] !== '0') {
2718
- // eslint-disable-next-line no-use-before-define
2719
- const [borderSize, borderStroke, borderColor] = cssBorderParser(vNode.properties.style['border-bottom']);
2720
- attributes.tableCellBorder = {
2721
- ...attributes.tableCellBorder,
2722
- bottom: borderSize,
2723
- color: borderColor,
2724
- stroke: borderStroke,
2725
- };
2726
- }
2727
- if (vNode.properties.style['border-right'] && vNode.properties.style['border-right'] === '0') {
2728
- attributes.tableCellBorder = {
2729
- ...attributes.tableCellBorder,
2730
- right: 0,
2731
- };
2732
- }
2733
- else if (vNode.properties.style['border-right'] &&
2734
- vNode.properties.style['border-right'] !== '0') {
2735
- // eslint-disable-next-line no-use-before-define
2736
- const [borderSize, borderStroke, borderColor] = cssBorderParser(vNode.properties.style['border-right']);
2737
- attributes.tableCellBorder = {
2738
- ...attributes.tableCellBorder,
2739
- right: borderSize,
2740
- color: borderColor,
2741
- stroke: borderStroke,
2742
- };
2743
- }
2744
- };
2745
- const buildTableCell = async (vNode, attributes, rowSpanMap, columnIndex, docxDocumentInstance) => {
2746
- const tableCellFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tc');
2747
- let modifiedAttributes = { ...attributes };
2748
- if (isVNode(vNode) && vNode.properties) {
2749
- if (vNode.properties.rowSpan) {
2750
- rowSpanMap.set(columnIndex.index, { rowSpan: vNode.properties.rowSpan - 1, colSpan: 0 });
2751
- modifiedAttributes.rowSpan = 'restart';
2752
- }
2753
- else {
2754
- const previousSpanObject = rowSpanMap.get(columnIndex.index);
2755
- rowSpanMap.set(columnIndex.index,
2756
- // eslint-disable-next-line prefer-object-spread
2757
- Object.assign({}, previousSpanObject, {
2758
- rowSpan: 0,
2759
- colSpan: (previousSpanObject && previousSpanObject.colSpan) || 0,
2760
- }));
2761
- }
2762
- if (vNode.properties.colSpan ||
2763
- (vNode.properties.style && vNode.properties.style['column-span'])) {
2764
- modifiedAttributes.colSpan =
2765
- vNode.properties.colSpan ||
2766
- (vNode.properties.style && vNode.properties.style['column-span']);
2767
- const previousSpanObject = rowSpanMap.get(columnIndex.index);
2768
- rowSpanMap.set(columnIndex.index,
2769
- // eslint-disable-next-line prefer-object-spread
2770
- Object.assign({}, previousSpanObject, {
2771
- colSpan: parseInt(modifiedAttributes.colSpan) || 0,
2772
- }));
2773
- columnIndex.index += parseInt(modifiedAttributes.colSpan) - 1;
2774
- }
2775
- if (vNode.properties.style) {
2776
- modifiedAttributes = {
2777
- ...modifiedAttributes,
2778
- ...modifiedStyleAttributesBuilder(vNode, attributes),
2779
- };
2780
- fixupTableCellBorder(vNode, modifiedAttributes);
2781
- }
2782
- }
2783
- const tableCellPropertiesFragment = buildTableCellProperties(modifiedAttributes);
2784
- tableCellFragment.import(tableCellPropertiesFragment);
2785
- if (vNodeHasChildren(vNode)) {
2786
- for (let index = 0; index < vNode.children.length; index++) {
2787
- const childVNode = vNode.children[index];
2788
- if (isVNode(childVNode) && childVNode.tagName === 'img') {
2789
- const imageFragment = await buildImage(docxDocumentInstance, childVNode, modifiedAttributes.maximumWidth);
2790
- if (imageFragment) {
2791
- tableCellFragment.import(imageFragment);
2792
- }
2793
- }
2794
- else if (isVNode(childVNode) && childVNode.tagName === 'figure') {
2795
- if (vNodeHasChildren(childVNode)) {
2796
- // eslint-disable-next-line no-plusplus
2797
- for (let iteratorIndex = 0; iteratorIndex < childVNode.children.length; iteratorIndex++) {
2798
- const grandChildVNode = childVNode.children[iteratorIndex];
2799
- if (grandChildVNode.tagName === 'img') {
2800
- const imageFragment = await buildImage(docxDocumentInstance, grandChildVNode, modifiedAttributes.maximumWidth);
2801
- if (imageFragment) {
2802
- tableCellFragment.import(imageFragment);
2803
- }
2804
- }
2805
- }
2806
- }
2807
- }
2808
- else if (isVNode(childVNode) && ['ul', 'ol'].includes(childVNode.tagName)) {
2809
- // render list in table
2810
- if (vNodeHasChildren(childVNode)) {
2811
- await buildList(childVNode, docxDocumentInstance, tableCellFragment);
2812
- }
2813
- }
2814
- else {
2815
- const paragraphFragment = await buildParagraph(childVNode, modifiedAttributes, docxDocumentInstance);
2816
- tableCellFragment.import(paragraphFragment);
2817
- }
2818
- }
2819
- }
2820
- else {
2821
- // TODO: Figure out why building with buildParagraph() isn't working
2822
- const paragraphFragment = fragment({ namespaceAlias: { w: namespaces.w } })
2823
- .ele('@w', 'p')
2824
- .up();
2825
- tableCellFragment.import(paragraphFragment);
2826
- }
2827
- tableCellFragment.up();
2828
- return tableCellFragment;
2829
- };
2830
- const buildRowSpanCell = (rowSpanMap, columnIndex, attributes) => {
2831
- const rowSpanCellFragments = [];
2832
- let spanObject = rowSpanMap.get(columnIndex.index);
2833
- while (spanObject && spanObject.rowSpan) {
2834
- const rowSpanCellFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tc');
2835
- const tableCellPropertiesFragment = buildTableCellProperties({
2836
- ...attributes,
2837
- rowSpan: 'continue',
2838
- colSpan: spanObject.colSpan ? spanObject.colSpan : 0,
2839
- });
2840
- rowSpanCellFragment.import(tableCellPropertiesFragment);
2841
- const paragraphFragment = fragment({ namespaceAlias: { w: namespaces.w } })
2842
- .ele('@w', 'p')
2843
- .up();
2844
- rowSpanCellFragment.import(paragraphFragment);
2845
- rowSpanCellFragment.up();
2846
- rowSpanCellFragments.push(rowSpanCellFragment);
2847
- if (spanObject.rowSpan - 1 === 0) {
2848
- rowSpanMap.delete(columnIndex.index);
2849
- }
2850
- else {
2851
- rowSpanMap.set(columnIndex.index, {
2852
- rowSpan: spanObject.rowSpan - 1,
2853
- colSpan: spanObject.colSpan || 0,
2854
- });
2855
- }
2856
- columnIndex.index += spanObject.colSpan || 1;
2857
- spanObject = rowSpanMap.get(columnIndex.index);
2858
- }
2859
- return rowSpanCellFragments;
2860
- };
2861
- const buildTableRowProperties = (attributes) => {
2862
- const tableRowPropertiesFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'trPr');
2863
- if (attributes && attributes.constructor === Object) {
2864
- Object.keys(attributes).forEach((key) => {
2865
- switch (key) {
2866
- case 'tableRowHeight':
2867
- const tableRowHeightFragment = buildTableRowHeight(attributes[key]);
2868
- tableRowPropertiesFragment.import(tableRowHeightFragment);
2869
- // eslint-disable-next-line no-param-reassign
2870
- delete attributes.tableRowHeight;
2871
- break;
2872
- case 'rowCantSplit':
2873
- if (attributes.rowCantSplit) {
2874
- const cantSplitFragment = fragment({ namespaceAlias: { w: namespaces.w } })
2875
- .ele('@w', 'cantSplit')
2876
- .up();
2877
- tableRowPropertiesFragment.import(cantSplitFragment);
2878
- // eslint-disable-next-line no-param-reassign
2879
- delete attributes.rowCantSplit;
2880
- }
2881
- break;
2882
- }
2883
- });
2884
- }
2885
- tableRowPropertiesFragment.up();
2886
- return tableRowPropertiesFragment;
2887
- };
2888
- const buildTableRow = async (vNode, attributes, rowSpanMap, docxDocumentInstance) => {
2889
- const tableRowFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tr');
2890
- const modifiedAttributes = { ...attributes };
2891
- if (isVNode(vNode) && vNode.properties) {
2892
- // FIXME: find a better way to get row height from cell style
2893
- if ((vNode.properties.style && vNode.properties.style.height) ||
2894
- (vNode.children[0] &&
2895
- isVNode(vNode.children[0]) &&
2896
- vNode.children[0].properties.style &&
2897
- vNode.children[0].properties.style.height)) {
2898
- modifiedAttributes.tableRowHeight = fixupRowHeight((vNode.properties.style && vNode.properties.style.height) ||
2899
- (vNode.children[0] &&
2900
- isVNode(vNode.children[0]) &&
2901
- vNode.children[0].properties.style &&
2902
- vNode.children[0].properties.style.height
2903
- ? vNode.children[0].properties.style.height
2904
- : undefined));
2905
- }
2906
- if (vNode.properties.style) {
2907
- fixupTableCellBorder(vNode, modifiedAttributes);
2908
- }
2909
- }
2910
- const tableRowPropertiesFragment = buildTableRowProperties(modifiedAttributes);
2911
- tableRowFragment.import(tableRowPropertiesFragment);
2912
- const columnIndex = { index: 0 };
2913
- if (vNodeHasChildren(vNode)) {
2914
- const tableColumns = vNode.children.filter((childVNode) => ['td', 'th'].includes(childVNode.tagName));
2915
- const maximumColumnWidth = docxDocumentInstance.availableDocumentSpace / tableColumns.length;
2916
- // eslint-disable-next-line no-restricted-syntax
2917
- for (const column of tableColumns) {
2918
- const rowSpanCellFragments = buildRowSpanCell(rowSpanMap, columnIndex, modifiedAttributes);
2919
- if (Array.isArray(rowSpanCellFragments)) {
2920
- for (let iteratorIndex = 0; iteratorIndex < rowSpanCellFragments.length; iteratorIndex++) {
2921
- const rowSpanCellFragment = rowSpanCellFragments[iteratorIndex];
2922
- tableRowFragment.import(rowSpanCellFragment);
2923
- }
2924
- }
2925
- const tableCellFragment = await buildTableCell(column, { ...modifiedAttributes, maximumWidth: maximumColumnWidth }, rowSpanMap, columnIndex, docxDocumentInstance);
2926
- columnIndex.index++;
2927
- tableRowFragment.import(tableCellFragment);
2928
- }
2929
- }
2930
- if (columnIndex.index < rowSpanMap.size) {
2931
- const rowSpanCellFragments = buildRowSpanCell(rowSpanMap, columnIndex, modifiedAttributes);
2932
- if (Array.isArray(rowSpanCellFragments)) {
2933
- for (let iteratorIndex = 0; iteratorIndex < rowSpanCellFragments.length; iteratorIndex++) {
2934
- const rowSpanCellFragment = rowSpanCellFragments[iteratorIndex];
2935
- tableRowFragment.import(rowSpanCellFragment);
2936
- }
2937
- }
2938
- }
2939
- tableRowFragment.up();
2940
- return tableRowFragment;
2941
- };
2942
- const buildTableGridCol = (gridWidth) => fragment({ namespaceAlias: { w: namespaces.w } })
2943
- .ele('@w', 'gridCol')
2944
- .att('@w', 'w', String(gridWidth));
2945
- const buildTableGrid = (vNode, attributes) => {
2946
- const tableGridFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tblGrid');
2947
- if (vNodeHasChildren(vNode)) {
2948
- const gridColumns = vNode.children.filter((childVNode) => childVNode.tagName === 'col');
2949
- const gridWidth = attributes.maximumWidth / gridColumns.length;
2950
- for (let index = 0; index < gridColumns.length; index++) {
2951
- const tableGridColFragment = buildTableGridCol(gridWidth);
2952
- tableGridFragment.import(tableGridColFragment);
2953
- }
2954
- }
2955
- tableGridFragment.up();
2956
- return tableGridFragment;
2957
- };
2958
- const buildTableGridFromTableRow = (vNode, attributes) => {
2959
- const tableGridFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tblGrid');
2960
- if (vNodeHasChildren(vNode)) {
2961
- const numberOfGridColumns = vNode.children.reduce((accumulator, childVNode) => {
2962
- const colSpan = childVNode.properties.colSpan ||
2963
- (childVNode.properties.style && childVNode.properties.style['column-span']);
2964
- return accumulator + (colSpan ? parseInt(colSpan) : 1);
2965
- }, 0);
2966
- const gridWidth = attributes.maximumWidth / numberOfGridColumns;
2967
- for (let index = 0; index < numberOfGridColumns; index++) {
2968
- const tableGridColFragment = buildTableGridCol(gridWidth);
2969
- tableGridFragment.import(tableGridColFragment);
2970
- }
2971
- }
2972
- tableGridFragment.up();
2973
- return tableGridFragment;
2974
- };
2975
- const buildTableBorders = (tableBorder) => {
2976
- const tableBordersFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tblBorders');
2977
- const { color, stroke, ...borders } = tableBorder;
2978
- Object.keys(borders).forEach((border) => {
2979
- if (borders[border]) {
2980
- const borderFragment = buildBorder(border, borders[border], 0, color, stroke);
2981
- tableBordersFragment.import(borderFragment);
2982
- }
2983
- });
2984
- tableBordersFragment.up();
2985
- return tableBordersFragment;
2986
- };
2987
- const buildTableWidth = (tableWidth) => fragment({ namespaceAlias: { w: namespaces.w } })
2988
- .ele('@w', 'tblW')
2989
- .att('@w', 'type', 'dxa')
2990
- .att('@w', 'w', String(tableWidth))
2991
- .up();
2992
- const buildCellMargin = (side, margin) => fragment({ namespaceAlias: { w: namespaces.w } })
2993
- .ele('@w', side)
2994
- .att('@w', 'type', 'dxa')
2995
- .att('@w', 'w', String(margin))
2996
- .up();
2997
- const buildTableCellMargins = (margin) => {
2998
- const tableCellMarFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tblCellMar');
2999
- ['top', 'bottom'].forEach((side) => {
3000
- const marginFragment = buildCellMargin(side, margin / 2);
3001
- tableCellMarFragment.import(marginFragment);
3002
- });
3003
- ['left', 'right'].forEach((side) => {
3004
- const marginFragment = buildCellMargin(side, margin);
3005
- tableCellMarFragment.import(marginFragment);
3006
- });
3007
- return tableCellMarFragment;
3008
- };
3009
- const buildTableProperties = (attributes) => {
3010
- const tablePropertiesFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tblPr');
3011
- if (attributes && attributes.constructor === Object) {
3012
- Object.keys(attributes).forEach((key) => {
3013
- switch (key) {
3014
- case 'tableBorder':
3015
- const tableBordersFragment = buildTableBorders(attributes[key]);
3016
- tablePropertiesFragment.import(tableBordersFragment);
3017
- // eslint-disable-next-line no-param-reassign
3018
- delete attributes.tableBorder;
3019
- break;
3020
- case 'tableCellSpacing':
3021
- const tableCellSpacingFragment = buildTableCellSpacing(attributes[key]);
3022
- tablePropertiesFragment.import(tableCellSpacingFragment);
3023
- // eslint-disable-next-line no-param-reassign
3024
- delete attributes.tableCellSpacing;
3025
- break;
3026
- case 'width':
3027
- if (attributes[key]) {
3028
- const tableWidthFragment = buildTableWidth(attributes[key]);
3029
- tablePropertiesFragment.import(tableWidthFragment);
3030
- }
3031
- // eslint-disable-next-line no-param-reassign
3032
- delete attributes.width;
3033
- break;
3034
- }
3035
- });
3036
- }
3037
- const tableCellMarginFragment = buildTableCellMargins(160);
3038
- tablePropertiesFragment.import(tableCellMarginFragment);
3039
- // by default, all tables are center aligned.
3040
- const alignmentFragment = buildHorizontalAlignment('center');
3041
- tablePropertiesFragment.import(alignmentFragment);
3042
- tablePropertiesFragment.up();
3043
- return tablePropertiesFragment;
3044
- };
3045
- const cssBorderParser = (borderString) => {
3046
- let [size, stroke, color] = borderString.split(' ');
3047
- if (pointRegex.test(size)) {
3048
- const matchedParts = size.match(pointRegex);
3049
- // convert point to eighth of a point
3050
- size = pointToEIP(matchedParts[1]);
3051
- }
3052
- else if (pixelRegex.test(size)) {
3053
- const matchedParts = size.match(pixelRegex);
3054
- // convert pixels to eighth of a point
3055
- size = pixelToEIP(matchedParts[1]);
3056
- }
3057
- stroke = stroke && ['dashed', 'dotted', 'double'].includes(stroke) ? stroke : 'single';
3058
- color = color && fixupColorCode(color).toUpperCase();
3059
- return [size, stroke, color];
3060
- };
3061
- const buildTable = async (vNode, attributes, docxDocumentInstance) => {
3062
- const tableFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tbl');
3063
- const modifiedAttributes = { ...attributes };
3064
- if (isVNode(vNode) && vNode.properties) {
3065
- const tableAttributes = vNode.properties.attributes || {};
3066
- const tableStyles = vNode.properties.style || {};
3067
- const tableBorders = {};
3068
- const tableCellBorders = {};
3069
- let [borderSize, borderStrike, borderColor] = [2, 'single', '000000'];
3070
- // eslint-disable-next-line no-restricted-globals
3071
- if (!isNaN(tableAttributes.border)) {
3072
- borderSize = parseInt(tableAttributes.border, 10);
3073
- }
3074
- // css style overrides table border properties
3075
- if (tableStyles.border) {
3076
- const [cssSize, cssStroke, cssColor] = cssBorderParser(tableStyles.border);
3077
- borderSize = cssSize || borderSize;
3078
- borderColor = cssColor || borderColor;
3079
- borderStrike = cssStroke || borderStrike;
3080
- }
3081
- tableBorders.top = borderSize;
3082
- tableBorders.bottom = borderSize;
3083
- tableBorders.left = borderSize;
3084
- tableBorders.right = borderSize;
3085
- tableBorders.stroke = borderStrike;
3086
- tableBorders.color = borderColor;
3087
- if (tableStyles['border-collapse'] === 'collapse') {
3088
- tableBorders.insideV = borderSize;
3089
- tableBorders.insideH = borderSize;
3090
- }
3091
- else {
3092
- tableBorders.insideV = 0;
3093
- tableBorders.insideH = 0;
3094
- tableCellBorders.top = 1;
3095
- tableCellBorders.bottom = 1;
3096
- tableCellBorders.left = 1;
3097
- tableCellBorders.right = 1;
3098
- }
3099
- modifiedAttributes.tableBorder = tableBorders;
3100
- modifiedAttributes.tableCellSpacing = 0;
3101
- if (Object.keys(tableCellBorders).length) {
3102
- modifiedAttributes.tableCellBorder = tableCellBorders;
3103
- }
3104
- let minimumWidth;
3105
- let maximumWidth;
3106
- let width;
3107
- // Calculate minimum width of table
3108
- if (pixelRegex.test(tableStyles['min-width'])) {
3109
- minimumWidth = pixelToTWIP(tableStyles['min-width'].match(pixelRegex)[1]);
3110
- }
3111
- else if (percentageRegex.test(tableStyles['min-width'])) {
3112
- const percentageValue = tableStyles['min-width'].match(percentageRegex)[1];
3113
- minimumWidth = Math.round((percentageValue / 100) * attributes.maximumWidth);
3114
- }
3115
- // Calculate maximum width of table
3116
- if (pixelRegex.test(tableStyles['max-width'])) {
3117
- pixelRegex.lastIndex = 0;
3118
- maximumWidth = pixelToTWIP(tableStyles['max-width'].match(pixelRegex)[1]);
3119
- }
3120
- else if (percentageRegex.test(tableStyles['max-width'])) {
3121
- percentageRegex.lastIndex = 0;
3122
- const percentageValue = tableStyles['max-width'].match(percentageRegex)[1];
3123
- maximumWidth = Math.round((percentageValue / 100) * attributes.maximumWidth);
3124
- }
3125
- // Calculate specified width of table
3126
- if (pixelRegex.test(tableStyles.width)) {
3127
- pixelRegex.lastIndex = 0;
3128
- width = pixelToTWIP(tableStyles.width.match(pixelRegex)[1]);
3129
- }
3130
- else if (percentageRegex.test(tableStyles.width)) {
3131
- percentageRegex.lastIndex = 0;
3132
- const percentageValue = tableStyles.width.match(percentageRegex)[1];
3133
- width = Math.round((percentageValue / 100) * attributes.maximumWidth);
3134
- }
3135
- // If width isn't supplied, we should have min-width as the width.
3136
- if (width) {
3137
- modifiedAttributes.width = width;
3138
- if (maximumWidth) {
3139
- modifiedAttributes.width = Math.min(modifiedAttributes.width, maximumWidth);
3140
- }
3141
- if (minimumWidth) {
3142
- modifiedAttributes.width = Math.max(modifiedAttributes.width, minimumWidth);
3143
- }
3144
- }
3145
- else if (minimumWidth) {
3146
- modifiedAttributes.width = minimumWidth;
3147
- }
3148
- if (modifiedAttributes.width) {
3149
- modifiedAttributes.width = Math.min(modifiedAttributes.width, attributes.maximumWidth);
3150
- }
3151
- }
3152
- const tablePropertiesFragment = buildTableProperties(modifiedAttributes);
3153
- tableFragment.import(tablePropertiesFragment);
3154
- const rowSpanMap = new Map();
3155
- if (vNodeHasChildren(vNode)) {
3156
- for (let index = 0; index < vNode.children.length; index++) {
3157
- const childVNode = vNode.children[index];
3158
- if (childVNode.tagName === 'colgroup') {
3159
- const tableGridFragment = buildTableGrid(childVNode, modifiedAttributes);
3160
- tableFragment.import(tableGridFragment);
3161
- }
3162
- else if (childVNode.tagName === 'thead') {
3163
- for (let iteratorIndex = 0; iteratorIndex < childVNode.children.length; iteratorIndex++) {
3164
- const grandChildVNode = childVNode.children[iteratorIndex];
3165
- if (grandChildVNode.tagName === 'tr') {
3166
- if (iteratorIndex === 0) {
3167
- const tableGridFragment = buildTableGridFromTableRow(grandChildVNode, modifiedAttributes);
3168
- tableFragment.import(tableGridFragment);
3169
- }
3170
- const tableRowFragment = await buildTableRow(grandChildVNode, modifiedAttributes, rowSpanMap, docxDocumentInstance);
3171
- tableFragment.import(tableRowFragment);
3172
- }
3173
- }
3174
- }
3175
- else if (childVNode.tagName === 'tbody') {
3176
- for (let iteratorIndex = 0; iteratorIndex < childVNode.children.length; iteratorIndex++) {
3177
- const grandChildVNode = childVNode.children[iteratorIndex];
3178
- if (grandChildVNode.tagName === 'tr') {
3179
- if (iteratorIndex === 0) {
3180
- const tableGridFragment = buildTableGridFromTableRow(grandChildVNode, modifiedAttributes);
3181
- tableFragment.import(tableGridFragment);
3182
- }
3183
- const tableRowFragment = await buildTableRow(grandChildVNode, modifiedAttributes, rowSpanMap, docxDocumentInstance);
3184
- tableFragment.import(tableRowFragment);
3185
- }
3186
- }
3187
- }
3188
- else if (childVNode.tagName === 'tr') {
3189
- if (index === 0) {
3190
- const tableGridFragment = buildTableGridFromTableRow(childVNode, modifiedAttributes);
3191
- tableFragment.import(tableGridFragment);
3192
- }
3193
- const tableRowFragment = await buildTableRow(childVNode, modifiedAttributes, rowSpanMap, docxDocumentInstance);
3194
- tableFragment.import(tableRowFragment);
3195
- }
3196
- }
3197
- }
3198
- tableFragment.up();
3199
- return tableFragment;
3200
- };
3201
- const buildPresetGeometry = () => fragment({ namespaceAlias: { a: namespaces.a } })
3202
- .ele('@a', 'prstGeom')
3203
- .att('prst', 'rect')
3204
- .up();
3205
- const buildExtents = ({ width, height }) => fragment({ namespaceAlias: { a: namespaces.a } })
3206
- .ele('@a', 'ext')
3207
- .att('cx', width)
3208
- .att('cy', height)
3209
- .up();
3210
- const buildOffset = () => fragment({ namespaceAlias: { a: namespaces.a } })
3211
- .ele('@a', 'off')
3212
- .att('x', '0')
3213
- .att('y', '0')
3214
- .up();
3215
- const buildGraphicFrameTransform = (attributes) => {
3216
- const graphicFrameTransformFragment = fragment({ namespaceAlias: { a: namespaces.a } }).ele('@a', 'xfrm');
3217
- const offsetFragment = buildOffset();
3218
- graphicFrameTransformFragment.import(offsetFragment);
3219
- const extentsFragment = buildExtents(attributes);
3220
- graphicFrameTransformFragment.import(extentsFragment);
3221
- graphicFrameTransformFragment.up();
3222
- return graphicFrameTransformFragment;
3223
- };
3224
- const buildShapeProperties = (attributes) => {
3225
- const shapeProperties = fragment({ namespaceAlias: { pic: namespaces.pic } }).ele('@pic', 'spPr');
3226
- const graphicFrameTransformFragment = buildGraphicFrameTransform(attributes);
3227
- shapeProperties.import(graphicFrameTransformFragment);
3228
- const presetGeometryFragment = buildPresetGeometry();
3229
- shapeProperties.import(presetGeometryFragment);
3230
- shapeProperties.up();
3231
- return shapeProperties;
3232
- };
3233
- const buildFillRect = () => fragment({ namespaceAlias: { a: namespaces.a } })
3234
- .ele('@a', 'fillRect')
3235
- .up();
3236
- const buildStretch = () => {
3237
- const stretchFragment = fragment({ namespaceAlias: { a: namespaces.a } }).ele('@a', 'stretch');
3238
- const fillRectFragment = buildFillRect();
3239
- stretchFragment.import(fillRectFragment);
3240
- stretchFragment.up();
3241
- return stretchFragment;
3242
- };
3243
- const buildSrcRectFragment = () => fragment({ namespaceAlias: { a: namespaces.a } })
3244
- .ele('@a', 'srcRect')
3245
- .att('b', '0')
3246
- .att('l', '0')
3247
- .att('r', '0')
3248
- .att('t', '0')
3249
- .up();
3250
- const buildBinaryLargeImageOrPicture = (relationshipId) => fragment({
3251
- namespaceAlias: { a: namespaces.a, r: namespaces.r },
3252
- })
3253
- .ele('@a', 'blip')
3254
- .att('@r', 'embed', `rId${relationshipId}`)
3255
- // FIXME: possible values 'email', 'none', 'print', 'hqprint', 'screen'
3256
- .att('cstate', 'print')
3257
- .up();
3258
- const buildBinaryLargeImageOrPictureFill = (relationshipId) => {
3259
- const binaryLargeImageOrPictureFillFragment = fragment({
3260
- namespaceAlias: { pic: namespaces.pic },
3261
- }).ele('@pic', 'blipFill');
3262
- const binaryLargeImageOrPictureFragment = buildBinaryLargeImageOrPicture(relationshipId);
3263
- binaryLargeImageOrPictureFillFragment.import(binaryLargeImageOrPictureFragment);
3264
- const srcRectFragment = buildSrcRectFragment();
3265
- binaryLargeImageOrPictureFillFragment.import(srcRectFragment);
3266
- const stretchFragment = buildStretch();
3267
- binaryLargeImageOrPictureFillFragment.import(stretchFragment);
3268
- binaryLargeImageOrPictureFillFragment.up();
3269
- return binaryLargeImageOrPictureFillFragment;
3270
- };
3271
- const buildNonVisualPictureDrawingProperties = () => fragment({ namespaceAlias: { pic: namespaces.pic } })
3272
- .ele('@pic', 'cNvPicPr')
3273
- .up();
3274
- const buildNonVisualDrawingProperties = (pictureId, pictureNameWithExtension, pictureDescription = '') => fragment({ namespaceAlias: { pic: namespaces.pic } })
3275
- .ele('@pic', 'cNvPr')
3276
- .att('id', pictureId)
3277
- .att('name', pictureNameWithExtension)
3278
- .att('descr', pictureDescription)
3279
- .up();
3280
- const buildNonVisualPictureProperties = (pictureId, pictureNameWithExtension, pictureDescription) => {
3281
- const nonVisualPicturePropertiesFragment = fragment({
3282
- namespaceAlias: { pic: namespaces.pic },
3283
- }).ele('@pic', 'nvPicPr');
3284
- // TODO: Handle picture attributes
3285
- const nonVisualDrawingPropertiesFragment = buildNonVisualDrawingProperties(pictureId, pictureNameWithExtension, pictureDescription);
3286
- nonVisualPicturePropertiesFragment.import(nonVisualDrawingPropertiesFragment);
3287
- const nonVisualPictureDrawingPropertiesFragment = buildNonVisualPictureDrawingProperties();
3288
- nonVisualPicturePropertiesFragment.import(nonVisualPictureDrawingPropertiesFragment);
3289
- nonVisualPicturePropertiesFragment.up();
3290
- return nonVisualPicturePropertiesFragment;
3291
- };
3292
- const buildPicture = ({ id, fileNameWithExtension, description, relationshipId, width, height, }) => {
3293
- const pictureFragment = fragment({ namespaceAlias: { pic: namespaces.pic } }).ele('@pic', 'pic');
3294
- const nonVisualPicturePropertiesFragment = buildNonVisualPictureProperties(id, fileNameWithExtension, description);
3295
- pictureFragment.import(nonVisualPicturePropertiesFragment);
3296
- const binaryLargeImageOrPictureFill = buildBinaryLargeImageOrPictureFill(relationshipId);
3297
- pictureFragment.import(binaryLargeImageOrPictureFill);
3298
- const shapeProperties = buildShapeProperties({ width, height });
3299
- pictureFragment.import(shapeProperties);
3300
- pictureFragment.up();
3301
- return pictureFragment;
3302
- };
3303
- const buildGraphicData = (graphicType, attributes) => {
3304
- const graphicDataFragment = fragment({ namespaceAlias: { a: namespaces.a } })
3305
- .ele('@a', 'graphicData')
3306
- .att('uri', 'http://schemas.openxmlformats.org/drawingml/2006/picture');
3307
- if (graphicType === 'picture') {
3308
- const pictureFragment = buildPicture(attributes);
3309
- graphicDataFragment.import(pictureFragment);
3310
- }
3311
- graphicDataFragment.up();
3312
- return graphicDataFragment;
3313
- };
3314
- const buildGraphic = (graphicType, attributes) => {
3315
- const graphicFragment = fragment({ namespaceAlias: { a: namespaces.a } }).ele('@a', 'graphic');
3316
- // TODO: Handle drawing type
3317
- const graphicDataFragment = buildGraphicData(graphicType, attributes);
3318
- graphicFragment.import(graphicDataFragment);
3319
- graphicFragment.up();
3320
- return graphicFragment;
3321
- };
3322
- const buildDrawingObjectNonVisualProperties = (pictureId, pictureName) => fragment({ namespaceAlias: { wp: namespaces.wp } })
3323
- .ele('@wp', 'docPr')
3324
- .att('id', pictureId)
3325
- .att('name', pictureName)
3326
- .up();
3327
- const buildWrapSquare = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3328
- .ele('@wp', 'wrapSquare')
3329
- .att('wrapText', 'bothSides')
3330
- .att('distB', '228600')
3331
- .att('distT', '228600')
3332
- .att('distL', '228600')
3333
- .att('distR', '228600')
3334
- .up();
3335
- // eslint-disable-next-line no-unused-vars
3336
- const buildWrapNone = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3337
- .ele('@wp', 'wrapNone')
3338
- .up();
3339
- const buildEffectExtentFragment = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3340
- .ele('@wp', 'effectExtent')
3341
- .att('b', '0')
3342
- .att('l', '0')
3343
- .att('r', '0')
3344
- .att('t', '0')
3345
- .up();
3346
- const buildExtent = ({ width, height }) => fragment({ namespaceAlias: { wp: namespaces.wp } })
3347
- .ele('@wp', 'extent')
3348
- .att('cx', width)
3349
- .att('cy', height)
3350
- .up();
3351
- const buildPositionV = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3352
- .ele('@wp', 'positionV')
3353
- .att('relativeFrom', 'paragraph')
3354
- .ele('@wp', 'posOffset')
3355
- .txt('19050')
3356
- .up()
3357
- .up();
3358
- const buildPositionH = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3359
- .ele('@wp', 'positionH')
3360
- .att('relativeFrom', 'column')
3361
- .ele('@wp', 'posOffset')
3362
- .txt('19050')
3363
- .up()
3364
- .up();
3365
- const buildSimplePos = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3366
- .ele('@wp', 'simplePos')
3367
- .att('x', '0')
3368
- .att('y', '0')
3369
- .up();
3370
- const buildAnchoredDrawing = (graphicType, attributes) => {
3371
- const anchoredDrawingFragment = fragment({ namespaceAlias: { wp: namespaces.wp } })
3372
- .ele('@wp', 'anchor')
3373
- .att('distB', '0')
3374
- .att('distL', '0')
3375
- .att('distR', '0')
3376
- .att('distT', '0')
3377
- .att('relativeHeight', '0')
3378
- .att('behindDoc', 'false')
3379
- .att('locked', 'true')
3380
- .att('layoutInCell', 'true')
3381
- .att('allowOverlap', 'false')
3382
- .att('simplePos', 'false');
3383
- // Even though simplePos isnt supported by Word 2007 simplePos is required.
3384
- const simplePosFragment = buildSimplePos();
3385
- anchoredDrawingFragment.import(simplePosFragment);
3386
- const positionHFragment = buildPositionH();
3387
- anchoredDrawingFragment.import(positionHFragment);
3388
- const positionVFragment = buildPositionV();
3389
- anchoredDrawingFragment.import(positionVFragment);
3390
- const extentFragment = buildExtent({ width: attributes.width, height: attributes.height });
3391
- anchoredDrawingFragment.import(extentFragment);
3392
- const effectExtentFragment = buildEffectExtentFragment();
3393
- anchoredDrawingFragment.import(effectExtentFragment);
3394
- const wrapSquareFragment = buildWrapSquare();
3395
- anchoredDrawingFragment.import(wrapSquareFragment);
3396
- const drawingObjectNonVisualPropertiesFragment = buildDrawingObjectNonVisualProperties(attributes.id, attributes.fileNameWithExtension);
3397
- anchoredDrawingFragment.import(drawingObjectNonVisualPropertiesFragment);
3398
- const graphicFragment = buildGraphic(graphicType, attributes);
3399
- anchoredDrawingFragment.import(graphicFragment);
3400
- anchoredDrawingFragment.up();
3401
- return anchoredDrawingFragment;
3402
- };
3403
- const buildInlineDrawing = (graphicType, attributes) => {
3404
- const inlineDrawingFragment = fragment({ namespaceAlias: { wp: namespaces.wp } })
3405
- .ele('@wp', 'inline')
3406
- .att('distB', '0')
3407
- .att('distL', '0')
3408
- .att('distR', '0')
3409
- .att('distT', '0');
3410
- const extentFragment = buildExtent({ width: attributes.width, height: attributes.height });
3411
- inlineDrawingFragment.import(extentFragment);
3412
- const effectExtentFragment = buildEffectExtentFragment();
3413
- inlineDrawingFragment.import(effectExtentFragment);
3414
- const drawingObjectNonVisualPropertiesFragment = buildDrawingObjectNonVisualProperties(attributes.id, attributes.fileNameWithExtension);
3415
- inlineDrawingFragment.import(drawingObjectNonVisualPropertiesFragment);
3416
- const graphicFragment = buildGraphic(graphicType, attributes);
3417
- inlineDrawingFragment.import(graphicFragment);
3418
- inlineDrawingFragment.up();
3419
- return inlineDrawingFragment;
3420
- };
3421
- const buildDrawing = (inlineOrAnchored = false, graphicType, attributes) => {
3422
- const drawingFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'drawing');
3423
- const inlineOrAnchoredDrawingFragment = inlineOrAnchored
3424
- ? buildInlineDrawing(graphicType, attributes)
3425
- : buildAnchoredDrawing(graphicType, attributes);
3426
- drawingFragment.import(inlineOrAnchoredDrawingFragment);
3427
- drawingFragment.up();
3428
- return drawingFragment;
3429
- };
3430
- // eslint-disable-next-line consistent-return, no-shadow
3431
- const buildImage = async (docxDocumentInstance, vNode, maximumWidth = null) => {
3432
- let response = null;
3433
- let base64Uri = null;
3434
- try {
3435
- const imageSource = vNode.properties.src;
3436
- if (isValidUrl(imageSource)) {
3437
- const base64String = await imageToBase64(imageSource).catch((error) => {
3438
- // eslint-disable-next-line no-console
3439
- console.warning(`skipping image download and conversion due to ${error}`);
3440
- });
3441
- if (base64String) {
3442
- base64Uri = `data:${mimeTypes.lookup(imageSource)};base64, ${base64String}`;
3443
- }
3444
- }
3445
- else {
3446
- base64Uri = decodeURIComponent(vNode.properties.src);
3447
- }
3448
- if (base64Uri) {
3449
- response = docxDocumentInstance.createMediaFile(base64Uri);
3450
- }
3451
- }
3452
- catch (error) {
3453
- // NOOP
3454
- }
3455
- if (response) {
3456
- docxDocumentInstance.zip
3457
- .folder('word')
3458
- .folder('media')
3459
- .file(response.fileNameWithExtension, Buffer.from(response.fileContent, 'base64'), {
3460
- createFolders: false,
3461
- });
3462
- const documentRelsId = docxDocumentInstance.createDocumentRelationships(docxDocumentInstance.relationshipFilename, imageType, `media/${response.fileNameWithExtension}`, internalRelationship);
3463
- const imageBuffer = Buffer.from(response.fileContent, 'base64');
3464
- const imageProperties = sizeOf(imageBuffer);
3465
- const imageFragment = await xmlBuilder.buildParagraph(vNode, {
3466
- type: 'picture',
3467
- inlineOrAnchored: true,
3468
- relationshipId: documentRelsId,
3469
- ...response,
3470
- maximumWidth: maximumWidth || docxDocumentInstance.availableDocumentSpace,
3471
- originalWidth: imageProperties.width,
3472
- originalHeight: imageProperties.height,
3473
- }, docxDocumentInstance);
3474
- return imageFragment;
3475
- }
3476
- };
3477
- const buildList = async (vNode, docxDocumentInstance, xmlFragment) => {
3478
- const listElements = [];
3479
- let vNodeObjects = [
3480
- {
3481
- node: vNode,
3482
- level: 0,
3483
- type: vNode.tagName,
3484
- numberingId: docxDocumentInstance.createNumbering(vNode.tagName, vNode.properties),
3485
- },
3486
- ];
3487
- while (vNodeObjects.length) {
3488
- const tempVNodeObject = vNodeObjects.shift();
3489
- if (isVText(tempVNodeObject.node) ||
3490
- (isVNode(tempVNodeObject.node) && !['ul', 'ol', 'li'].includes(tempVNodeObject.node.tagName))) {
3491
- const paragraphFragment = await xmlBuilder.buildParagraph(tempVNodeObject.node, {
3492
- numbering: { levelId: tempVNodeObject.level, numberingId: tempVNodeObject.numberingId },
3493
- }, docxDocumentInstance);
3494
- xmlFragment.import(paragraphFragment);
3495
- }
3496
- if (tempVNodeObject.node.children &&
3497
- tempVNodeObject.node.children.length &&
3498
- ['ul', 'ol', 'li'].includes(tempVNodeObject.node.tagName)) {
3499
- const tempVNodeObjects = tempVNodeObject.node.children.reduce((accumulator, childVNode) => {
3500
- if (['ul', 'ol'].includes(childVNode.tagName)) {
3501
- accumulator.push({
3502
- node: childVNode,
3503
- level: tempVNodeObject.level + 1,
3504
- type: childVNode.tagName,
3505
- numberingId: docxDocumentInstance.createNumbering(childVNode.tagName, childVNode.properties),
3506
- });
3507
- }
3508
- else {
3509
- // eslint-disable-next-line no-lonely-if
3510
- if (accumulator.length > 0 &&
3511
- isVNode(accumulator[accumulator.length - 1].node) &&
3512
- accumulator[accumulator.length - 1].node.tagName.toLowerCase() === 'p') {
3513
- accumulator[accumulator.length - 1].node.children.push(childVNode);
3514
- }
3515
- else {
3516
- const paragraphVNode = new VNode('p', null,
3517
- // eslint-disable-next-line no-nested-ternary
3518
- isVText(childVNode)
3519
- ? [childVNode]
3520
- : // eslint-disable-next-line no-nested-ternary
3521
- isVNode(childVNode)
3522
- ? childVNode.tagName.toLowerCase() === 'li'
3523
- ? [...childVNode.children]
3524
- : [childVNode]
3525
- : []);
3526
- accumulator.push({
3527
- // eslint-disable-next-line prettier/prettier, no-nested-ternary
3528
- node: isVNode(childVNode)
3529
- ? // eslint-disable-next-line prettier/prettier, no-nested-ternary
3530
- childVNode.tagName.toLowerCase() === 'li'
3531
- ? childVNode
3532
- : childVNode.tagName.toLowerCase() !== 'p'
3533
- ? paragraphVNode
3534
- : childVNode
3535
- : // eslint-disable-next-line prettier/prettier
3536
- paragraphVNode,
3537
- level: tempVNodeObject.level,
3538
- type: tempVNodeObject.type,
3539
- numberingId: tempVNodeObject.numberingId,
3540
- });
3541
- }
3542
- }
3543
- return accumulator;
3544
- }, []);
3545
- vNodeObjects = tempVNodeObjects.concat(vNodeObjects);
3546
- }
3547
- }
3548
- return listElements;
3549
- };
3550
-
3551
- /* eslint-disable no-await-in-loop */
3552
- /* eslint-disable no-case-declarations */
3553
- const convertHTML$1 = HTMLToVDOM({
3554
- VNode: VNode$1,
3555
- VText,
3556
- });
3557
- async function findXMLEquivalent(docxDocumentInstance, vNode, xmlFragment) {
3558
- if (vNode.tagName === 'div' &&
3559
- (vNode.properties.attributes.class === 'page-break' ||
3560
- (vNode.properties.style && vNode.properties.style['page-break-after']))) {
3561
- const paragraphFragment = fragment({ namespaceAlias: { w: namespaces.w } })
3562
- .ele('@w', 'p')
3563
- .ele('@w', 'r')
3564
- .ele('@w', 'br')
3565
- .att('@w', 'type', 'page')
3566
- .up()
3567
- .up()
3568
- .up();
3569
- xmlFragment.import(paragraphFragment);
3570
- return;
3571
- }
3572
- switch (vNode.tagName) {
3573
- case 'h1':
3574
- case 'h2':
3575
- case 'h3':
3576
- case 'h4':
3577
- case 'h5':
3578
- case 'h6':
3579
- const headingFragment = await buildParagraph(vNode, {
3580
- paragraphStyle: `Heading${vNode.tagName[1]}`,
3581
- }, docxDocumentInstance);
3582
- xmlFragment.import(headingFragment);
3583
- return;
3584
- case 'span':
3585
- case 'strong':
3586
- case 'b':
3587
- case 'em':
3588
- case 'i':
3589
- case 'u':
3590
- case 'ins':
3591
- case 'strike':
3592
- case 'del':
3593
- case 's':
3594
- case 'sub':
3595
- case 'sup':
3596
- case 'mark':
3597
- case 'p':
3598
- case 'a':
3599
- case 'blockquote':
3600
- case 'code':
3601
- case 'pre':
3602
- const paragraphFragment = await buildParagraph(vNode, {}, docxDocumentInstance);
3603
- xmlFragment.import(paragraphFragment);
3604
- return;
3605
- case 'figure':
3606
- if (vNodeHasChildren(vNode)) {
3607
- // eslint-disable-next-line no-plusplus
3608
- for (let index = 0; index < vNode.children.length; index++) {
3609
- const childVNode = vNode.children[index];
3610
- if (childVNode.tagName === 'table') {
3611
- const tableFragment = await buildTable(childVNode, {
3612
- maximumWidth: docxDocumentInstance.availableDocumentSpace,
3613
- rowCantSplit: docxDocumentInstance.tableRowCantSplit,
3614
- }, docxDocumentInstance);
3615
- xmlFragment.import(tableFragment);
3616
- // Adding empty paragraph for space after table
3617
- const emptyParagraphFragment = await buildParagraph(null, {});
3618
- xmlFragment.import(emptyParagraphFragment);
3619
- }
3620
- else if (childVNode.tagName === 'img') {
3621
- const imageFragment = await buildImage(docxDocumentInstance, childVNode);
3622
- if (imageFragment) {
3623
- xmlFragment.import(imageFragment);
3624
- }
3625
- }
3626
- }
3627
- }
3628
- return;
3629
- case 'table':
3630
- const tableFragment = await buildTable(vNode, {
3631
- maximumWidth: docxDocumentInstance.availableDocumentSpace,
3632
- rowCantSplit: docxDocumentInstance.tableRowCantSplit,
3633
- }, docxDocumentInstance);
3634
- xmlFragment.import(tableFragment);
3635
- // Adding empty paragraph for space after table
3636
- const emptyParagraphFragment = await buildParagraph(null, {});
3637
- xmlFragment.import(emptyParagraphFragment);
3638
- return;
3639
- case 'ol':
3640
- case 'ul':
3641
- await buildList(vNode, docxDocumentInstance, xmlFragment);
3642
- return;
3643
- case 'img':
3644
- const imageFragment = await buildImage(docxDocumentInstance, vNode);
3645
- if (imageFragment) {
3646
- xmlFragment.import(imageFragment);
3647
- }
3648
- return;
3649
- case 'br':
3650
- const linebreakFragment = await buildParagraph(null, {});
3651
- xmlFragment.import(linebreakFragment);
3652
- return;
3653
- }
3654
- if (vNodeHasChildren(vNode)) {
3655
- // eslint-disable-next-line no-plusplus
3656
- for (let index = 0; index < vNode.children.length; index++) {
3657
- const childVNode = vNode.children[index];
3658
- // eslint-disable-next-line no-use-before-define
3659
- await convertVTreeToXML(docxDocumentInstance, childVNode, xmlFragment);
3660
- }
3661
- }
3662
- }
3663
- // eslint-disable-next-line consistent-return
3664
- async function convertVTreeToXML(docxDocumentInstance, vTree, xmlFragment) {
3665
- if (!vTree) {
3666
- // eslint-disable-next-line no-useless-return
3667
- return '';
3668
- }
3669
- if (Array.isArray(vTree) && vTree.length) {
3670
- // eslint-disable-next-line no-plusplus
3671
- for (let index = 0; index < vTree.length; index++) {
3672
- const vNode = vTree[index];
3673
- await convertVTreeToXML(docxDocumentInstance, vNode, xmlFragment);
3674
- }
3675
- }
3676
- else if (isVNode(vTree)) {
3677
- await findXMLEquivalent(docxDocumentInstance, vTree, xmlFragment);
3678
- }
3679
- else if (isVText(vTree)) {
3680
- buildTextElement(xmlFragment, escape(String(vTree.text)));
3681
- }
3682
- return xmlFragment;
3683
- }
3684
- async function renderDocumentFile(docxDocumentInstance) {
3685
- const vTree = convertHTML$1(docxDocumentInstance.htmlString);
3686
- const xmlFragment = fragment({ namespaceAlias: { w: namespaces.w } });
3687
- const populatedXmlFragment = await convertVTreeToXML(docxDocumentInstance, vTree, xmlFragment);
3688
- return populatedXmlFragment;
3689
- }
3690
-
3691
- /* eslint-disable import/prefer-default-export */
3692
-
3693
- class ListStyleBuilder {
3694
- // defaults is an object passed in from constants.js / numbering with the following properties:
3695
- // defaultOrderedListStyleType: 'decimal' (unless otherwise specified)
3696
- constructor(defaults) {
3697
- this.defaults = defaults || { defaultOrderedListStyleType: 'decimal' };
3698
- }
3699
- // eslint-disable-next-line class-methods-use-this
3700
- getListStyleType(listType) {
3701
- switch (listType) {
3702
- case 'upper-roman':
3703
- return 'upperRoman';
3704
- case 'lower-roman':
3705
- return 'lowerRoman';
3706
- case 'upper-alpha':
3707
- case 'upper-alpha-bracket-end':
3708
- return 'upperLetter';
3709
- case 'lower-alpha':
3710
- case 'lower-alpha-bracket-end':
3711
- return 'lowerLetter';
3712
- case 'decimal':
3713
- case 'decimal-bracket':
3714
- return 'decimal';
3715
- default:
3716
- return this.defaults.defaultOrderedListStyleType;
3717
- }
3718
- }
3719
- getListPrefixSuffix(style, lvl) {
3720
- let listType = this.defaults.defaultOrderedListStyleType;
3721
- if (style && style['list-style-type']) {
3722
- listType = style['list-style-type'];
3723
- }
3724
- switch (listType) {
3725
- case 'upper-roman':
3726
- case 'lower-roman':
3727
- case 'upper-alpha':
3728
- case 'lower-alpha':
3729
- return `%${lvl + 1}.`;
3730
- case 'upper-alpha-bracket-end':
3731
- case 'lower-alpha-bracket-end':
3732
- case 'decimal-bracket-end':
3733
- return `%${lvl + 1})`;
3734
- case 'decimal-bracket':
3735
- return `(%${lvl + 1})`;
3736
- case 'decimal':
3737
- default:
3738
- return `%${lvl + 1}.`;
3739
- }
3740
- }
3741
- }
3742
-
3743
- function generateContentTypesFragments(contentTypesXML, type, objects) {
3744
- if (objects && Array.isArray(objects)) {
3745
- objects.forEach((object) => {
3746
- const contentTypesFragment = fragment({ defaultNamespace: { ele: namespaces.contentTypes } })
3747
- .ele('Override')
3748
- .att('PartName', `/word/${type}${object[`${type}Id`]}.xml`)
3749
- .att('ContentType', `application/vnd.openxmlformats-officedocument.wordprocessingml.${type}+xml`)
3750
- .up();
3751
- contentTypesXML.root().import(contentTypesFragment);
3752
- });
3753
- }
3754
- }
3755
- function generateSectionReferenceXML(documentXML, documentSectionType, objects, isEnabled) {
3756
- if (isEnabled && objects && Array.isArray(objects) && objects.length) {
3757
- const xmlFragment = fragment();
3758
- objects.forEach(({ relationshipId, type }) => {
3759
- const objectFragment = fragment({ namespaceAlias: { w: namespaces.w, r: namespaces.r } })
3760
- .ele('@w', `${documentSectionType}Reference`)
3761
- .att('@r', 'id', `rId${relationshipId}`)
3762
- .att('@w', 'type', type)
3763
- .up();
3764
- xmlFragment.import(objectFragment);
3765
- });
3766
- documentXML.root().first().first().import(xmlFragment);
3767
- }
3768
- }
3769
- function generateXMLString(xmlString) {
3770
- const xmlDocumentString = create({ encoding: 'UTF-8', standalone: true }, xmlString);
3771
- return xmlDocumentString.toString({ prettyPrint: true });
3772
- }
3773
- async function generateSectionXML(vTree, type = 'header') {
3774
- debugger;
3775
- const sectionXML = create({
3776
- encoding: 'UTF-8',
3777
- standalone: true,
3778
- namespaceAlias: {
3779
- a: namespaces.a,
3780
- cdr: namespaces.cdr,
3781
- o: namespaces.o,
3782
- pic: namespaces.pic,
3783
- r: namespaces.r,
3784
- v: namespaces.v,
3785
- ve: namespaces.ve,
3786
- vt: namespaces.vt,
3787
- w: namespaces.w,
3788
- w10: namespaces.w10,
3789
- wp: namespaces.wp,
3790
- wne: namespaces.wne
3791
- },
3792
- }).ele('@w', type === 'header' ? 'hdr' : 'ftr');
3793
- const XMLFragment = fragment();
3794
- await convertVTreeToXML(this, vTree, XMLFragment);
3795
- if (type === 'footer' && XMLFragment.first().node.tagName === 'p' && this.pageNumber) {
3796
- XMLFragment.first().import(fragment({ namespaceAlias: { w: namespaces.w } })
3797
- .ele('@w', 'fldSimple')
3798
- .att('@w', 'instr', 'PAGE')
3799
- .ele('@w', 'r')
3800
- .up()
3801
- .up());
3802
- }
3803
- sectionXML.root().import(XMLFragment);
3804
- const referenceName = type === 'header' ? 'Header' : 'Footer';
3805
- this[`last${referenceName}Id`] += 1;
3806
- return { [`${type}Id`]: this[`last${referenceName}Id`], [`${type}XML`]: sectionXML };
3807
- }
3808
- class DocxDocument {
3809
- constructor(properties) {
3810
- this.zip = properties.zip;
3811
- this.htmlString = properties.htmlString;
3812
- this.orientation = properties.orientation;
3813
- this.pageSize = properties.pageSize || defaultDocumentOptions.pageSize;
3814
- const isPortraitOrientation = this.orientation === defaultOrientation;
3815
- const height = this.pageSize.height ? this.pageSize.height : landscapeHeight;
3816
- const width = this.pageSize.width ? this.pageSize.width : landscapeWidth;
3817
- this.width = isPortraitOrientation ? width : height;
3818
- this.height = isPortraitOrientation ? height : width;
3819
- const marginsObject = properties.margins;
3820
- this.margins =
3821
- // eslint-disable-next-line no-nested-ternary
3822
- marginsObject && Object.keys(marginsObject).length
3823
- ? marginsObject
3824
- : isPortraitOrientation
3825
- ? portraitMargins
3826
- : landscapeMargins;
3827
- this.availableDocumentSpace = this.width - this.margins.left - this.margins.right;
3828
- this.title = properties.title || '';
3829
- this.subject = properties.subject || '';
3830
- this.creator = properties.creator || applicationName;
3831
- this.keywords = properties.keywords || [applicationName];
3832
- this.description = properties.description || '';
3833
- this.lastModifiedBy = properties.lastModifiedBy || applicationName;
3834
- this.revision = properties.revision || 1;
3835
- this.createdAt = properties.createdAt || new Date();
3836
- this.modifiedAt = properties.modifiedAt || new Date();
3837
- this.headerType = properties.headerType || 'default';
3838
- this.header = properties.header || false;
3839
- this.footerType = properties.footerType || 'default';
3840
- this.footer = properties.footer || false;
3841
- this.font = properties.font || defaultFont;
3842
- this.fontSize = properties.fontSize || defaultFontSize;
3843
- this.complexScriptFontSize = properties.complexScriptFontSize || defaultFontSize;
3844
- this.tableRowCantSplit =
3845
- (properties.table && properties.table.row && properties.table.row.cantSplit) || false;
3846
- this.pageNumber = properties.pageNumber || false;
3847
- this.skipFirstHeaderFooter = properties.skipFirstHeaderFooter || false;
3848
- this.lineNumber = properties.lineNumber ? properties.lineNumberOptions : null;
3849
- this.lastNumberingId = 0;
3850
- this.lastMediaId = 0;
3851
- this.lastHeaderId = 0;
3852
- this.lastFooterId = 0;
3853
- this.stylesObjects = [];
3854
- this.numberingObjects = [];
3855
- this.relationshipFilename = documentFileName;
3856
- this.relationships = [{ fileName: documentFileName, lastRelsId: 4, rels: [] }];
3857
- this.mediaFiles = [];
3858
- this.headerObjects = [];
3859
- this.footerObjects = [];
3860
- this.documentXML = null;
3861
- this.generateContentTypesXML = this.generateContentTypesXML.bind(this);
3862
- this.generateDocumentXML = this.generateDocumentXML.bind(this);
3863
- this.generateCoreXML = this.generateCoreXML.bind(this);
3864
- this.generateSettingsXML = this.generateSettingsXML.bind(this);
3865
- this.generateWebSettingsXML = this.generateWebSettingsXML.bind(this);
3866
- this.generateStylesXML = this.generateStylesXML.bind(this);
3867
- this.generateFontTableXML = this.generateFontTableXML.bind(this);
3868
- this.generateThemeXML = this.generateThemeXML.bind(this);
3869
- this.generateNumberingXML = this.generateNumberingXML.bind(this);
3870
- this.generateRelsXML = this.generateRelsXML.bind(this);
3871
- this.createMediaFile = this.createMediaFile.bind(this);
3872
- this.createDocumentRelationships = this.createDocumentRelationships.bind(this);
3873
- this.generateHeaderXML = this.generateHeaderXML.bind(this);
3874
- this.generateFooterXML = this.generateFooterXML.bind(this);
3875
- this.generateSectionXML = generateSectionXML.bind(this);
3876
- this.ListStyleBuilder = new ListStyleBuilder(properties.numbering);
3877
- }
3878
- generateContentTypesXML() {
3879
- const contentTypesXML$1 = create({ encoding: 'UTF-8', standalone: true }, contentTypesXML);
3880
- generateContentTypesFragments(contentTypesXML$1, 'header', this.headerObjects);
3881
- generateContentTypesFragments(contentTypesXML$1, 'footer', this.footerObjects);
3882
- return contentTypesXML$1.toString({ prettyPrint: true });
3883
- }
3884
- generateDocumentXML() {
3885
- const documentXML = create({ encoding: 'UTF-8', standalone: true }, generateDocumentTemplate(this.width, this.height, this.orientation, this.margins));
3886
- // documentXML.root().first().import(this.documentXML);
3887
- generateSectionReferenceXML(documentXML, 'header', this.headerObjects, this.header);
3888
- generateSectionReferenceXML(documentXML, 'footer', this.footerObjects, this.footer);
3889
- if ((this.header || this.footer) && this.skipFirstHeaderFooter) {
3890
- documentXML
3891
- .root()
3892
- .first()
3893
- .first()
3894
- .import(fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'titlePg'));
3895
- }
3896
- if (this.lineNumber) {
3897
- const { countBy, start, restart } = this.lineNumber;
3898
- documentXML
3899
- .root()
3900
- .first()
3901
- .first()
3902
- .import(fragment({ namespaceAlias: { w: namespaces.w } })
3903
- .ele('@w', 'lnNumType')
3904
- .att('@w', 'countBy', countBy)
3905
- .att('@w', 'start', start)
3906
- .att('@w', 'restart', restart));
3907
- }
3908
- return documentXML.toString({ prettyPrint: true });
3909
- }
3910
- generateCoreXML() {
3911
- return generateXMLString(generateCoreXML(this.title, this.subject, this.creator, this.keywords, this.description, this.lastModifiedBy, this.revision, this.createdAt, this.modifiedAt));
3912
- }
3913
- // eslint-disable-next-line class-methods-use-this
3914
- generateSettingsXML() {
3915
- return generateXMLString(settingsXML);
3916
- }
3917
- // eslint-disable-next-line class-methods-use-this
3918
- generateWebSettingsXML() {
3919
- return generateXMLString(webSettingsXML);
3920
- }
3921
- generateStylesXML() {
3922
- return generateXMLString(generateStylesXML(this.font, this.fontSize, this.complexScriptFontSize));
3923
- }
3924
- // eslint-disable-next-line class-methods-use-this
3925
- generateFontTableXML() {
3926
- return generateXMLString(fontTableXML);
3927
- }
3928
- generateThemeXML() {
3929
- return generateXMLString(generateThemeXML(this.font));
3930
- }
3931
- generateNumberingXML() {
3932
- const numberingXML = create({ encoding: 'UTF-8', standalone: true }, generateNumberingXMLTemplate());
3933
- const abstractNumberingFragments = fragment();
3934
- const numberingFragments = fragment();
3935
- this.numberingObjects.forEach(({ numberingId, type, properties }) => {
3936
- const abstractNumberingFragment = fragment({ namespaceAlias: { w: namespaces.w } })
3937
- .ele('@w', 'abstractNum')
3938
- .att('@w', 'abstractNumId', String(numberingId));
3939
- [...Array(8).keys()].forEach((level) => {
3940
- const levelFragment = fragment({ namespaceAlias: { w: namespaces.w } })
3941
- .ele('@w', 'lvl')
3942
- .att('@w', 'ilvl', level)
3943
- .ele('@w', 'start')
3944
- .att('@w', 'val', type === 'ol'
3945
- ? (properties.attributes && properties.attributes['data-start']) || 1
3946
- : '1')
3947
- .up()
3948
- .ele('@w', 'numFmt')
3949
- .att('@w', 'val', type === 'ol'
3950
- ? this.ListStyleBuilder.getListStyleType(properties.style && properties.style['list-style-type'])
3951
- : 'bullet')
3952
- .up()
3953
- .ele('@w', 'lvlText')
3954
- .att('@w', 'val', type === 'ol' ? this.ListStyleBuilder.getListPrefixSuffix(properties.style, level) : '')
3955
- .up()
3956
- .ele('@w', 'lvlJc')
3957
- .att('@w', 'val', 'left')
3958
- .up()
3959
- .ele('@w', 'pPr')
3960
- .ele('@w', 'tabs')
3961
- .ele('@w', 'tab')
3962
- .att('@w', 'val', 'num')
3963
- .att('@w', 'pos', (level + 1) * 720)
3964
- .up()
3965
- .up()
3966
- .ele('@w', 'ind')
3967
- .att('@w', 'left', (level + 1) * 720)
3968
- .att('@w', 'hanging', 360)
3969
- .up()
3970
- .up()
3971
- .up();
3972
- if (type === 'ul') {
3973
- levelFragment.last().import(fragment({ namespaceAlias: { w: namespaces.w } })
3974
- .ele('@w', 'rPr')
3975
- .ele('@w', 'rFonts')
3976
- .att('@w', 'ascii', 'Symbol')
3977
- .att('@w', 'hAnsi', 'Symbol')
3978
- .att('@w', 'hint', 'default')
3979
- .up()
3980
- .up());
3981
- }
3982
- abstractNumberingFragment.import(levelFragment);
3983
- });
3984
- abstractNumberingFragment.up();
3985
- abstractNumberingFragments.import(abstractNumberingFragment);
3986
- numberingFragments.import(fragment({ namespaceAlias: { w: namespaces.w } })
3987
- .ele('@w', 'num')
3988
- .att('@w', 'numId', String(numberingId))
3989
- .ele('@w', 'abstractNumId')
3990
- .att('@w', 'val', String(numberingId))
3991
- .up()
3992
- .up());
3993
- });
3994
- numberingXML.root().import(abstractNumberingFragments);
3995
- numberingXML.root().import(numberingFragments);
3996
- return numberingXML.toString({ prettyPrint: true });
3997
- }
3998
- // eslint-disable-next-line class-methods-use-this
3999
- appendRelationships(xmlFragment, relationships) {
4000
- relationships.forEach(({ relationshipId, type, target, targetMode }) => {
4001
- xmlFragment.import(fragment({ defaultNamespace: { ele: namespaces.relationship } })
4002
- .ele('Relationship')
4003
- .att('Id', `rId${relationshipId}`)
4004
- .att('Type', type)
4005
- .att('Target', target)
4006
- .att('TargetMode', targetMode)
4007
- .up());
4008
- });
4009
- }
4010
- generateRelsXML() {
4011
- const relationshipXMLStrings = this.relationships.map(({ fileName, rels }) => {
4012
- const xmlFragment = create({ encoding: 'UTF-8', standalone: true }, fileName === documentFileName ? documentRelsXML : genericRelsXML);
4013
- this.appendRelationships(xmlFragment.root(), rels);
4014
- return { fileName, xmlString: xmlFragment.toString({ prettyPrint: true }) };
4015
- });
4016
- return relationshipXMLStrings;
4017
- }
4018
- createNumbering(type, properties) {
4019
- this.lastNumberingId += 1;
4020
- this.numberingObjects.push({ numberingId: this.lastNumberingId, type, properties });
4021
- return this.lastNumberingId;
4022
- }
4023
- createMediaFile(base64String) {
4024
- // eslint-disable-next-line no-useless-escape
4025
- const matches = base64String.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
4026
- if (matches.length !== 3) {
4027
- throw new Error('Invalid base64 string');
4028
- }
4029
- const base64FileContent = matches[2];
4030
- // matches array contains file type in base64 format - image/jpeg and base64 stringified data
4031
- const fileExtension = matches[1].match(/\/(.*?)$/)[1] === 'octet-stream' ? 'png' : matches[1].match(/\/(.*?)$/)[1];
4032
- const fileNameWithExtension = `image-${nanoid()}.${fileExtension}`;
4033
- this.lastMediaId += 1;
4034
- return { id: this.lastMediaId, fileContent: base64FileContent, fileNameWithExtension };
4035
- }
4036
- createDocumentRelationships(fileName = 'document', type, target, targetMode = 'External') {
4037
- debugger;
4038
- let relationshipObject = this.relationships.find((relationship) => relationship.fileName === fileName);
4039
- let lastRelsId = 1;
4040
- if (relationshipObject) {
4041
- lastRelsId = relationshipObject.lastRelsId + 1;
4042
- relationshipObject.lastRelsId = lastRelsId;
4043
- }
4044
- else {
4045
- relationshipObject = { fileName, lastRelsId, rels: [] };
4046
- this.relationships.push(relationshipObject);
4047
- }
4048
- let relationshipType;
4049
- switch (type) {
4050
- case hyperlinkType:
4051
- relationshipType = namespaces.hyperlinks;
4052
- break;
4053
- case imageType:
4054
- relationshipType = namespaces.images;
4055
- break;
4056
- case headerType:
4057
- relationshipType = namespaces.headers;
4058
- break;
4059
- case footerType:
4060
- relationshipType = namespaces.footers;
4061
- break;
4062
- case themeType:
4063
- relationshipType = namespaces.themes;
4064
- break;
4065
- }
4066
- relationshipObject.rels.push({
4067
- relationshipId: lastRelsId,
4068
- type: relationshipType,
4069
- target,
4070
- targetMode,
4071
- });
4072
- console.log(fileName);
4073
- console.log(relationshipObject.rels);
4074
- return lastRelsId;
4075
- }
4076
- generateHeaderXML(vTree) {
4077
- return this.generateSectionXML(vTree, 'header');
4078
- }
4079
- generateFooterXML(vTree) {
4080
- return this.generateSectionXML(vTree, 'footer');
4081
- }
4082
- }
4083
-
4084
- const defaultMargins = {
4085
- top: 1440,
4086
- right: 1440,
4087
- bottom: 1440,
4088
- left: 1440,
4089
- header: 720,
4090
- footer: 720,
4091
- gutter: 0,
4092
- };
4093
- const documentTemplate = (width, height, orient, margins) => {
4094
- return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
4095
- <w:document
4096
- xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
4097
- xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"
4098
- xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
4099
- xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
4100
- xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
4101
- xmlns:ns6="http://schemas.openxmlformats.org/schemaLibrary/2006/main"
4102
- xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"
4103
- xmlns:ns8="http://schemas.openxmlformats.org/drawingml/2006/chartDrawing"
4104
- xmlns:dgm="http://schemas.openxmlformats.org/drawingml/2006/diagram"
4105
- xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"
4106
- xmlns:ns11="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"
4107
- xmlns:dsp="http://schemas.microsoft.com/office/drawing/2008/diagram"
4108
- xmlns:ns13="urn:schemas-microsoft-com:office:excel"
4109
- xmlns:o="urn:schemas-microsoft-com:office:office"
4110
- xmlns:v="urn:schemas-microsoft-com:vml"
4111
- xmlns:w10="urn:schemas-microsoft-com:office:word"
4112
- xmlns:ns17="urn:schemas-microsoft-com:office:powerpoint"
4113
- xmlns:odx="http://opendope.org/xpaths"
4114
- xmlns:odc="http://opendope.org/conditions"
4115
- xmlns:odq="http://opendope.org/questions"
4116
- xmlns:odi="http://opendope.org/components"
4117
- xmlns:odgm="http://opendope.org/SmartArt/DataHierarchy"
4118
- xmlns:ns24="http://schemas.openxmlformats.org/officeDocument/2006/bibliography"
4119
- xmlns:ns25="http://schemas.openxmlformats.org/drawingml/2006/compatibility"
4120
- xmlns:ns26="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas">
4121
- <w:body>
4122
- <w:altChunk r:id="htmlChunk" />
4123
- <w:sectPr>
4124
- <w:pgSz w:w="${width}" w:h="${height}" w:orient="${orient}" />
4125
- <w:pgMar w:top="${margins.top}"
4126
- w:right="${margins.right}"
4127
- w:bottom="${margins.bottom}"
4128
- w:left="${margins.left}"
4129
- w:header="${margins.header}"
4130
- w:footer="${margins.footer}"
4131
- w:gutter="${margins.gutter}"/>
4132
- </w:sectPr>
4133
- </w:body>
4134
- </w:document>
4135
- `;
4136
- };
4137
-
4138
- const mhtDocumentTemplate = (htmlSource, contentParts) => {
4139
- debugger;
4140
- return `MIME-Version: 1.0
4141
- Content-Type: multipart/related;
4142
- type="text/html";
4143
- boundary="----=mhtDocumentPart"
4144
-
4145
-
4146
- ------=mhtDocumentPart
4147
- Content-Type: text/html;
4148
- charset="utf-8"
4149
- Content-Transfer-Encoding: quoted-printable
4150
- Content-Location: file:///C:/fake/document.html
4151
-
4152
- ${htmlSource}
4153
-
4154
- ${contentParts}
4155
-
4156
- ------=mhtDocumentPart--
4157
- `;
4158
- };
4159
-
4160
- const mhtPartTemplate = (contentType, contentEncoding, contentLocation, encodedContent) => {
4161
- return `------=mhtDocumentPart
4162
- Content-Type: ${contentType}
4163
- Content-Transfer-Encoding: ${contentEncoding}
4164
- Content-Location: ${contentLocation}
4165
-
4166
- ${encodedContent}
4167
- `;
4168
- };
4169
-
4170
- function getMHTdocument(htmlSource) {
4171
- debugger;
4172
- const ref = _prepareImageParts(htmlSource);
4173
- const imageContentPartsString = ref.imageContentParts.join('\n');
4174
- htmlSource = ref.htmlSource.replace(/\=/g, '=3D');
4175
- return mhtDocumentTemplate(htmlSource, imageContentPartsString);
4176
- }
4177
- function _prepareImageParts(htmlSource) {
4178
- debugger;
4179
- const imageContentParts = [];
4180
- const inlinedSrcPattern = /"data:(\w+\/\w+);(\w+),(\S+)"/g;
4181
- const inlinedReplacer = (match, contentType, contentEncoding, encodedContent) => {
4182
- const index = imageContentParts.length;
4183
- const extension = contentType.split('/')[1];
4184
- const contentLocation = `file:///C:/fake/image${index}.${extension}`;
4185
- imageContentParts.push(mhtPartTemplate(contentType, contentEncoding, contentLocation, encodedContent));
4186
- return `\"${contentLocation}\"`;
4187
- };
4188
- if (!/<img/g.test(htmlSource)) {
4189
- return { htmlSource, imageContentParts };
4190
- }
4191
- htmlSource = htmlSource.replace(inlinedSrcPattern, inlinedReplacer);
4192
- return { htmlSource, imageContentParts };
4193
- }
4194
-
4195
- const convertHTML = HTMLToVDOM({
4196
- VNode: VNode$1,
4197
- VText,
4198
- });
4199
- const mergeOptions = (options, patch) => ({ ...options, ...patch });
4200
- const fixupFontSize = (fontSize) => {
4201
- let normalizedFontSize;
4202
- if (pointRegex.test(fontSize)) {
4203
- const matchedParts = fontSize.match(pointRegex);
4204
- normalizedFontSize = pointToHIP(matchedParts[1]);
4205
- }
4206
- else if (fontSize) {
4207
- // assuming it is already in HIP
4208
- normalizedFontSize = fontSize;
4209
- }
4210
- else {
4211
- normalizedFontSize = null;
4212
- }
4213
- return normalizedFontSize;
4214
- };
4215
- const normalizeUnits = (dimensioningObject, defaultDimensionsProperty) => {
4216
- let normalizedUnitResult = {};
4217
- if (typeof dimensioningObject === 'object' && dimensioningObject !== null) {
4218
- Object.keys(dimensioningObject).forEach((key) => {
4219
- if (pixelRegex.test(dimensioningObject[key])) {
4220
- const matchedParts = dimensioningObject[key].match(pixelRegex);
4221
- normalizedUnitResult[key] = pixelToTWIP(matchedParts[1]);
4222
- }
4223
- else if (cmRegex.test(dimensioningObject[key])) {
4224
- const matchedParts = dimensioningObject[key].match(cmRegex);
4225
- normalizedUnitResult[key] = cmToTWIP(matchedParts[1]);
4226
- }
4227
- else if (inchRegex.test(dimensioningObject[key])) {
4228
- const matchedParts = dimensioningObject[key].match(inchRegex);
4229
- normalizedUnitResult[key] = inchToTWIP(matchedParts[1]);
4230
- }
4231
- else if (dimensioningObject[key]) {
4232
- normalizedUnitResult[key] = dimensioningObject[key];
4233
- }
4234
- else {
4235
- // incase value is something like 0
4236
- normalizedUnitResult[key] = defaultDimensionsProperty[key];
4237
- }
4238
- });
4239
- }
4240
- else {
4241
- // eslint-disable-next-line no-param-reassign
4242
- normalizedUnitResult = null;
4243
- }
4244
- return normalizedUnitResult;
4245
- };
4246
- const normalizeDocumentOptions = (documentOptions) => {
4247
- const normalizedDocumentOptions = { ...documentOptions };
4248
- Object.keys(documentOptions).forEach((key) => {
4249
- // eslint-disable-next-line default-case
4250
- switch (key) {
4251
- case 'pageSize':
4252
- case 'margins':
4253
- normalizedDocumentOptions[key] = normalizeUnits(documentOptions[key], defaultDocumentOptions[key]);
4254
- break;
4255
- case 'fontSize':
4256
- case 'complexScriptFontSize':
4257
- normalizedDocumentOptions[key] = fixupFontSize(documentOptions[key]);
4258
- break;
4259
- }
4260
- });
4261
- return normalizedDocumentOptions;
4262
- };
4263
- // Ref: https://en.wikipedia.org/wiki/Office_Open_XML_file_formats
4264
- // http://officeopenxml.com/anatomyofOOXML.php
4265
- async function addFilesToContainer(zip, htmlString, suppliedDocumentOptions, headerHTMLString, footerHTMLString) {
4266
- debugger;
4267
- const normalizedDocumentOptions = normalizeDocumentOptions(suppliedDocumentOptions);
4268
- const documentOptions = mergeOptions(defaultDocumentOptions, normalizedDocumentOptions);
4269
- if (documentOptions.header && !headerHTMLString) {
4270
- // eslint-disable-next-line no-param-reassign
4271
- headerHTMLString = defaultHTMLString;
4272
- }
4273
- if (documentOptions.footer && !footerHTMLString) {
4274
- // eslint-disable-next-line no-param-reassign
4275
- footerHTMLString = defaultHTMLString;
4276
- }
4277
- const docxDocument = new DocxDocument({ zip, htmlString, ...documentOptions });
4278
- // Conversion to Word XML happens here
4279
- docxDocument.documentXML = await renderDocumentFile(docxDocument);
4280
- debugger;
4281
- zip
4282
- .folder(relsFolderName)
4283
- .file('.rels', create({ encoding: 'UTF-8', standalone: true }, relsXML).toString({ prettyPrint: true }), { createFolders: false });
4284
- zip.folder('docProps').file('core.xml', docxDocument.generateCoreXML(), {
4285
- createFolders: false,
4286
- });
4287
- if (docxDocument.header && headerHTMLString) {
4288
- const vTree = convertHTML(headerHTMLString);
4289
- docxDocument.relationshipFilename = headerFileName;
4290
- const { headerId, headerXML } = await docxDocument.generateHeaderXML(vTree);
4291
- docxDocument.relationshipFilename = documentFileName;
4292
- const fileNameWithExt = `${headerType}${headerId}.xml`;
4293
- const relationshipId = docxDocument.createDocumentRelationships(docxDocument.relationshipFilename, headerType, fileNameWithExt, internalRelationship);
4294
- zip.folder(wordFolder).file(fileNameWithExt, generateDocumentTemplateHeader.toString({ prettyPrint: true }), {
4295
- createFolders: false,
4296
- });
4297
- docxDocument.headerObjects.push({ headerId, relationshipId, type: docxDocument.headerType });
4298
- }
4299
- if (docxDocument.footer && footerHTMLString) {
4300
- const vTree = convertHTML(footerHTMLString);
4301
- docxDocument.relationshipFilename = footerFileName;
4302
- const { footerId, footerXML } = await docxDocument.generateFooterXML(vTree);
4303
- docxDocument.relationshipFilename = documentFileName;
4304
- const fileNameWithExt = `${footerType}${footerId}.xml`;
4305
- const relationshipId = docxDocument.createDocumentRelationships(docxDocument.relationshipFilename, footerType, fileNameWithExt, internalRelationship);
4306
- console.log(footerXML.toString({ prettyPrint: true }));
4307
- if (suppliedDocumentOptions.pageNumber)
4308
- zip.folder(wordFolder).file(fileNameWithExt, generateDocumentTemplateFooter.toString({ prettyPrint: true }), {
4309
- createFolders: false,
4310
- });
4311
- else
4312
- zip.folder(wordFolder).file(fileNameWithExt, generateDocumentTemplateFooterWithoutPaging.toString({ prettyPrint: true }), {
4313
- createFolders: false,
4314
- });
4315
- docxDocument.footerObjects.push({ footerId, relationshipId, type: docxDocument.footerType });
4316
- }
4317
- const themeFileNameWithExt = `${themeFileName}.xml`;
4318
- docxDocument.createDocumentRelationships(docxDocument.relationshipFilename, themeType, `${themeFolder}/${themeFileNameWithExt}`, internalRelationship);
4319
- zip
4320
- .folder(wordFolder)
4321
- .folder(themeFolder)
4322
- .file(themeFileNameWithExt, docxDocument.generateThemeXML(), {
4323
- createFolders: false,
4324
- });
4325
- zip
4326
- .folder(wordFolder)
4327
- .file('document.xml', docxDocument.generateDocumentXML(), { createFolders: false })
4328
- .file('afchunk.mht', getMHTdocument(htmlString), {
4329
- createFolders: false,
4330
- })
4331
- .file('afchunkheader.mht', getMHTdocument(headerHTMLString), {
4332
- createFolders: false,
4333
- })
4334
- .file('afchunkfooter.mht', getMHTdocument(footerHTMLString), {
4335
- createFolders: false,
4336
- })
4337
- .file('fontTable.xml', docxDocument.generateFontTableXML(), { createFolders: false })
4338
- .file('styles.xml', docxDocument.generateStylesXML(), { createFolders: false })
4339
- .file('numbering.xml', docxDocument.generateNumberingXML(), { createFolders: false })
4340
- .file('settings.xml', docxDocument.generateSettingsXML(), { createFolders: false })
4341
- .file('webSettings.xml', docxDocument.generateWebSettingsXML(), { createFolders: false });
4342
- const relationshipXMLs = docxDocument.generateRelsXML();
4343
- if (relationshipXMLs && Array.isArray(relationshipXMLs)) {
4344
- relationshipXMLs.forEach(({ fileName, xmlString }) => {
4345
- console.log(xmlString);
4346
- zip.folder(wordFolder).folder(relsFolderName).file(`${fileName}.xml.rels`, xmlString, {
4347
- createFolders: false,
4348
- });
4349
- });
4350
- }
4351
- if (relationshipXMLs && Array.isArray(relationshipXMLs)) {
4352
- relationshipXMLs.forEach(({ fileName, xmlString }) => {
4353
- zip.folder(wordFolder).folder(relsFolderName).file(`header1.xml.rels`, xmlString, {
4354
- createFolders: false,
4355
- });
4356
- });
4357
- }
4358
- if (relationshipXMLs && Array.isArray(relationshipXMLs)) {
4359
- relationshipXMLs.forEach(({ fileName, xmlString }) => {
4360
- zip.folder(wordFolder).folder(relsFolderName).file(`footer1.xml.rels`, xmlString, {
4361
- createFolders: false,
4362
- });
4363
- });
4364
- }
4365
- zip.file('[Content_Types].xml', docxDocument.generateContentTypesXML(), { createFolders: false });
4366
- return zip;
4367
- }
4368
-
4369
- /* eslint-disable no-useless-escape */
4370
- const minifyHTMLString = (htmlString) => {
4371
- try {
4372
- if (typeof htmlString === 'string' || htmlString instanceof String) {
4373
- const minifiedHTMLString = htmlString
4374
- .replace(/\n/g, ' ')
4375
- .replace(/\r/g, ' ')
4376
- .replace(/\r\n/g, ' ')
4377
- .replace(/[\t]+\</g, '<')
4378
- .replace(/\>[\t ]+\</g, '><')
4379
- .replace(/\>[\t ]+$/g, '>');
4380
- return minifiedHTMLString;
4381
- }
4382
- throw new Error('invalid html string');
4383
- }
4384
- catch (error) {
4385
- return null;
4386
- }
4387
- };
4388
- async function generateContainer(htmlString, headerHTMLString, documentOptions = {}, footerHTMLString) {
4389
- const zip = new JSZip();
4390
- let contentHTML = htmlString;
4391
- let headerHTML = headerHTMLString;
4392
- let footerHTML = footerHTMLString;
4393
- if (htmlString) {
4394
- contentHTML = minifyHTMLString(contentHTML);
4395
- }
4396
- if (headerHTMLString) {
4397
- headerHTML = minifyHTMLString(headerHTML);
4398
- }
4399
- if (footerHTMLString) {
4400
- footerHTML = minifyHTMLString(footerHTML);
4401
- }
4402
- await addFilesToContainer(zip, contentHTML, documentOptions, headerHTML, footerHTML);
4403
- const buffer = await zip.generateAsync({ type: 'arraybuffer' });
4404
- if (Object.prototype.hasOwnProperty.call(global, 'Buffer')) {
4405
- return Buffer.from(new Uint8Array(buffer));
4406
- }
4407
- if (Object.prototype.hasOwnProperty.call(global, 'Blob')) {
4408
- // eslint-disable-next-line no-undef
4409
- return new Blob([buffer], {
4410
- type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
4411
- });
4412
- }
4413
- throw new Error('Add blob support using a polyfill eg https://github.com/bjornstar/blob-polyfill');
4414
- }
4415
-
883
+ /**
884
+ * Word Document Service
885
+ *
886
+ * Uses dynamic imports to avoid bundling word generation dependencies (~8 MB)
887
+ * unless the service is actually used.
888
+ *
889
+ * Dependencies (loaded on-demand):
890
+ * - xmlbuilder2
891
+ * - jszip
892
+ * - html-to-vdom
893
+ * - virtual-dom
894
+ * - image-size
895
+ * - image-to-base64
896
+ * - color-name
897
+ * - escape-html
898
+ * - mime-types
899
+ */
4416
900
  class WordDocumentService {
4417
901
  async generateWordByteFile(model) {
902
+ // Dynamic import to avoid bundling word generation dependencies
903
+ // unless this method is actually called
904
+ const { generateContainer } = await import('./bnsights-bbsf-utilities-index-C3Twnewr.mjs');
4418
905
  let documentOptions = {};
4419
906
  if (model.options.isLandscape)
4420
907
  documentOptions.orientation = 'landscape';