-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
190 lines (148 loc) · 5.43 KB
/
Copy pathindex.js
File metadata and controls
190 lines (148 loc) · 5.43 KB
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
/*
* @Author: Bruno Machado
* @Date: 2018-05-07
*/
var FileInputStream = Java.type('java.io.FileInputStream');
var FileOutputStream = Java.type('java.io.FileOutputStream');
var ByteArrayInputStream = Java.type('java.io.ByteArrayInputStream');
var ByteArrayOutputStream = Java.type('java.io.ByteArrayOutputStream');
var XWPFDocument = Java.type('org.apache.poi.xwpf.usermodel.XWPFDocument');
var ConverterRegistry = Java.type('fr.opensagres.xdocreport.converter.ConverterRegistry');
var ConverterTypeTo = Java.type('fr.opensagres.xdocreport.converter.ConverterTypeTo');
var Options = Java.type('fr.opensagres.xdocreport.converter.Options');
var DocumentKind = Java.type('fr.opensagres.xdocreport.core.document.DocumentKind');
var SIMPLE_PLACEHOLDER_PATTERN = /\{\{(\w+|\.)\}\}/g;
var BEGIN_PLACEHOLDER_PATTERN = /\{\{#(\w+)\}\}/;
var END_PLACEHOLDER_PATTERN = /\{\{\/(\w+)\}\}/;
/**
* Método utilizado para parsear um template docx, usando um objeto
* para preenchimento dos placeholders.
* @param byteArray Array de bytes do arquivo
* @param record Objeto que será usado como contexto para substituição dos placeholders
* @param options Objeto de opções para modificar o funcionamento do parser.
* parseToPdf <Boolean> Default: false
*/
function parseDocument(byteArray, record, opt) {
if (!byteArray) {
throw new Error('Os bytes do arquivo são obrigatórios.');
}
if (!record) {
throw new Error('Os JSON com os valores a serem renderizados é obrigatório.')
}
var options = Object.assign({
parseToPdf: false
}, opt);
var fis = new ByteArrayInputStream(byteArray);
var doc = new XWPFDocument(fis);
var blocks = [];
var currentBlock = null;
doc.getParagraphs().forEach(function (paragraph) {
var paragraphText = paragraph.getParagraphText();
if (currentBlock && END_PLACEHOLDER_PATTERN.exec(paragraphText)) {
currentBlock.endParagraph = paragraph;
currentBlock = null;
} else if (currentBlock != null) {
currentBlock.paragraphs.unshift(paragraph);
} else {
var m = BEGIN_PLACEHOLDER_PATTERN.exec(paragraphText);
if (m) {
currentBlock = {
startParagraph: paragraph,
name: m[1],
context: record[m[1]],
paragraphs: []
};
blocks.unshift(currentBlock);
} else {
replaceIfItExists(paragraph, record, null);
}
}
});
blocks.forEach(function (block) {
if (!block.endParagraph) {
throw new Error("Bloco " + block.name + " foi iniciado porém não foi finalizado.");
}
doc.removeBodyElement(doc.getPosOfParagraph(block.startParagraph));
doc.removeBodyElement(doc.getPosOfParagraph(block.endParagraph));
if (block.context) {
if (block.context.constructor.name != 'Array') {
block.context = [block.context];
}
var listCtx = block.context.slice(0).reverse();
var cursor;
var lastParagraph = null;
listCtx.forEach(function (ctx) {
block.paragraphs.forEach(function (paragraph) {
if (lastParagraph == null) {
cursor = paragraph.getCTP().newCursor();
} else {
cursor = lastParagraph.getCTP().newCursor();
}
var newParagraph = cloneParagraph(doc, paragraph, cursor);
replaceIfItExists(newParagraph, ctx, block.name);
lastParagraph = newParagraph;
});
});
}
block.paragraphs.forEach(function (paragraph) {
doc.removeBodyElement(doc.getPosOfParagraph(paragraph));
});
});
var outputStream = new ByteArrayOutputStream();
doc.write(outputStream);
if (options.parseToPdf) {
var inputStream = new ByteArrayInputStream(outputStream.toByteArray());
outputStream.reset();
var converterOptions = Options.getFrom(DocumentKind.DOCX).to(ConverterTypeTo.PDF);
var converter = ConverterRegistry.getRegistry().getConverter(converterOptions);
converter.convert(inputStream, outputStream, converterOptions);
}
return outputStream.toByteArray();
}
function replaceIfItExists(paragraph, context, ctxName) {
var runs = paragraph.getRuns();
if (runs) {
runs.forEach(function (r) {
var text = r.getText(0);
if (text && !text.isEmpty()) {
replaceTextIfItExists(r, text, context, ctxName);
}
});
}
}
function replaceTextIfItExists(run, text, context, ctxName) {
SIMPLE_PLACEHOLDER_PATTERN.lastIndex = 0;
var replacedText = text.replace(SIMPLE_PLACEHOLDER_PATTERN, function(group, key) {
var newValue = group;
if ('.'.equals(key) || (ctxName != null && ctxName.equals(key))) {
newValue = context.toString();
} else {
if (context.constructor.name == 'Object') {
if (context[key]) {
newValue = context[key].toString();
}
}
}
return newValue;
});
run.setText(replacedText, 0);
}
function cloneParagraph(doc, paragraph, cursor) {
var newParagraph = doc.insertNewParagraph(cursor);
var pPr = newParagraph.getCTP().isSetPPr() ? newParagraph.getCTP().getPPr()
: newParagraph.getCTP().addNewPPr();
pPr.set(paragraph.getCTP().getPPr());
paragraph.getRuns().forEach(function (r) {
var nr = newParagraph.createRun();
cloneRun(nr, r);
});
return newParagraph;
}
function cloneRun(clone, source) {
var rPr = clone.getCTR().isSetRPr() ? clone.getCTR().getRPr() : clone.getCTR().addNewRPr();
rPr.set(source.getCTR().getRPr());
clone.setText(source.getText(0));
}
exports = {
parseDocument: parseDocument
}