forked from RolandDreger/indesign-word-import
-
Notifications
You must be signed in to change notification settings - Fork 0
/
importDocx.jsx
3659 lines (3006 loc) · 116 KB
/
importDocx.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* DESCRIPTION: Import Word Document (docx) */
/*
+ Adobe InDesign Version: CC2021+
+ Author: Roland Dreger
+ Date: January 24, 2022
+ Last modified: October 2, 2022
+ Descriptions
Alternative import for Microsoft Word documents
for clean and sematically structured content
*/
//@include "utils/i18n.jsx"
//@include "utils/classes.jsx"
//@include "utils/dialogs.jsx"
//@include "utils/helpers.jsx"
//@include "hooks/beforeImport.jsx"
//@include "hooks/beforeMount.jsx"
//@include "hooks/beforePlaced.jsx"
//@include "hooks/afterPlaced.jsx"
var _global = {
"projectName":"Import_Docx",
"version":"0.4.0",
"mode":"release", /* Type: String. Value: "debug" or "release" */
"isLogged":false,
"isDialogShown":true,
"log":[]
};
/* Document Settings */
_global["setups"] = {
"user":$.getenv("USER"),
"document":{
"isAutoflowing": true, /* Type: Boolean. Description: If true, autoflows placed text. (Depends on document settings.) */
"isUntagged":false, /* Type: Boolean. Description: If true, then the XML structure will be removed out of the document after import. */
"defaultParagraphStyle":"Normal" /* Type: String. Value: e.g. "Normal". Description: This style is used for paragraphs that do not have a specific paragraph style applied in the Word document. */
},
"metadata":{
"tag":"document",
"attributes":{
"description":"description",
"category":"category",
"keywords":"keywords",
"author":"author",
"subject":"subject",
"title":"title"
},
"areMerged":false,
"areReplaced":false,
"areIgnored":true
},
"linkFolder":{
"name":"Links", /* Type: String. Value: e.g. "Links". Description: Folder name for placed images; */
"path":"" /* Type: String. Value: e.g. "" (next to the InDesign Document) or "~/Desktop". Description: Folder path for placed images (optional). */
},
"xslt":{
"name":"docx2Indesign.xsl"
},
"import":{
"styleMode":"extended", /* Type: String. Value: 'extended' or 'minimized'. Description: If minimized, all local overrides are ignored except the following: strong, i, em, u, superscript, subscript, small caps, caps, highlight. */
"tableMode":"table" /* Type: String. Value: 'table' or 'tabbedlist'. Description: If 'tabbedlist', import table structure as tab separated text. */
},
"place":{},
"mount":{},
"paragraph":{
"tag":"paragraph"
},
"pageBreak":{
"tag":"pagebreak",
"isInserted":true
},
"columnBreak":{
"tag":"columnbreak",
"isInserted":true
},
"forcedLineBreak":{
"tag":"forcedlinebreak",
"isInserted":true
},
"sectionBreak":{
"tag":"sectionbreak",
"isInserted":true
},
"comment":{
"tag":"comment",
"color":[255,255,155],
"metadata":{
"isAdded":true
},
"isRemoved":false,
"isMarked":false,
"isCreated":true
},
"indexmark":{
"tag":"indexmark",
"attributes":{
"type":"type",
"format":"format",
"entry":"entry",
"target":"target"
},
"topicSeparator": ":",
"isRemoved":false,
"isCreated":true,
"crossReference":{
"prefixes":[
{ "de":"Siehe [auch]", "en":"See [also]", "fr":"Voir [aussi]" }, /* English key "en" and value "See [also]" is required as a minimum. Do not modify the value. */
{ "de":"Siehe auch hier", "en":"See also herein", "fr":"Voir aussi ici" }, /* English key "en" and value "See also herein" is required as a minimum. Do not modify the value. */
{ "de":"Siehe auch", "en":"See also", "fr":"Voir aussi" }, /* English key "en" and value "See also" is required as a minimum. Do not modify the value. */
{ "de":"Siehe hier", "en":"See herein", "fr":"Voir ici" }, /* English key "en" and value "See herein" is required as a minimum. Do not modify the value. */
{ "de":"Siehe", "en":"See", "fr":"Voir" }, /* English key "en" and value "See" is required as a minimum. Do not modify the value. */
/* more objects can be added -> results in cross-reference with type CrossReferenceType.CUSTOM_CROSS_REFERENCE */
{"de":"→", "en":"→", "fr":"→" } /* Word cross-reference field: e.g. x Topic0: Topic1 */
],
"noMatchCustomTypeString": "\u200B" /* Default: zero-width whitespace; If an empty string, the prefix "See [also]" is used. */
}
},
"hyperlink":{
"tag":"hyperlink",
"attributes":{
"uri":"uri",
"title":"title"
},
"color":[120,190,255],
"characterStyleName":"Hyperlink",
"isCharacterStyleAdded":false,
"isMarked":false,
"isCreated":true,
"isIgnored":false
},
"crossReference":{
"tag":"cross-reference",
"attributes":{
"uri":"uri",
"type":"type",
"format":"format"
},
"color":[120,190,255],
"characterStyleName":"Cross_Reference",
"isAnchorHidden":true,
"isCharacterStyleAdded":true,
"isMarked":false,
"isCreated":true,
"isIgnored":false
},
"bookmark":{
"tag":"bookmark",
"attributes":{
"id":"id",
"index":"index",
"content":"content"
},
"marker":"", /* Marker as a prefix of Word bookmark ID to be included as InDesign bookmark. Value: String. Example: indesign_my_bookmark_name -> Marker: indesign_ */
"isAnchorHidden":true,
"isCreated":false
},
"textbox":{
"tag":"textbox",
"color":[155,155,255],
"width":"100", /* Default textbox width in mm; Value: String */
"height":"40", /* Default textbox height in mm; Value: String */
"objectStyleProperties":{
"enableAnchoredObjectOptions":true,
"anchoredObjectSettings": {
"anchoredPosition":AnchorPosition.ANCHORED,
"anchorPoint":AnchorPoint.TOP_LEFT_ANCHOR,
"horizontalAlignment": HorizontalAlignment.LEFT_ALIGN,
"horizontalReferencePoint":AnchoredRelativeTo.TEXT_FRAME,
"spineRelative":false,
"pinPosition": false,
"verticalReferencePoint":VerticallyRelativeTo.LINE_BASELINE
},
"enableTextWrapAndOthers":true,
"textWrapPreferences":{
"textWrapMode":TextWrapModes.JUMP_OBJECT_TEXT_WRAP
}
},
"isRemoved":false,
"isMarked":false,
"isCreated":true
},
"image":{
"tag":"image",
"attributes":{
"source":"source",
"description":"description"
},
"width":"100", /* Default image width in mm; Value: String */
"height":"100", /* Default image height in mm; Value: String */
"objectStyleProperties":{
"strokeWeight":0,
"enableAnchoredObjectOptions":true,
"anchoredObjectSettings": {
"anchoredPosition":AnchorPosition.ANCHORED,
"anchorPoint":AnchorPoint.TOP_LEFT_ANCHOR,
"horizontalAlignment": HorizontalAlignment.LEFT_ALIGN,
"horizontalReferencePoint":AnchoredRelativeTo.TEXT_FRAME,
"spineRelative":false,
"pinPosition": false,
"verticalReferencePoint":VerticallyRelativeTo.LINE_BASELINE
},
"enableFrameFittingOptions":true,
"frameFittingOptions":{
"fittingAlignment":AnchorPoint.TOP_LEFT_ANCHOR,
"fittingOnEmptyFrame":EmptyFrameFittingOptions.PROPORTIONALLY
},
"enableTextWrapAndOthers":true,
"textWrapPreferences":{
"textWrapMode":TextWrapModes.JUMP_OBJECT_TEXT_WRAP
}
},
"color":[155,255,255],
"isAltTextInserted":true,
"isRemoved":false,
"isMarked":false,
"isPlaced":true
},
"trackChanges":{
"insertedText":{
"tag":"insertedtext",
"color":[0,255,0]
},
"deletedText":{
"tag":"deletedtext",
"color":[255,0,0]
},
"movedFromText":{
"tag":"deletedtext",
"color":[155,155,255]
},
"movedToText":{
"tag":"movedtext",
"color":[0,255,255]
},
"isRemoved":false,
"isMarked":true,
"isCreated":false
},
"footnote":{
"tag":"footnote",
"color":[155,255,255],
"isRemoved":false,
"isMarked":false,
"isCreated":true
},
"endnote":{
"tag":"endnote",
"color":[255,155,255],
"isRemoved":false,
"isMarked":false,
"isCreated":true
}
};
/* Check: Developer or User? */
if(_global["setups"]["user"] === "rolanddreger") {
// _global["mode"] = "debug";
_global["isLogged"] = true;
}
__start();
function __start() {
if(!_global) {
throw new Error("Global object [_global] not defined.");
}
/* Deutsch-Englische Dialogtexte definieren */
__defLocalizeStrings();
/* Progressbar definieren */
_global["progressbar"] = new ProgressBar();
if(!_global["progressbar"]) {
throw new Error(localize(_global.createProgessbarErrorMessage));
}
/* Active document */
var _doc = app.documents.firstItem();
if(!_doc || !(_doc instanceof Document) || !_doc.isValid) {
alert(localize(_global.noDocOpenAlert));
return false;
}
/* Script Preferences */
var _userEnableRedraw = app.scriptPreferences.enableRedraw;
app.scriptPreferences.enableRedraw = false;
var _userInteractionLevel = app.scriptPreferences.userInteractionLevel;
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
/* Document Preferences */
var _userShowStructure = _doc.xmlViewPreferences.showStructure;
// _doc.xmlViewPreferences.showStructure = false;
try {
if(_global["mode"] !== "debug") {
app.doScript(
__runMainSequence,
ScriptLanguage.JAVASCRIPT,
[_doc],
UndoModes.ENTIRE_SCRIPT,
localize(_global.goBackLabel)
);
} else {
__runMainSequence([_doc]);
}
} catch(_error) {
if(_error instanceof Error) {
alert(
_error.name + " | " + _error.number + "\n" +
localize(_global.errorMessageLabel) + " " + _error.message + ";\n" +
localize(_global.lineLabel) + " " + _error.line + "\n" +
localize(_global.fileNameLabel) + " " + _error.fileName,
"Error", true
);
} else {
alert(localize(_global.processingErrorAlert) + "\n" + _error, "Error", true);
}
} finally {
if(_doc && _doc.isValid) {
_doc.xmlViewPreferences.showStructure = _userShowStructure;
}
app.scriptPreferences.enableRedraw = _userEnableRedraw;
app.scriptPreferences.userInteractionLevel = _userInteractionLevel;
}
/* Close progressbar */
if(_global.hasOwnProperty("progressbar")) {
_global["progressbar"].close();
}
/* Check: Log messages? */
if(_global["log"].length > 0) {
__showLog(_global["log"]);
return false;
}
return true;
} /* END function __start */
_global = null;
/**
* Main Sequence
* @param {Array} _doScriptParameterArray
* @returns Boolean
*/
function __runMainSequence(_doScriptParameterArray) {
if(!_global.hasOwnProperty("setups")) {
throw new Error("Global object has no property [_setups].");
}
if(!_doScriptParameterArray || !(_doScriptParameterArray instanceof Array) || _doScriptParameterArray.length === 0) {
throw new Error("Array with length > 1 as parameter required.");
}
var _setupObj = _global["setups"];
if(!_setupObj || !(_setupObj instanceof Object)) {
throw new Error("Object as parameter required.");
}
var _doc = _doScriptParameterArray[0];
if(!_doc || !(_doc instanceof Document) || !_doc.isValid) {
throw new Error("Document as parameter required.");
}
var _hooks = new Hooks();
/* Get docx file */
var _docxFile = __getDocxFile();
if(!_docxFile) {
return false;
}
/* Show import dialog */
if(_global["isDialogShown"] || (ScriptUI && ScriptUI.environment && ScriptUI.environment.keyboardState && ScriptUI.environment.keyboardState.shiftKey)) {
_setupObj = __showImportDialog(_setupObj);
if(!_setupObj) {
return false;
}
}
/* Get package data */
var _unpackObj = __getPackageData(_docxFile);
if(!_unpackObj) {
return false;
}
/* Hook: beforeImport */
var _beforeImportResultObj = _hooks.beforeImport(_doc, _unpackObj, _setupObj);
if(!_beforeImportResultObj) {
return false;
}
/* Import XML from unpacked docx file */
var _wordXMLElement = __importXML(_doc, _unpackObj, _setupObj);
if(!_wordXMLElement) {
return false;
}
/* Hook: beforeMount */
var _beforeMountResultObj = _hooks.beforeMount(_doc, _unpackObj, _wordXMLElement, _setupObj);
if(!_beforeMountResultObj) {
return false;
}
/* Mount InDesign items before XML placed */
var _mountBeforePlaceResultObj = __mountBeforePlaced(_doc, _unpackObj, _wordXMLElement, _setupObj);
if(!_mountBeforePlaceResultObj) {
return false;
}
/* Hook: beforePlaced */
var _beforePlaceResultObj = _hooks.beforePlaced(_doc, _unpackObj, _wordXMLElement, _setupObj);
if(!_beforePlaceResultObj) {
return false;
}
/* Place imported XML structure */
var _wordStory = __placeXML(_doc, _wordXMLElement, _setupObj);
if(!_wordStory) {
return false;
}
/* Hook: afterPlaced */
var _afterPlaceResultObj = _hooks.afterPlaced(_doc, _unpackObj, _wordXMLElement, _wordStory, _setupObj);
if(!_afterPlaceResultObj) {
return false;
}
/* Mount InDesign items after XML placed */
var _mountAfterPlaceResultObj = __mountAfterPlaced(_doc, _unpackObj, _wordXMLElement, _wordStory, _setupObj);
if(!_mountAfterPlaceResultObj) {
return false;
}
/* Remove XML Structure */
if(_setupObj["document"]["isUntagged"]) {
if(_wordXMLElement && _wordXMLElement.hasOwnProperty("untag") && _wordXMLElement.isValid) {
_wordXMLElement.untag();
}
}
return true;
} /* END function __runMainSequence */
/**
* Get docx file
* @returns File
*/
function __getDocxFile() {
const _wordExtRegExp = new RegExp("(\\.docx$|\\.xml$)","i");
var _wordFile = File.openDialog(localize(_global.selectWordFile));
if(!_wordFile || !_wordFile.exists) {
return null;
}
var _wordFileName = _wordFile.name;
if(!_wordExtRegExp.test(_wordFileName)) {
_global["log"].push(localize(_global.fileExtensionValidationMessage));
return null;
}
return _wordFile;
} /* END function __getDocxFile */
/**
* Get package data
* (Unpack file to temp folder if docx)
* @param {File} _packageFile
* @returns Object
*/
function __getPackageData(_packageFile) {
if(!_packageFile || !(_packageFile instanceof File) || !_packageFile.exists) {
throw new Error("Existing file as parameter required.");
}
const TEMP_FOLDER_NAME = "InDesign_Word_Import";
const _xmlExtRegExp = new RegExp("\\.xml$","i");
const _docxExtRegExp = new RegExp("\\.docx$","i");
var _packageFileName = _packageFile.name;
var _packageFilePath = _packageFile.fullName;
/* Check: Word-XML-Document (.xml)? */
if(_xmlExtRegExp.test(_packageFileName)) {
return {
"folder":null,
"word": {
"document":_packageFile
}
};
}
/* Check: Word Document (.docx)? */
if(!_docxExtRegExp.test(_packageFileName)) {
return null;
}
var _tempFolderPath = "";
var _tempFolder;
var _packageFolderPath = "";
var _packageFolder;
var _timestamp = __getTimestamp();
/* Create temporary package folder */
try {
_tempFolderPath = Folder.temp.fullName + "/" + TEMP_FOLDER_NAME;
_tempFolder = Folder(_tempFolderPath);
if(!_tempFolder.exists) {
_tempFolder.create();
}
if(!_tempFolder.exists) {
_global["log"].push(localize(_global.createFolderErrorMessage, _tempFolderPath));
return null;
}
_packageFolderPath = _tempFolder.fullName + "/package_" + _timestamp;
_packageFolder = Folder(_packageFolderPath);
} catch(_error) {
_global["log"].push(localize(_global.indesignErrorMessage, _error.message, _error.line));
return null;
}
if(!_packageFolder || !(_packageFolder instanceof Folder)) {
_global["log"].push(localize(_global.createFolderErrorMessage, _packageFolderPath));
return null;
}
/* Unpack Word Document */
try {
app.unpackageUCF(_packageFile, _packageFolder);
} catch(_error) {
_global["log"].push(localize(_global.indesignErrorMessage, _error.message, _error.line));
return null;
}
if(!_packageFolder.exists) {
_global["log"].push(localize(_global.unpackageFolderErrorMessage, _packageFolderPath));
return null;
}
var _xmlDocFile = File(_packageFolder.fullName + "/word/document.xml");
if(!_xmlDocFile.exists) {
_global["log"].push(localize(_global.unpackageDocumentFileErrorMessage, _packageFilePath));
return null;
}
return {
"folder":_packageFolder,
"word": {
"document":_xmlDocFile
}
};
} /* END function __getPackageData */
/**
* Import Word document xml file
* @param {Document} _doc InDesign document
* @param {Objekt} _unpackObj Result of unpacking Word document file
* @param {Objekt} _setupObj
* @returns XMLElement
*/
function __importXML(_doc, _unpackObj, _setupObj) {
if(!_doc || !(_doc instanceof Document) || !_doc.isValid) {
throw new Error("Document as parameter required.");
}
if(!_unpackObj || !(_unpackObj instanceof Object)) {
throw new Error("Object as parameter required.");
}
if(!_setupObj || !(_setupObj instanceof Object)) {
throw new Error("Object as parameter required.");
}
const _defaultPStyleName = _setupObj["document"]["defaultParagraphStyle"];
const _xsltFileName = _setupObj["xslt"]["name"];
const _styleMode = _setupObj["import"]["styleMode"];
const _tableMode = _setupObj["import"]["tableMode"];
_global["progressbar"].init(0, 2, "", localize(_global.importProgressLabel));
_global["progressbar"].step();
var _transformParams = [];
_transformParams.push(["app", "indesign"]);
_transformParams.push(["style-mode", _styleMode]);
_transformParams.push(["table-mode", _tableMode]);
_transformParams.push(["fallback-paragraph-style-name", _defaultPStyleName]);
var _xsltFile = __getXSLTFile(_xsltFileName);
if(!_xsltFile) {
return null;
}
var _unpackFolderPath = "";
var _unpackFolder = _unpackObj["folder"];
if(_unpackFolder && _unpackFolder instanceof Folder && _unpackFolder.exists) {
_unpackFolderPath = _unpackFolder.fullName;
_transformParams.push(["package-base-uri", ".."]);
}
var _wordXMLFile = _unpackObj["word"]["document"];
if(!_wordXMLFile || !_wordXMLFile.exists) {
_global["log"].push(localize(_global.wordDocumentFileErrorMessage, _wordXMLFile));
return null;
}
_transformParams.push(["document-file-name",_wordXMLFile.name]);
var _rootXMLElement = _doc.xmlElements.firstItem();
var _lastXMLElement = _rootXMLElement.xmlElements.lastItem();
if(_lastXMLElement.isValid) {
_lastXMLElement = _lastXMLElement.getElements()[0];
} else {
_lastXMLElement = null;
}
if(File(_unpackFolderPath + "/" + "word/comments.xml").exists) {
_transformParams.push(["comments-file-path", "comments.xml"]);
}
if(File(_unpackFolderPath + "/" + "docProps/app.xml").exists) {
_transformParams.push(["app-props-file-path", "../docProps/app.xml"]);
}
if(File(_unpackFolderPath + "/" + "docProps/core.xml").exists) {
_transformParams.push(["core-props-file-path", "../docProps/core.xml"]);
}
if(File(_unpackFolderPath + "/" + "docProps/custom.xml").exists) {
_transformParams.push(["custom-props-file-path", "../docProps/custom.xml"]);
}
if(File(_unpackFolderPath + "/" + "word/_rels/document.xml.rels").exists) {
_transformParams.push(["document-relationships-file-path", "_rels/document.xml.rels"]);
}
if(File(_unpackFolderPath + "/" + "word/endnotes.xml").exists) {
_transformParams.push(["endnotes-file-path", "endnotes.xml"]);
}
if(File(_unpackFolderPath + "/" + "word/_rels/endnotes.xml.rels").exists) {
_transformParams.push(["endnotes-relationships-file-path", "_rels/endnotes.xml.rels"]);
}
if(File(_unpackFolderPath + "/" + "word/footnotes.xml").exists) {
_transformParams.push(["footnotes-file-path", "footnotes.xml"]);
}
if(File(_unpackFolderPath + "/" + "word/_rels/footnotes.xml.rels").exists) {
_transformParams.push(["footnotes-relationships-file-path", "_rels/footnotes.xml.rels"]);
}
if(File(_unpackFolderPath + "/" + "word/numbering.xml").exists) {
_transformParams.push(["numbering-file-path", "numbering.xml"]);
}
if(File(_unpackFolderPath + "/" + "word/styles.xml").exists) {
_transformParams.push(["styles-file-path", "styles.xml"]);
}
var _userXMLImportPreferences = _doc.xmlImportPreferences.properties;
try {
/* XML Import Preferences */
_doc.xmlImportPreferences.properties = {
importStyle:XMLImportStyles.APPEND_IMPORT,
allowTransform:true,
transformFilename:_xsltFile,
transformParameters:_transformParams,
repeatTextElements:false,
ignoreWhitespace:false,
createLinkToXML:false,
ignoreUnmatchedIncoming:false,
importCALSTables:false,
importTextIntoTables:false,
importToSelected:false,
removeUnmatchedExisting:false
};
/* Import XML File */
_doc.importXML(_wordXMLFile);
} catch(_error) {
_global["log"].push(localize(_global.indesignErrorMessage, _error.message, _error.line));
return null;
} finally {
_doc.xmlImportPreferences.properties = _userXMLImportPreferences;
}
/* Check: XML import successful? */
var _wordXMLElement = _rootXMLElement.xmlElements.lastItem();
if(!_wordXMLElement.isValid) {
_global["log"].push(localize(_global.xmlDataImportErrorMessage));
return null;
}
_wordXMLElement = _wordXMLElement.getElements()[0];
if(_wordXMLElement === _lastXMLElement) {
_global["log"].push(localize(_global.xmlDataImportErrorMessage));
return null;
}
_global["progressbar"].step();
return _wordXMLElement;
} /* END function __importXML */
/**
* Get XSL transformation file
* @param {String} _xsltFileName
* @returns File
*/
function __getXSLTFile(_xsltFileName) {
if(!_xsltFileName || _xsltFileName.constructor !== String) {
throw new Error("Object as string required.");
}
const _xslFileExtRegExp = new RegExp("\\.xsl$", "i");
var _xsltFolder = __getScriptFolder();
if(!_xsltFolder || !_xsltFolder.exists) {
_global["log"].push(localize(_global.scriptFolderErrorMessage));
return false;
}
var _xsltFile = _xsltFolder.getFiles(_xsltFileName)[0];
if(!_xsltFile || !_xsltFile.exists) {
_xsltFile = File.openDialog(localize(_global.selectXSLFile, _xsltFileName), null, false);
if(!_xsltFile) {
return null;
}
}
if(!_xsltFile.exists || !_xslFileExtRegExp.test(_xsltFile.name)) {
_global["log"].push(localize(_global.noXSLFileErrorMessage));
return null;
}
return _xsltFile;
} /* END function __getXSLTFile */
/**
* Get path for current script
* @returns String
*/
function __getScriptFolder() {
var _skriptFolder;
try {
_skriptFolder = app.activeScript.parent;
} catch(_error) {
_skriptFolder = File(_error.fileName).parent;
}
if(!_skriptFolder || !_skriptFolder.exists) {
return null;
}
return _skriptFolder;
} /* END function __getScriptFolder */
/**
* Mount InDesign items before placing XML
* @param {Document} _doc
* @param {Object} _unpackObj
* @param {XMLElement} _wordXMLElement
* @param {Object} _setupObj
* @returns Object
*/
function __mountBeforePlaced(_doc, _unpackObj, _wordXMLElement, _setupObj) {
if(!_doc || !(_doc instanceof Document) || !_doc.isValid) {
throw new Error("Document as parameter required.");
}
if(!_unpackObj || !(_unpackObj instanceof Object)) {
throw new Error("Object as parameter required.");
}
if(!_wordXMLElement || !(_wordXMLElement instanceof XMLElement) || !_wordXMLElement.isValid) {
throw new Error("XMLElement as parameter required.");
}
if(!_setupObj || !(_setupObj instanceof Object)) {
throw new Error("Object as parameter required.");
}
/* 01 Metadata */
__handleMetadata(_doc, _wordXMLElement, _setupObj);
/* 02 Breaks */
__insertBreaks(_doc, _wordXMLElement, _setupObj);
/* 03 Comments */
__handleComments(_doc, _wordXMLElement, _setupObj);
/* 04 Index */
__handleIndexmarks(_doc, _wordXMLElement, _setupObj);
/* 05Hyperlinks */
__handleHyperlinks(_doc, _wordXMLElement, _setupObj);
/* 06 Cross-references */
__handleCrossReferences(_doc, _wordXMLElement, _setupObj);
/* 07Bookmarks */
__handleBookmarks(_doc, _wordXMLElement, _setupObj);
/* 08 Textboxes */
__handleTextboxes(_doc, _wordXMLElement, _setupObj);
/* 09 Images */
__handleImages(_doc, _wordXMLElement, _unpackObj, _setupObj);
/* 10 Track Changes */
__handleTrackChanges(_doc, _wordXMLElement, _setupObj);
/*
Last in chain: Footnotes and Endnotes
(After all XML manipulations, since XML elements must be removed from footnotes and endnotes)
*/
/* 11 Footnotes */
__handleFootnotes(_doc, _wordXMLElement, _setupObj);
/* 12 Endnotes */
__handleEndnotes(_doc, _wordXMLElement, _setupObj);
return {};
} /* END function __mountBeforePlaced */
/**
* Handle Document Metadata
* @param {Document} _doc
* @param {XMLElement} _wordXMLElement
* @param {Object} _setupObj
* @returns Boolean
*/
function __handleMetadata(_doc, _wordXMLElement, _setupObj) {
if(!_doc || !(_doc instanceof Document) || !_doc.isValid) {
throw new Error("Document as parameter required.");
}
if(!_wordXMLElement || !(_wordXMLElement instanceof XMLElement) || !_wordXMLElement.isValid) {
throw new Error("XMLElement as parameter required.");
}
if(!_setupObj || !(_setupObj instanceof Object)) {
throw new Error("Object as parameter required.");
}
const METADATA_TAG_NAME = _setupObj["metadata"]["tag"];
const ARE_METADATA_MERGED = _setupObj["metadata"]["areMerged"];
const ARE_METADATA_REPLACED = _setupObj["metadata"]["areReplaced"];
const ARE_METADATA_IGNORED = _setupObj["metadata"]["areIgnored"];
var _metadataXMLElementArray = _wordXMLElement.evaluateXPathExpression("//" + METADATA_TAG_NAME);
if(_metadataXMLElementArray.length === 0) {
return true;
}
if(ARE_METADATA_IGNORED) {
return true;
}
if(ARE_METADATA_MERGED) {
__insertMetadata(_doc, _metadataXMLElementArray[0], "merge", _setupObj);
return true;
}
if(ARE_METADATA_REPLACED) {
__insertMetadata(_doc, _metadataXMLElementArray[0], "replace", _setupObj);
return true;
}
return true;
} /* END function __handleMetadata */
/**
* Create Comments
* @param {Document} _doc
* @param {XMLElement} _metadataXMLElement
* @param {String} _mode Values: merge | replace
* @param {Object} _setupObj
* @returns Boolean
*/
function __insertMetadata(_doc, _metadataXMLElement, _mode, _setupObj) {
if(!_doc || !(_doc instanceof Document) || !_doc.isValid) {
throw new Error("Document as parameter required.");
}
if(!_metadataXMLElement || !(_metadataXMLElement instanceof XMLElement) || !_metadataXMLElement.isValid) {
throw new Error("XMLElement as parameter required.");
}
if(!_mode || _mode.constructor !== String || (_mode !== "merge" && _mode !== "replace")) {
throw new Error("String as parameter required.");
}
if(!_setupObj || !(_setupObj instanceof Object)) {
throw new Error("Object as parameter required.");
}
const TITLE_ATTRIBUTE_NAME = _setupObj["metadata"]["attributes"]["title"];
const AUTHOR_ATTRIBUTE_NAME = _setupObj["metadata"]["attributes"]["author"];
const DESCRIPTION_ATTRIBUTE_NAME = _setupObj["metadata"]["attributes"]["description"];
const CATEGORY_ATTRIBUTE_NAME = _setupObj["metadata"]["attributes"]["category"];
const KEYWORDS_ATTRIBUTE_NAME = _setupObj["metadata"]["attributes"]["keywords"];
const SUBJECT_ATTRIBUTE_NAME = _setupObj["metadata"]["attributes"]["subject"];
const DC_NS = "http://purl.org/dc/elements/1.1/";
const METADATA_VALUE_SEPARATOR = "; ";
var _metadataCounter = 0;
var _isSet = false;
var _metadataPrefs = _doc.metadataPreferences;
/* Document title */
var _titleAttribute = _metadataXMLElement.xmlAttributes.itemByName(TITLE_ATTRIBUTE_NAME);
if(_titleAttribute.isValid && _titleAttribute.value) {
var _docTitle = "";
if(_mode === "merge") {
_docTitle = (_metadataPrefs.documentTitle && _metadataPrefs.documentTitle + METADATA_VALUE_SEPARATOR) || "";
}
_docTitle += _titleAttribute.value;
var _titleObjArray = __getItemObjArray(_docTitle, [{ "name":"xml:lang", "value":"x-default" }]);
_isSet = __setXMPContainerProperties(_doc, "ALT", DC_NS, "dc:title", _titleObjArray, "replace");
if(_isSet) {
_metadataCounter += 1;
}
}
/* Authors */
var _authorAttribute = _metadataXMLElement.xmlAttributes.itemByName(AUTHOR_ATTRIBUTE_NAME);
if(_authorAttribute.isValid && _authorAttribute.value) {
var _creatorObjArray = __getItemObjArray(_authorAttribute.value, [], "split");
_isSet = __setXMPContainerProperties(_doc, "SEQ", DC_NS, "dc:creator", _creatorObjArray, _mode);
if(_isSet) {
_metadataCounter += 1;
}
}
/* Description */
var _descriptionAttribute = _metadataXMLElement.xmlAttributes.itemByName(DESCRIPTION_ATTRIBUTE_NAME);
if(_descriptionAttribute.isValid && _descriptionAttribute.value) {
var _description = "";
if(_mode === "merge") {
_description = (_metadataPrefs.description && _metadataPrefs.description + METADATA_VALUE_SEPARATOR) || "";
}
_description += _descriptionAttribute.value;
var _descObjArray = __getItemObjArray(_description, [{ "name":"xml:lang", "value":"x-default" }]);
_isSet = __setXMPContainerProperties(_doc, "ALT", DC_NS, "dc:description", _descObjArray, "replace");
if(_isSet) {
_metadataCounter += 1;
}
}
/* Keywords */
var _keywordsAttribute = _metadataXMLElement.xmlAttributes.itemByName(KEYWORDS_ATTRIBUTE_NAME);
if(_keywordsAttribute.isValid && _keywordsAttribute.value) {
var _subjectObjArray = __getItemObjArray(_keywordsAttribute.value, [], "split");
_isSet = __setXMPContainerProperties(_doc, "BAG", DC_NS, "dc:subject", _subjectObjArray, _mode);
if(_isSet) {
_metadataCounter += 1;
}
}
if(_global["isLogged"]) {
_global["log"].push(localize(_global.insertMetadataMessage, _metadataCounter));
}
return true;
} /* END function __insertMetadata */
/**