nscomponentsreact
Version:
React Wrapper Components for NSComponents
1,613 lines (1,519 loc) • 159 kB
JavaScript
var nsModuleExport = function(root,name,prototype)
{
if(typeof exports === 'object' && typeof module === 'object')
{
module.exports[name] = prototype;
}
else if (typeof define === "function" && define.amd)
{
define(name,[], function () {return prototype;});
}
else if(typeof exports === 'object')
{
exports[name] = prototype;
}
else
{
root[name] = prototype;
}
};var nsIsWeb = function(root)
{
if(typeof exports === 'object' && typeof module === 'object')
{
return false;
}
else if (typeof define === "function" && define.amd)
{
return false;
}
else if(typeof exports === 'object')
{
return false;
}
else
{
return true;
}
};if(!nsIsWeb())
{
var nsutilRef = require('./nsUtil.min.js');
var NSUtil = nsutilRef.NSUtil;
}
var NSZip = (function()
{
var NSZip = function(config)
{
var self = this;
var setting = {};
var objFiles = {};
var util = null;
var initialize = function()
{
if(!config)
{
config = {};
}
/*setting = {
fileName: config["fileName"] || "download",
mimeType: config["mimeType"] || "application/zip"
};
if (setting.fileName.indexOf(".") === -1)
{
setting.fileName = setting.fileName + ".zip";
}*/
util = new ZipUtil();
};
var getFile = function(type,mimeType)
{
var objRet = null;
type = type ? type : "blob";
switch(type)
{
case "blob":
objRet = getBlob(mimeType);
break;
}
return objRet;
};
var addFolders = function(arrPath)
{
var arrReturn = null;
if(arrPath && arrPath.length > 0)
{
arrReturn = [];
for(var index = 0;index < arrPath.length;index++)
{
arrReturn.push(addFolder(arrPath[index]));
}
}
return arrReturn;
};
var addFolder = function(path)
{
return createFolder(path);
};
var addFile = function(path,content,prop)
{
return createFile(path,content,prop,false);
};
var createFolder = function(path)
{
path = util.addSlashAtEnd(path);
if(objFiles[path])
{
return objFiles[path].zipFile;
}
return createFile(path,null,null,true);
};
var createFile = function(path,content,prop,isDir)
{
prop = prop ? prop : {};
var item = {path: path,content: content,origContent: content};
item.created = new Date();
item.dataType = util.getDataType(content);
item.isDir = isDir ? true : false;
var parent = util.getParentFolder(path);
if(parent)
{
createFolder(parent);
}
item.isBase64 = (item.type == "base64");
item.isBinary = (item.type == "binary");
var isUnicodeString = (item.dataType === "string") && item.isBase64 && item.isBinary;
if (item.type != "binary")
{
item.isBinary = !isUnicodeString;
}
if(item.isDir || !path || !path.length)
{
item.dataType = "string";
item.isBase64 = false;
item.isBinary = true;
item.content = "";
}
item.content = getContent(item);
var zipFile = new ZipFile(util,item,self);
objFiles[path] = {item: item,zipFile: zipFile};
return zipFile;
};
var getContent = function(item)
{
var refine = function(data)
{
var dataType = item.dataType;
if(dataType)
{
if(dataType === "string")
{
if(item.isBase64)
{
data = util.base64Decode(data);
}
else if(item.isBinary)
{
/*var arrData = new Uint8Array(data.length);
data = util.fillArrayWithString(data,arrData);*/
}
}
else if (dataType === "arraybuffer")
{
data = new Uint8Array(item);
}
}
else
{
console.warn("DataType cannot be detected for file " + item.path);
}
return data;
};
var content = item.content;
var isBlob = (content instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(content)) !== -1);
if(isBlob && typeof FileReader !== "undefined")
{
return new Promise(function (resolve, reject)
{
var reader = new FileReader();
reader.onload = function(event)
{
item.content = refine(event.target.result);
resolve(event.target.result);
};
reader.onerror = function(event)
{
console.error(event.target.error);
reject(event.target.error);
};
reader.readAsArrayBuffer(content);
});
}
return refine(content);
};
var clear = function()
{
objFiles = {};
};
var getBlob = function(mimeType)
{
mimeType = mimeType ? mimeType : "application/zip";
var textOutput = buildFileStream();
var uInt8Output = util.buildUint8Array(textOutput);
clear();
return new Blob([uInt8Output], { type: setting.mimeType });
};
var buildFileStream = function(initContent)
{
initContent = initContent ? initContent : "";
var len = Object.keys(objFiles).length;
var middleContent = "";
var lL = 0;
var cL = 0;
for(var path in objFiles)
{
var file = objFiles[path].item;
var objHeader = getHeader(file, lL);
var fileHeader = objHeader.fileHeader;
var folderHeader = objHeader.folderHeader;
var content = objHeader.content;
lL += fileHeader.length + content.length;
cL += folderHeader.length;
initContent += fileHeader + content;
middleContent += folderHeader;
}
var endContent = buildFolderEnd(len, cL, lL);
return initContent + middleContent + endContent;
};
var getHeader = function(file,offset)
{
var content = util.utf8_encode(file.content);
var path = file.path;
var created = file.created;
var utfPath = util.utf8_encode(path);
var isUTF8 = (utfPath !== path);
var time = util.convertTime(created);
var dt = util.convertDate(created);
var extraFields = "";
if (isUTF8)
{
var uExtraFieldPath = util.decToHex(1, 1) + util.decToHex(util.getFromCrc32Table(utfPath), 4) + utfPath;
extraFields = "\x75\x70" + util.decToHex(uExtraFieldPath.length, 2) + uExtraFieldPath;
}
var header = '\x0A\x00' +
(isUTF8 ? '\x00\x08' : '\x00\x00') + // general purpose bit flag
'\x00\x00' +
util.decToHex(time, 2) + // last modified time
util.decToHex(dt, 2) + // last modified date
util.decToHex(content ? util.getFromCrc32Table(content) : 0, 4) +
util.decToHex(content ? content.length : 0, 4) + // compressed size
util.decToHex(content ? content.length : 0, 4) + // uncompressed size
util.decToHex(utfPath.length, 2) + // file name length
util.decToHex(extraFields.length, 2); // extra field length
var fileHeader = 'PK\x03\x04' + header + utfPath + extraFields;
var folderHeader = 'PK\x01\x02' + // central header
'\x14\x00' +
header + // file header
'\x00\x00' +
'\x00\x00' +
'\x00\x00' +
(content ? '\x00\x00\x00\x00' : '\x10\x00\x00\x00') + // external file attributes
util.decToHex(offset, 4) + // relative offset of local header
utfPath + // file name
extraFields; // extra field
return { fileHeader: fileHeader, folderHeader: folderHeader, content: content || '' };
};
var buildFolderEnd = function(totalEntries,size,startOffset)
{
var retValue = "PK\x05\x06" + "\x00\x00" + "\x00\x00";
retValue += util.decToHex(totalEntries, 2);
retValue += util.decToHex(totalEntries, 2);
retValue += util.decToHex(size, 4);
retValue += util.decToHex(startOffset, 4);
retValue += "\x00\x00";
return retValue;
};
var downloadFile = function(fileName,mimeType,type,content)
{
fileName = fileName ? fileName : "download";
if (fileName.indexOf(".") === -1)
{
fileName = fileName + ".zip";
}
content = content ? content : getFile(type,mimeType);
util.downloadFile(fileName,content);
};
var ZipFile = function(util,item,objRoot)
{
var self = this;
var addFolder = function(path)
{
return objRoot.addFolder(getPath(path));
};
var addFile = function(path,content)
{
return objRoot.addFile(getPath(path),content);
};
var getPath = function(path)
{
return item.path + path;
};
if(item.isDir)
{
self.addFolder = addFolder;
self.addFile = addFile;
}
};
var ZipUtil = function()
{
var self = this;
var crcTable = [];
var base64Key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var initialize = function()
{
crcTable = makeCRCTable();
};
//https://stackoverflow.com/questions/18638900/javascript-crc32
var makeCRCTable = function()
{
var c;
var crcTable = [];
for(var n =0; n < 256; n++)
{
c = n;
for(var k =0; k < 8; k++)
{
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
crcTable[n] = c;
}
return crcTable;
};
var getFromCrc32Table = function(content, crc)
{
if(typeof content === "undefined" || !content.length)
{
return 0;
}
if(!crc)
{
crc = 0;
}
crc ^= (-1);
var dataType = util.getDataType(content);
if(dataType === "string")
{
var ch = 0;
var k = 0;
var l = 0;
var len = content.length;
for (var count = 0;count < len;count++)
{
ch = content.charCodeAt(count);
k = (crc ^ ch) & 0xFF;
l = crcTable[k];
crc = (crc >>> 8) ^ l;
}
}
else
{
var ch = 0;
var k = 0;
var l = 0;
var len = content.length;
for (var count = 0;count < len;count++)
{
ch = content[count];
k = (crc ^ ch) & 0xFF;
l = crcTable[k];
crc = (crc >>> 8) ^ l;
}
}
return crc ^ (-1);
};
var buildUint8Array = function(content)
{
var retValue = new Uint8Array(content.length);
for (var count = 0; count < content.length; count++)
{
retValue[count] = content.charCodeAt(count);
}
return retValue;
};
//http://www.navioo.com/javascript/tutorials/Javascript_utf8_encode_1529.html
// Encodes an ISO-8859-1 string to UTF-8
var utf8_encode = function(str)
{
var retValue = "";
var str = str.replace(/\r\n/g, "\n");
var len = str.length;
var start = 0;
var end = 0;
var enc = null;
var ch = null;
for(var count = 0;count < len;count++)
{
ch = str.charCodeAt(count);
enc = null;
if(ch < 128)
{
end++;
}
else if(ch > 127 && ch < 2048)
{
enc = String.fromCharCode(ch >> 6 | 192);
enc += String.fromCharCode((ch & 63) | 128);
}
else
{
enc = String.fromCharCode((ch >> 12) | 224);
enc += String.fromCharCode(((ch >> 6) & 63) | 128);
enc += String.fromCharCode((ch & 63) | 128);
}
if (enc != null)
{
if (end > start)
{
retValue += str.substring(start, end);
}
retValue += enc;
start = end = count + 1;
}
}
if (end > start)
{
retValue += str.substring(start,str.length);
}
return retValue;
};
//http://www.navioo.com/javascript/tutorials/Javascript_utf8_decode_1528.html
// Converts a UTF-8 encoded string to ISO-8859-1
var utf8_decode = function(str)
{
var arrReturn = [];
var count = 0;
var retCount = 0;
var char1 = 0;
var char2 = 0;
var char3 = 0;
str += "";
while (count < str.length)
{
char1 = str.charCodeAt(count);
if (char1 < 128)
{
arrReturn[retCount++] = String.fromCharCode(char1);
count++;
}
else if ((char1 > 191) && (char1 < 224))
{
char2 = str.charCodeAt(count+1);
arrReturn[retCount++] = String.fromCharCode(((char1 & 31) << 6) | (char2 & 63));
count += 2;
}
else
{
char2 = str.charCodeAt(count+1);
char3 = str.charCodeAt(count+2);
arrReturn[retCount++] = String.fromCharCode(((char1 & 15) << 12) | ((char2 & 63) << 6) | (char3 & 63));
count += 3;
}
}
return arrReturn.join('');
};
var decToHex = function(number, bytes)
{
var retValue = "";
for(var count = 0;count < bytes;count++)
{
retValue += String.fromCharCode(number & 0xFF);
number = number >>> 8;
}
return retValue;
};
var fillArrayWithString = function(str,arrData)
{
for (var count = 0;count < str.length;count++)
{
arrData[count] = str.charCodeAt(count) & 0xFF;
}
return arrData;
};
var convertTime = function(date)
{
var hour = date.getUTCHours();
hour = hour << 6;
hour = hour | date.getUTCMinutes();
hour = hour << 5;
hour = hour | date.getUTCSeconds() / 2;
return hour;
};
var convertDate = function(date)
{
var retDate = date.getUTCFullYear() - 1980;
retDate = retDate << 4;
retDate = retDate | (date.getUTCMonth() + 1);
retDate = retDate << 5;
retDate = retDate | date.getUTCDate();
return retDate;
};
var addSlashAtEnd = function(path)
{
if (path.slice(-1) !== "/")
{
path += "/";
}
return path;
};
var getParentFolder = function(path)
{
if (path.slice(-1) === '/')
{
path = path.substring(0, path.length - 1);
}
var lastSlash = path.lastIndexOf('/');
return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
};
var getDataType = function(data)
{
if (typeof data === "string")
{
return "string";
}
if (Object.prototype.toString.call(data) === "[object Array]")
{
return "array";
}
if (typeof Buffer !== "undefined" && data instanceof Buffer)
{
return "nodebuffer";
}
if (data instanceof Uint8Array)
{
return "uint8array";
}
if (data instanceof ArrayBuffer)
{
return "arraybuffer";
}
};
var base64Decode = function(data)
{
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0, resultIndex = 0;
if(data.indexOf('base64,') > -1)
{
var index = data.indexOf('base64,') + 'base64,'.length;
data = data.substring(index);
}
data = data.replace(/[^A-Za-z0-9\+\/\=]/g, "");
var totalLength = data.length * 3 / 4;
if(data.charAt(data.length - 1) === base64Key.charAt(64))
{
totalLength--;
}
if(data.charAt(data.length - 2) === base64Key.charAt(64))
{
totalLength--;
}
//totalLength is base64 expected length
if (totalLength % 1 !== 0)
{
throw new Error("Invalid base64 data");
}
var retValue = new Uint8Array(totalLength|0);
while (i < data.length)
{
enc1 = base64Key.indexOf(data.charAt(i++));
enc2 = base64Key.indexOf(data.charAt(i++));
enc3 = base64Key.indexOf(data.charAt(i++));
enc4 = base64Key.indexOf(data.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
retValue[resultIndex++] = chr1;
if (enc3 !== 64)
{
retValue[resultIndex++] = chr2;
}
if (enc4 !== 64)
{
retValue[resultIndex++] = chr3;
}
}
return retValue;
};
var downloadFile = function(fileName,content)
{
if ("msSaveOrOpenBlob" in window.navigator)
{
window.navigator.msSaveOrOpenBlob(content, fileName);
}
else
{
var element = document.createElement("a");
var url = window.URL.createObjectURL(content);
element.setAttribute("href", url);
element.setAttribute("download", fileName);
element.style.display = "none";
document.body.appendChild(element);
element.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(element);
}
};
initialize();
self.getFromCrc32Table = getFromCrc32Table;
self.buildUint8Array = buildUint8Array;
self.utf8_encode = utf8_encode;
self.utf8_decode = utf8_decode;
self.decToHex = decToHex;
self.fillArrayWithString = fillArrayWithString;
self.convertTime = convertTime;
self.convertDate = convertDate;
self.addSlashAtEnd = addSlashAtEnd;
self.getParentFolder = getParentFolder;
self.getDataType = getDataType;
self.base64Decode = base64Decode;
self.downloadFile = downloadFile;
};
initialize();
self.addFolder = addFolder;
self.addFolders = addFolders;
self.addFile = addFile;
self.getBlob = getBlob;
self.getFile = getFile;
self.downloadFile = downloadFile;
};
return NSZip;
})();
nsModuleExport(this,"NSZip",NSZip);var nsExtendPrototype = (function()
{
var nsExtendPrototype = function(source,destination)
{
if(source && destination)
{
destination.prototype = Object.create(source.prototype);
destination.prototype.constructor = destination;
destination.prototype.base = source.prototype;
return source.prototype;
}
return null;
};
return nsExtendPrototype;
})();
var NSDocxExport = (function()
{
var NSDocxExport = function(config)
{
this.__config = config;
this.util = null;
this.__exportUtil = null;
this.__setting = {};
this.__objOrientation = {};
this.__arrDefault = [];
this.__arrOverride = [];
this.__arrRelationship = [];
this.__relationshipID = 0;
this.__extraFiles = {};
this.__arrChildren = [];
this.__pageSection = null;
this.__styles = null;
this.__enableChunk = true;
this.__initialize();
};
NSDocxExport.prototype.process = function()
{
var self = this;
var objPromise = new Promise(function(resolve,reject)
{
var mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
var zip = new NSZip();
self.__save(zip).then(function(){
zip.downloadFile(self.__setting.fileName,mimeType);
resolve(true);
}).catch(function(error){
reject(error);
});
});
return objPromise;
};
NSDocxExport.prototype.addSection = function()
{
this.__enableChunk = false;
var section = new Section(this);
this.__arrChildren.push(section)
return section;
};
NSDocxExport.prototype.addParagraph = function(option)
{
this.__enableChunk = false;
var paragraph = new Paragraph(this,option);
this.__arrChildren.push(paragraph)
return paragraph;
};
NSDocxExport.prototype.addTable = function(option)
{
this.__enableChunk = false;
var table = new Table(this,option);
this.__arrChildren.push(table)
return table;
};
NSDocxExport.prototype.addHeader = function(type)
{
//this.__enableChunk = false;
var header = this.__pageSection.addHeader(type);
return header;
};
NSDocxExport.prototype.addFooter = function(type)
{
//this.__enableChunk = false;
var footer = this.__pageSection.addFooter(type);
return footer;
};
NSDocxExport.prototype.styles = function(value)
{
if(value && value instanceof Styles)
{
this.__styles = value;
}
else
{
!this.__styles && (this.__styles = new Styles(this,value));
}
return this.__styles;
};
NSDocxExport.prototype.getPageSection = function()
{
return this.__pageSection;
};
NSDocxExport.prototype.__initialize = function()
{
if(!this.__config)
{
this.__config = {};
}
this.util = new NSUtil();
this.__exportUtil = new ExportUtil(this.util);
this.__setting = {
fileName: this.__config["fileName"] || "download",
htmlSetting: this.__config["htmlSetting"],
printSetting: this.__config["printSetting"],
styles: this.__config["styles"],
};
this.__setHtmlSetting();
this.__setPrintSetting();
this.__initMargins();
this.__initOrientation();
this.__pageSection = new Section(this);
if(this.__setting.fileName.indexOf(".") === -1)
{
this.__setting.fileName = this.__setting.fileName + ".docx";
}
var arrStyles = this.__getDefaultStyle();
var styles = this.__setting.styles || {};
if(styles.styles && styles.styles.length)
{
arrStyles = arrStyles.concat(styles.styles);
}
styles.styles = arrStyles;
this.styles(styles);
};
//by default TableNormal and TableGrid are available for table
NSDocxExport.prototype.__getDefaultStyle = function()
{
var arrDefault = [];
var tblNormal = {
id: "TableNormal",
type: "table",
name: "Normal Table",
basedOn: "Normal",
uiPriority: "99",
semiHidden: true,
unhideWhenUsed: true,
quickFormat: true,
table: {
cellMargin: { top: {width: 0,type: "dxa"},
left: {width: 108,type: "dxa"},
bottom: {width: 0,type: "dxa"},
right: {width: 108,type: "dxa"},
},
},
};
arrDefault.push(tblNormal);
var tblGrid = {
id: "TableGrid",
type: "table",
name: "Table Grid",
basedOn: "TableNormal",
uiPriority: "59",
paragraph:{spacing: { after: 0 },},
table: {
borders: {top: {color: "auto",space: 0,size: 4,value: "single"},
left: {color: "auto",space: 0,size: 4,value: "single"},
bottom: {color: "auto",space: 0,size: 4,value: "single"},
right: {color: "auto",space: 0,size: 4,value: "single"},
insideH: {color: "auto",space: 0,size: 4,value: "single"},
insideV: {color: "auto",space: 0,size: 4,value: "single"},
},
cellMargin: { top: {width: 0,type: "dxa"},
left: {width: 108,type: "dxa"},
bottom: {width: 0,type: "dxa"},
right: {width: 108,type: "dxa"},
},
},
};
arrDefault.push(tblGrid);
return arrDefault;
};
NSDocxExport.prototype.__setPrintSetting = function()
{
var printSetting = this.__setting.printSetting || {};
this.__setting.printSetting = {
orientation: printSetting["orientation"] || "portrait",
margins: printSetting["margins"]
};
};
NSDocxExport.prototype.__initOrientation = function()
{
this.__objOrientation = {landscape:{width: 16838,height: 11906,orientation: "landscape"},
portrait:{width: 11906,height: 16838,orientation: "portrait"},
};
};
NSDocxExport.prototype.__initMargins = function()
{
/*var margins = this.__setting.printSetting.margins;
if(margins)
{
this.__setting.printSetting.margins = {
top: this.util.isUndefinedOrNull(margins["top"]) ? null : parseInt(margins["top"]),
right: this.util.isUndefinedOrNull(margins["right"]) ? null : parseInt(margins["right"]),
bottom: this.util.isUndefinedOrNull(margins["bottom"]) ? null : parseInt(margins["bottom"]),
left: this.util.isUndefinedOrNull(margins["left"]) ? null : parseInt(margins["left"]),
header: this.util.isUndefinedOrNull(margins["header"]) ? null : parseInt(margins["header"]),
footer: this.util.isUndefinedOrNull(margins["footer"]) ? null : parseInt(margins["footer"]),
gutter: this.util.isUndefinedOrNull(margins["gutter"]) ? null: parseInt(margins["gutter"]),
};
}*/
var margins = this.__setting.printSetting.margins || {};
this.__setting.printSetting.margins = {
top: this.util.isUndefinedOrNull(margins["top"]) ? 1440 : parseInt(margins["top"]),
right: this.util.isUndefinedOrNull(margins["right"]) ? 1440 : parseInt(margins["right"]),
bottom: this.util.isUndefinedOrNull(margins["bottom"]) ? 1440 : parseInt(margins["bottom"]),
left: this.util.isUndefinedOrNull(margins["left"]) ? 1440 : parseInt(margins["left"]),
header: this.util.isUndefinedOrNull(margins["header"]) ? 708 : parseInt(margins["header"]),
footer: this.util.isUndefinedOrNull(margins["footer"]) ? 708 : parseInt(margins["footer"]),
gutter: this.util.isUndefinedOrNull(margins["gutter"]) ? 0: parseInt(margins["gutter"]),
};
};
NSDocxExport.prototype.__save = function(zip)
{
var self = this;
var resolveOtherFiles = function()
{
word.addFile("document.xml",self.__getDocumentFile());
if(self.__styles)
{
var styleXml = self.__styles.toXml();
if(styleXml)
{
self.__addFile(null,"styles.xml","http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles","application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml")
console.log(styleXml);
word.addFile("styles.xml",styleXml);
}
}
word.addFile("numbering.xml",);
var wordRels = word.addFolder("_rels");
wordRels.addFile("document.xml.rels",self.__getWordRels());
zip.addFile("_rels/.rels", self.__getRels());
zip.addFile("[Content_Types].xml", self.__getContentTypesXml());
self.__addExtraFiles.call(self,zip,word);
};
var objPromise = null;
var word = zip.addFolder("word");
if(this.__isChunk())
{
objPromise = new Promise(function(resolve,reject)
{
self.__getHtmlContent(word).then(function(data){
if(data)
{
self.__addFile(null,"afchunk.mht","http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk","message/rfc822")
//self.__arrOverride.push({partName:"/word/afchunk.mht",contentType:"message/rfc822"});
//self.__arrRelationship.push({id:"htmlChunk",type:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk",target:"/word/afchunk.mht"});
word.addFile("afchunk.mht",data);
}
resolveOtherFiles();
resolve(true);
});
});
}
else
{
objPromise = new Promise(function(resolve,reject)
{
resolveOtherFiles();
resolve(true);
});
}
return objPromise;
};
NSDocxExport.prototype.__getContentTypesXml = function()
{
var isChunk = this.__isChunk();
var objDefault = {rels:{extension:"rels",contentType:"application/vnd.openxmlformats-package.relationships+xml",isDefault:true},
xml:{extension:"xml",contentType:"application/xml",isDefault:true},
png:{extension:"png",contentType:"image/png",isDefault:!isChunk},
jpeg:{extension:"jpeg",contentType:"image/jpeg",isDefault:!isChunk},
jpg:{extension:"jpg",contentType:"image/jpeg",isDefault:!isChunk},
bmp:{extension:"bmp",contentType:"image/bmp",isDefault:!isChunk},
gif:{extension:"gif",contentType:"image/gif",isDefault:!isChunk}
};
var objOverride = {document:{partName:"/word/document.xml",contentType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"},
};
var arrChild = [];
var item = null;
var key = null;
var count = 0;
for(key in objDefault)
{
item = objDefault[key];
if(item.isDefault)
{
arrChild.push(this.__exportUtil.getXML({
name: "Default",
attributes: {"Extension": item.extension,"ContentType": item.contentType}
}));
}
}
for(count = 0;count < this.__arrDefault.length;count++)
{
item = objDefault[this.__arrDefault[count]];
if(item && !item.isDefault)
{
arrChild.push(this.__exportUtil.getXML({
name: "Default",
attributes: {"Extension": item.extension,"ContentType": item.contentType}
}));
}
}
for(key in objOverride)
{
item = objOverride[key];
arrChild.push(this.__exportUtil.getXML({
name: "Override",
attributes: {"PartName": item.partName,"ContentType": item.contentType}
}));
}
for(count = 0;count < this.__arrOverride.length;count++)
{
item = this.__arrOverride[count];
if(item && !item.isDefault)
{
arrChild.push(this.__exportUtil.getXML({
name: "Override",
attributes: {"PartName": item.partName,"ContentType": item.contentType}
}));
}
}
return this.__exportUtil.getXML({
name: "Types",
ns: "contentTypes",
children: arrChild
});
};
NSDocxExport.prototype.__getRels = function()
{
var rels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n ' +
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n ' +
'<Relationship Id="Id1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="/word/document.xml"/>\n ' +
'</Relationships>';
return rels;
};
NSDocxExport.prototype.__getDocumentFile = function()
{
var printSetting = this.__setting.printSetting;
var orientation = printSetting.orientation;
if(orientation)
{
var itemOrient = this.__objOrientation[orientation.toLowerCase()];
if(itemOrient)
{
var pageSize = this.__pageSection.pgSz();
pageSize.width(itemOrient.width);
pageSize.height(itemOrient.height);
pageSize.orientation(itemOrient.orientation);
}
else
{
this.util.throwNSError("NSDocxExport","Orientation entered is not valid");
}
}
var margins = this.__setting.printSetting.margins;
if(margins)
{
var pageMargins = this.__pageSection.pgMar();
pageMargins.top(margins.top);
pageMargins.right(margins.right);
pageMargins.bottom(margins.bottom);
pageMargins.left(margins.left);
pageMargins.header(margins.header);
pageMargins.footer(margins.footer);
pageMargins.gutter(margins.gutter);
}
var objDocAttr = {"xmlns:w":"http://schemas.openxmlformats.org/wordprocessingml/2006/main",
"xmlns:m":"http://schemas.openxmlformats.org/officeDocument/2006/math",
"xmlns:r":"http://schemas.openxmlformats.org/officeDocument/2006/relationships",
"xmlns:wp":"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
"xmlns:a":"http://schemas.openxmlformats.org/drawingml/2006/main",
"xmlns:ns6":"http://schemas.openxmlformats.org/schemaLibrary/2006/main",
"xmlns:c":"http://schemas.openxmlformats.org/drawingml/2006/chart",
"xmlns:ns8":"http://schemas.openxmlformats.org/drawingml/2006/chartDrawing",
"xmlns:dgm":"http://schemas.openxmlformats.org/drawingml/2006/diagram",
"xmlns:pic":"http://schemas.openxmlformats.org/drawingml/2006/picture",
"xmlns:ns11":"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",
"xmlns:dsp":"http://schemas.microsoft.com/office/drawing/2008/diagram",
"xmlns:ns13":"urn:schemas-microsoft-com:office:excel",
"xmlns:o":"urn:schemas-microsoft-com:office:office",
"xmlns:v":"urn:schemas-microsoft-com:vml",
"xmlns:w10":"urn:schemas-microsoft-com:office:word",
"xmlns:ns17":"urn:schemas-microsoft-com:office:powerpoint",
"xmlns:odx":"http://opendope.org/xpaths",
"xmlns:odc":"http://opendope.org/conditions",
"xmlns:odq":"http://opendope.org/questions",
"xmlns:odi":"http://opendope.org/components",
"xmlns:odgm":"http://opendope.org/SmartArt/DataHierarchy",
"xmlns:ns24":"http://schemas.openxmlformats.org/officeDocument/2006/bibliography",
"xmlns:ns25":"http://schemas.openxmlformats.org/drawingml/2006/compatibility",
"xmlns:ns26":"http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"
};
var arrBody = [];
if(this.__isChunk())
{
var id = null;
for(var count = 0;count < this.__arrRelationship.length;count++)
{
if(this.__arrRelationship[count].target == "afchunk.mht")
{
id = this.__arrRelationship[count].id;
break;
}
}
if(id)
{
arrBody.push("<w:altChunk r:id=\"" + id + "\" />");
}
}
else
{
var arrChildren = this.__getWordChildren();
arrBody = arrBody.concat(arrChildren);
}
arrBody.push(this.__pageSection.toXml());
var body = this.__exportUtil.getXML({
name: 'w:body',
children: arrBody
});
console.log(body);
return this.__exportUtil.getXML({
name: 'w:document',
addXmlPrefix: true,
attributes: objDocAttr,
children: [body]
});
};
NSDocxExport.prototype.__getWordRels = function()
{
var item = null;
var arrChild = [];
for(var count = 0;count < this.__arrRelationship.length;count++)
{
item = this.__arrRelationship[count];
if(item)
{
arrChild.push(this.__exportUtil.getXML({
name: 'Relationship',
attributes: {'Id': item.id,'Type': item.type,'Target': item.target}
}));
}
}
var relationships = this.__exportUtil.getXML({
name: 'Relationships',
addXmlPrefix: true,
attributes: {xmlns:"http://schemas.openxmlformats.org/package/2006/relationships"},
children: arrChild
});
return relationships;
};
NSDocxExport.prototype.__addExtraFiles = function(zip,word)
{
if(this.__extraFiles && Object.keys(this.__extraFiles).length)
{
var arrFile = [];
var item = null;
var xml = null;
var file = null;
for(var key in this.__extraFiles)
{
arrFile = this.__extraFiles[key];
if(arrFile && arrFile.length)
{
for(var count = 0;count < arrFile.length;count++)
{
item = arrFile[count];
if(item)
{
file = item.file;
if(file)
{
if(this.util.isString(file))
{
xml = file;
}
else
{
xml = file.toXml();
}
if(xml)
{
console.log(xml);
zip.addFile(item.path + item.fileName, xml);
}
}
}
}
}
}
}
};
NSDocxExport.prototype.__addFile = function(file,fileType,relationType,overrideType)
{
var fileName = fileType;
var rId = null;
if(file)
{
fileName = this.__addExtraFile(fileType,file)
}
if(fileName)
{
rId = this.__addRelationship(file,relationType,fileName);
this.__addOverride(overrideType,"/word/" + fileName);
return {fileName: fileName,id: rId};
}
return null;
};
NSDocxExport.prototype.__addExtraFile = function(fileType,file,path,ext)
{
if(fileType && file)
{
fileType = fileType.toLowerCase();
if(!this.__extraFiles[fileType])
{
this.__extraFiles[fileType] = [];
}
ext = ext || "xml";
path = path || "word/"
var fileName = fileType + (this.__extraFiles[fileType].length + 1) + "." + ext;
this.__extraFiles[fileType].push({file: file,fileName: fileName,path: path});
return fileName;
}
return null;
};
NSDocxExport.prototype.__addRelationship = function(file,type,target)
{
if(type && target)
{
var id = "rId" + (++this.__relationshipID);
this.__arrRelationship.push({id:id,type:type,target:target});
return id;
}
};
NSDocxExport.prototype.__addOverride = function(contentType,partName)
{
if(contentType && partName)
{
this.__arrOverride.push({contentType:contentType,partName:partName});
}
};
NSDocxExport.prototype.__isChunk = function()
{
//return !(this.__arrChildren && this.__arrChildren.length)
return this.__enableChunk;
};
/* word related functions */
NSDocxExport.prototype.__getWordChildren = function()
{
var arrChildren = [];
var item = null;
var xml = null;
var length = this.__arrChildren.length;
for(var count = 0;count < length;count++)
{
item = this.__arrChildren[count];
if(item)
{
if(this.util.isString(item))
{
arrChildren.push(item);
}
else
{
xml = item.toXml();
if(xml)
{
arrChildren.push(xml);
}
}
}
}
return arrChildren;
};
/* end of word related functions */
/* html related functions */
NSDocxExport.prototype.__setHtmlSetting = function()
{
var htmlSetting = this.__setting.htmlSetting || {};
this.__setting.htmlSetting = {
element: htmlSetting["element"],
html: htmlSetting["html"],
htmlStyle: htmlSetting["htmlStyle"],
pageBreakTag: htmlSetting["pageBreakTag"],
enablePageNumber: Boolean.parse(htmlSetting["enablePageNumber"]),
loopNodesCallback: htmlSetting["loopNodesCallback"]// should be discouraged as it can be costly operation for large docs
};
};
NSDocxExport.prototype.__getHtmlContent = function(wordFolder)
{
var self = this;
var objPromise = new Promise(function(resolve,reject)
{
var htmlSetting = self.__setting.htmlSetting;
if(htmlSetting.element || htmlSetting.html)
{
var html = htmlSetting.html;
if(!html)
{
var element = self.util.getElement(htmlSetting.element);
if(element)
{
html = element.innerHTML;
}
else
{
self.util.throwNSError("NSDocxExport","Element does not exists as defined in config");
}
}
if(html)
{
self.__parseImages(html).then(function(objData){
if(objData)
{
html = objData.html;
var arrImages = objData.arrImages;
var styles = htmlSetting.htmlStyle || "";
var startHtml = "";
var endHtml = "";
var extraCSS = "";
if(htmlSetting.enablePageNumber)
{
startHtml = "<div class=\"Section1\">";
endHtml = "<table id=\"hrdftrtbl\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\"> <tr> <td> <div style=\"mso-element:footer\" id=\"f1\"> <p class=\"MsoFooter\"> <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"> <tr> <td align=\"center\" class=\"footer\"> <g:message code=\"offer.letter.page.label\"/> <span style=\"mso-field-code: PAGE \"></span> of <span style=\"mso-field-code: NUMPAGES \"></span> </td> </tr> </table> </p> </div> </td> </tr> </table> </div>";
extraCSS = "p.MsoHeader, li.MsoHeader, div.MsoHeader{ margin:0in; margin-top:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; } p.MsoFooter, li.MsoFooter, div.MsoFooter{ margin:0in 0in 1in 0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; } .footer { font-size: 9pt; } @page Section1{ size:8.5in 11.0in; margin:0.5in 0.5in 0.5in 0.5in; mso-header-margin:0.5in; mso-header:h1; mso-footer:f1; mso-footer-margin:0.5in; mso-paper-source:0; } div.Section1{ page:Section1; } table#hrdftrtbl{ margin:0in 0in 0in 9in; }";
}
html = startHtml + html + endHtml;
if(htmlSetting["pageBreakTag"])
{
html = html.replaceAll(htmlSetting["pageBreakTag"],"<br clear=all style='mso-special-character:line-break;page-break-before:always'>");
}
styles = styles + extraCSS;
html = self.__getDocHtml(html,arrImages,styles);
var strData = self.__convertHtmlToMht(html);
resolve(strData);
}
else
{
resolve(null);
}
});
}
else
{
resolve(null);
}
}
else
{
self.util.debug("NSDocxExport","Element and HTML are not defined in config");
resolve(null);
}
});
return objPromise;
};
NSDocxExport.prototype.__parseImages = function(html)
{
var self = this;
var replacerCallback = function(match,contentType,contentEncoding,encodedContent)
{
var index = arrImages.length;
var extension = contentType.split('/')[1];
var contentLocation = "file:///C:/fake/image" + index + "." + extension;
arrImages.push(getImageString(contentType,contentEncoding,contentLocation,encodedContent));
return "\"" + contentLocation + "\"";
};
var getImageString = function(contentType,contentEncoding,contentLocation,encodedContent)
{
var str = "Content-Type:" + self.__exportUtil.getNonNullString(contentType);
str += self.__exportUtil.newLine + "Content-Transfer-Encoding: " + self.__exportUtil.getNonNullString(contentEncoding);
str += self.__exportUtil.newLine + "Content-Location: " + self.__exportUtil.getNonNullString(contentLocation);
str += self.__exportUtil.newLine + self.__exportUtil.newLine + self.__exportUtil.getNonNullString(encodedContent);
str = "------=mhtDocumentPart" + self.__exportUtil.newLine + str + self.__exportUtil.newLine;
return str;
};
var arrImages = [];
var regex = /"data:(\w+\/\w+);(\w+),(\S+)"/g;
var objPromise = new Promise(function(resolve,reject)
{
if(html)
{
self.__replaceImagesByBase64(html).then(function(paramHtml){
html = paramHtml;
if (!/<img/g.test(html))
{
resolve({html: html,arrImages: arrImages});
}
else
{
html = html.replace(regex,replacerCallback);
resolve({html: html,arrImages: arrImages});
}
});
}
else
{
resolve(null);
}
});
return objPromise;
};
NSDocxExport.prototype.__replaceImagesByBase64 = function(html)
{
var parser = new DOMParser();
var tempDoc = parser.parseFromString(html,"text/html");
var arrImages = tempDoc.querySelectorAll("img");
var length = arrImages.length;
var resolved = 0;
var self = this;
var objPromise = new Promise(function(resolve,reject)
{
if(length)
{
var increaseResolved = function()
{
resolved++;
if(resolved == length)
{
resolve(tempDoc.getElementsByTagName("html")[0].outerHTML);
}
};
for(var count = 0;count < length;count++)
{
var img = arrImages[count];
var src = img.getAttribute("src");
if(!self.util.isBase64String(src))
{
var callback = function(paramImg,base64,orignalSrc,hasError,errorDetails)
{
//orignalSrc can be src or image itself
//paramImg is always giving last image in the outer loop so that is why looping orignalSrc to find the image
if(base64)
{
var tempImg = null;
for(var tempCount = 0;tempCount < length;tempCount++)
{
tempImg = arrImages[tempCount];
if(tempImg == orignalSrc || tempImg.getAttribute("src") == orignalSrc)
{
if(hasError)
{
self.util.warning("NSDocxExport","The image with source " + tempImg.getAttribute("src") + " has issues.So it is getting deleted.The error detials are :: " + errorDetails);
if(tempImg.parentNode)
{
tempImg.parentNode.removeChild(tempImg);
}
}
else
{
tempImg.setAttribute("src",base64);
}
break;
}
}
}
increaseResolved();
};
if(self.util.isSVGString(src))
{
self.util.convertSvgToBase64(src,callback);
}
else
{
//sending img and not src as we have to also pass the width
//this.util.convertImageToBase64(src,callback);
self.util.convertImageToBase64(img,true).then(function(item){
if(item)
{
callback(img,item.base64,item.param,item.hasError,item.errorDetails);
}
else
{
increaseResolved();
}
});
}
}
else
{
increaseResolved();
}
}
}
else
{
resolve(tempDoc.getElementsByTagName("html")[0].outerHTML);
}
});
return objPromise;
};
NSDocxExport.prototype.__getDocHtml = function(html,arrImages,styles)
{
var self = this;
function addStyle(paramStyle)
{
var css = doc.createElement("style");
css.setAttribute("id","styleNSDocxExport");
css.setAttribute("type","text/css");
if(css.styleSheet)
{
css.styleSheet.cssText = styles;
}
else
{
css.appendChild(doc.createTextNode(styles));
}
doc.getElementsByTagName("head")[0].appendChild(css);
};
function loopElements()
{
if(self.__setting.htmlSetting.loopNodesCallback)
{
var callback = self.__setting.htmlSetting.loopNodesCallback;
var arrElement = doc.querySelectorAll("body *");
var length = arrElement.length;
for(var count = 0;count < length;count++)
{
callback(arrElement[count]);
}
}
};
var parser = new DOMParser();
var doc = parser.parseFromString(html, "text/html");
loopElements();
if(styles)
{
addStyle(styles);
}
var content = doc.getElementsByTagName("html")[0].outerHTML;
content = content.replace(/\=/g, '=3D');
var strImages = (arrImages && arrImages.length) ? arrImages.join("") : "";
content += this.__exportUtil.newLine + this.__exportUtil.newLine + this.__exportUtil.getNonNullString(strImages);
return content;
};
NSDocxExport.prototype.__convertHtmlToMht = function(html)
{
var mimeTypeToAdd = 'MIME-Version: 1.0\nContent-Type: multipart/related;\n type="text/html";\n boundary="----=mhtDocumentPart"\nX-MimeOLE: Produced By Microsoft MimeOLE V6.1.7601.17609\n\nThis is a multi-part message in MIME format.\n\n------=mhtDocumentPart\nContent-Type: text/html;\n charset="utf-8"\nContent-Transfer-Encoding: quoted-printable\nContent-Location: file://\\\\fake\\document.html\n\n';
var endHtml = this.__exportUtil.newLine + this.__exportUtil.newLine + "------=mhtDocumentPart--" + this.__exportUtil.newLine;
return mimeTypeToAdd + html + endHtml;
};
/* end of html related functions */
var BaseElement = function()
{
};
BaseElement.prototype.init = function(docxRef)
{
this.util = new NSUtil();
this.__docxRef = docxRef;
this.__exportUtil = new ExportUtil(this.util);
this.__children = [];
};
BaseElement.prototype.getChildrenForXml = function()
{
var arrChildren = [];
var item = null;
var xml = null;
var length = this.__children.length;
for(var count = 0;count < length;count++)
{
item = this.__children[count];
if(item)
{
if(this.util.isString(item))
{
arrChildren.push(item);
}
else
{
xml = item.toXml.call(item);
if(xml)
{
arrChildren.push(xml);
}
}
}
}
return arrChildren;
};
BaseElement.prototype.toXml = function(xmlTag,attributes)
{
var arrChildren = this.getChildrenForXml();
var item = {name: xmlTag};
if(arrChildren && arrChildren.length)
{
item.chi