-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocxreplacerapp.pas
356 lines (302 loc) · 8.93 KB
/
docxreplacerapp.pas
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
unit docxreplacerapp;
{$mode delphi}
interface
uses
Classes, SysUtils, CustApp, Zipper, XMLRead, DOM, fpjson, FileUtil, LazFileUtils,
XMLWrite, rcmdline, jsonparser;
type
{ TDocxReplacerApp }
TDocxReplacerApp = class(TCustomApplication)
private
FCommandLineReader: TCommandLineReader;
FInputFilePath: string;
FPlaceholdersPath: string;
FOutputPath: string;
FXMLDocument: TXMLDocument;
function GetParamFile(AParam: String): String;
function GetInputFilePath: string;
function GetOutputPath: string;
function GetInternalDocXmlPath: string;
function GetPlaceholdersPath: string;
function GetTempPath: string;
procedure UncompressDocx;
procedure IteratePlaceholders;
procedure IterateXMLDocument(APlaceholder, AReplacement: string);
procedure ReplacePlaceholder(Node: TDOMNode;
APlaceholder, AReplacement: string);
procedure SaveDocx;
procedure CleanTemp;
procedure DeclareParams;
function ParseParams: boolean;
procedure WriteHelp;
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
property InputFilePath: string read GetInputFilePath;
property PlaceholdersPath: string read GetPlaceholdersPath;
property TempPath: string read GetTempPath;
property OutputPath: string read GetOutputPath;
property InternalDocXmlPath: string read GetInternalDocXmlPath;
end;
const
PARAM_INPUT_DOC = 'inputDoc';
PARAM_OUTPUT_DOC = 'outputDoc';
PARAM_TOKENS_JSON = 'placeholdersJson';
implementation
{ TDocxReplacerApp }
procedure TDocxReplacerApp.UncompressDocx;
var
UnZip: TUnZipper;
begin
UnZip := TUnZipper.Create;
try
UnZip.FileName := InputFilePath;
UnZip.OutputPath := TempPath;
UnZip.Examine;
UnZip.UnZipAllFiles;
finally
UnZip.Free;
end;
end;
function TDocxReplacerApp.GetInputFilePath: string;
begin
Result := CleanAndExpandFilename(FInputFilePath);
end;
function TDocxReplacerApp.GetParamFile(AParam: String): String;
var
flagError: Boolean;
begin
Result := FCommandLineReader.readString(AParam);
flagError := (not FCommandLineReader.existsProperty(AParam))
or (Result = '');
if flagError then
WriteLn('Error: Parameter ' + AParam + ' is mandatory!' + LineEnding)
else
if not(FileExists(CleanAndExpandFilename(Result))) then
begin
Result := '';
WriteLn('Error: Filename ' + AParam + ' is not found!' + LineEnding);
end;
end;
function TDocxReplacerApp.GetOutputPath: string;
begin
Result := ExpandFileName(FOutputPath);
end;
function TDocxReplacerApp.GetInternalDocXmlPath: string;
begin
if (LowerCase(ExtractFileExt(FInputFilePath)) = '.docx') then
Result := ConcatPaths([Location, 'temp', 'word', 'document.xml'])
else
Result := ConcatPaths([Location, 'temp', 'content.xml']);
end;
function TDocxReplacerApp.GetPlaceholdersPath: string;
begin
Result := CleanAndExpandFilename(FPlaceholdersPath);
end;
function TDocxReplacerApp.GetTempPath: string;
begin
Result := ExpandFileName('temp');
ForceDirectories(Result);
end;
procedure TDocxReplacerApp.IteratePlaceholders;
var
Placeholder, Replacement: string;
i: integer;
json: TJSONData;
jsonArray: TJSONArray;
jsonFile: TFileStream;
begin
// Load the JSON file containing the placeholder data
jsonFile := TFileStream.Create(PlaceholdersPath, fmOpenRead);
json := GetJSON(jsonFile);
try
// Get the number of placeholders in the JSON file
jsonArray := json.FindPath('placeholder') as TJSONArray;
// Iterate through all the placeholders in the JSON file
for i := 0 to jsonArray.Count - 1 do
begin
// Get the placeholder and replacement text from the JSON file
Placeholder := jsonArray.Items[i].FindPath('name').AsString;
Replacement := jsonArray.Items[i].FindPath('value').AsString;
// Replace all occurrences of the placeholder with the replacement text
IterateXMLDocument(Placeholder, Replacement);
end;
finally
json.Free;
jsonFile.Free;
end;
end;
procedure TDocxReplacerApp.IterateXMLDocument(APlaceholder, AReplacement: string);
var
iNode: TDOMNode;
procedure ProcessNode(Node: TDOMNode);
var
cNode: TDOMNode;
begin
if Node = nil then Exit; // Stops if reached a leaf
ReplacePlaceholder(Node, APlaceholder, AReplacement);
// Goes to the child node
cNode := Node.FirstChild;
// Processes all child nodes
while cNode <> nil do
begin
ProcessNode(cNode);
cNode := cNode.NextSibling;
end;
end;
begin
Assert(Assigned(Self.FXMLDocument));
// Iterate through all the nodes in the XML document
iNode := Self.FXMLDocument.DocumentElement.FirstChild;
while iNode <> nil do
begin
ProcessNode(iNode); // Recursive
iNode := iNode.NextSibling;
end;
end;
procedure TDocxReplacerApp.ReplacePlaceholder(Node: TDOMNode;
APlaceholder, AReplacement: string);
begin
// Check if the node is a text node
if Node.NodeType = TEXT_NODE then
begin
// Replace the placeholder text with the replacement text
if Pos(APlaceholder, Node.TextContent) > 0 then
Node.TextContent := StringReplace(Node.TextContent, APlaceholder,
AReplacement, [rfReplaceAll]);
end;
end;
procedure TDocxReplacerApp.SaveDocx;
var
AZipper: TZipper;
szPathEntry: string;
i: integer;
ZEntries: TZipFileEntries;
TheFileList: TStringList;
RelativeDirectory: string;
begin
WriteXMLFile(FXMLDocument, InternalDocXmlPath);
AZipper := TZipper.Create;
try
try
AZipper.Filename := Self.OutputPath;
RelativeDirectory := TempPath;
AZipper.Clear;
ZEntries := TZipFileEntries.Create(TZipFileEntry);
// Verify valid directory
if DirPathExists(RelativeDirectory) then
begin
// Construct the path to the directory BELOW RelativeDirectory
szPathEntry := IncludeTrailingPathDelimiter(RelativeDirectory);
// Use the FileUtils.FindAllFiles function to get everything (files and folders) recursively
TheFileList := TStringList.Create;
try
FindAllFiles(TheFileList, RelativeDirectory);
for i := 0 to TheFileList.Count - 1 do
begin
// Make sure the RelativeDirectory files are not in the root of the ZipFile
ZEntries.AddFileEntry(TheFileList[i], CreateRelativePath(
TheFileList[i], szPathEntry));
end;
finally
TheFileList.Free;
end;
end;
if (ZEntries.Count > 0) then
AZipper.ZipFiles(ZEntries);
except
On E: EZipError do
E.CreateFmt('Zipfile could not be created%sReason: %s',
[LineEnding, E.Message])
end;
finally
FreeAndNil(ZEntries);
AZipper.Free;
end;
end;
procedure TDocxReplacerApp.CleanTemp;
begin
DeleteDirectory(Self.TempPath, True);
end;
procedure TDocxReplacerApp.DeclareParams;
begin
FCommandLineReader.declareFile(PARAM_INPUT_DOC, 'Filepath to input docx/odt');
FCommandLineReader.addAbbreviation('i');
FCommandLineReader.declareFile(PARAM_TOKENS_JSON, 'Filepath to placeholders json file');
FCommandLineReader.addAbbreviation('p');
FCommandLineReader.declareFile(PARAM_OUTPUT_DOC, 'Filepath to output docx/odt', 'newDocx.docx');
FCommandLineReader.addAbbreviation('o');
end;
function TDocxReplacerApp.ParseParams: boolean;
begin
Result := False;
try
try
FCommandLineReader.parse();
FInputFilePath := GetParamFile(PARAM_INPUT_DOC);
FPlaceholdersPath := GetParamFile(PARAM_TOKENS_JSON);
FOutputPath := FCommandLineReader.readString(PARAM_OUTPUT_DOC);
except
on E: Exception do
WriteLn(E.Message + LineEnding);
end;
finally
Result := (FInputFilePath <> '') and (FPlaceholdersPath <> '');
end;
end;
procedure TDocxReplacerApp.WriteHelp;
begin
WriteLn('The following command line options are valid: ' + LineEnding +
LineEnding + FCommandLineReader.availableOptions);
end;
procedure TDocxReplacerApp.DoRun;
var
FileDocPath: String;
begin
DeclareParams;
if not ParseParams then
begin
WriteHelp;
Terminate;
Exit;
end;
UncompressDocx;
try
//Read xml in FXMLDocument
FileDocPath := InternalDocXmlPath;
if (FileExists(FileDocPath)) then
begin
ReadXMLFile(FXMLDocument, InternalDocXmlPath);
//Iterate placeholders.json tokens to replace them in xml
IteratePlaceholders;
//Compress again in a docx file
SaveDocx;
CleanTemp;
end
else begin
WriteLn('Error: File document xml [' + InternalDocXmlPath + '] not found!');
Terminate;
Exit;
end;
finally
FXMLDocument.Free;
end;
// stop program loop
Terminate;
end;
constructor TDocxReplacerApp.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException := True;
FCommandLineReader := TCommandLineReader.Create;
//showErrorAutomatically = false because we won't halt when find wrong param
FCommandLineReader.showErrorAutomatically := False;
end;
destructor TDocxReplacerApp.Destroy;
begin
inherited Destroy;
FCommandLineReader.Free;
end;
end.