-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
603 lines (538 loc) · 29.7 KB
/
Program.cs
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
// ------------------------------------------------------------------------
// Copyright 2022 Thomas Gossler
// Licensed under the AGPL license, Version 3 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/#AGPL
// ------------------------------------------------------------------------
using System.CommandLine;
using System.Text.Json;
using AddPdfEnvelope;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Utils;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using Microsoft.Extensions.Configuration;
#region Workaround for commandLineArgs in WSL launch profile
// Workaround for not supported commandLineArgs in WSL launch profile with Visual Studio remote debugging
#if DEBUG
if (OperatingSystem.IsOSPlatform("Linux") && args.Length == 0 && Environment.CommandLine.Contains(".dll")) {
var launchSettingsFile = Environment.CurrentDirectory.Split("/bin")[0] + "/Properties/launchSettings.json";
var launchSettingsString = File.ReadAllText(launchSettingsFile);
var launchSettings = JsonDocument.Parse(launchSettingsString);
var commandLine = launchSettings.RootElement.GetProperty("profiles").GetProperty("ReplacePdfHyperlinks").GetProperty("commandLineArgs").ToString();
args = CommandLine.Parse(commandLine);
}
#endif
#endregion
#region Read application settings
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var settings = new PdfEnvelopeSettings(); // to prevent trimming of types
settings = config.GetRequiredSection("PdfEnvelope").Get<PdfEnvelopeSettings>();
#endregion
#region Configure command line options
// Configure command line options
var command = new RootCommand("CLI tool to add a cover page, header and footer to a PDF file.");
Option<FileInfo?> inputFileOption = DefineInputFileOption();
command.AddOption(inputFileOption);
Option<FileInfo?> outputFileOption = DefineOutputFileOption();
command.AddOption(outputFileOption);
Option<bool?> overwriteOption = DefineOverwriteOption();
command.AddOption(overwriteOption);
#endregion
#region Command handling
// Command handler
command.SetHandler((inputFile, outputFile, overwrite) => {
int exitCode = 0;
var useInputFileAsOutputFile = false;
if (outputFile == null) {
// No output file specified but replace regex specified means input file shall be modified in-place
if (overwrite.HasValue && overwrite.Value) {
var tempOutputFilename = GetTempOutputFilename(inputFile);
outputFile = new FileInfo(tempOutputFilename);
useInputFileAsOutputFile = true;
}
else {
Console.WriteLine($"In order to modify the input file in-place use option {overwriteOption.Name}.");
exitCode = 1;
return Task.FromResult(exitCode);
}
}
else {
// Avoid overwriting an existing output file without declared intent
if (File.Exists(outputFile.FullName)) {
if (!overwrite.HasValue || !overwrite.Value) {
LogError($"Output file exists. Use option {overwriteOption.Name}.");
exitCode = 1;
return Task.FromResult(exitCode);
}
try {
File.Delete(outputFile.FullName);
}
catch (Exception) {
LogError($"Output file exists and cannot be overwritten. Ensure it is not opened in another application.");
exitCode = 1;
return Task.FromResult(exitCode);
}
}
}
Console.WriteLine($"Processing file: {inputFile.FullName}...");
const float pageSideMargin = 50;
const float pageTopMargin = 35;
const float pageBottomMargin = 25;
try {
// Add a cover page to the document
var coverTempFilename = $"{outputFile.Directory.FullName}{System.IO.Path.DirectorySeparatorChar}{outputFile.Name}-cover.pdf";
using (var reader = new PdfReader(inputFile)) {
using var writer = GetPdfWriter(outputFile);
if (writer == null) {
exitCode = 1;
return Task.FromResult(exitCode);
}
using var inputPdf = new PdfDocument(reader);
using var outputPdf = new PdfDocument(writer);
// Create temporary cover page document
using (var coverWriter = GetPdfWriter(new FileInfo(coverTempFilename))) {
if (coverWriter == null) {
exitCode = 1;
return Task.FromResult(exitCode);
}
using var coverPdf = new PdfDocument(coverWriter);
coverPdf.AddNewPage(new PageSize(inputPdf.GetFirstPage().GetPageSize()));
using var coverDocument = new Document(coverPdf);
PdfPage pdfPage = coverPdf.GetPage(1);
var pageSize = pdfPage.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(pdfPage.NewContentStreamBefore(), pdfPage.GetResources(), coverPdf);
using (Canvas canvas = new Canvas(pdfCanvas, pdfPage.GetCropBox())) {
const float textSideMargin = 20;
var font = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
canvas.SetFont(font);
// Topic
canvas.Add(new Paragraph(ResolvePlaceholders(settings.CoverPage.Topic, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.LEFT)
.SetFontSize(22)
.SetBold()
.SetFixedPosition(1, pageSideMargin + textSideMargin, pageSize.GetHeight() - pageTopMargin - 120, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin));
// Subtopic
canvas.Add(new Paragraph(ResolvePlaceholders(settings.CoverPage.Subtopic, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.LEFT)
.SetFontSize(22)
.SetBold()
.SetFixedPosition(1, pageSideMargin + textSideMargin, pageSize.GetHeight() - pageTopMargin - 150, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin));
// Disclaimer
if (!string.IsNullOrWhiteSpace(settings.CoverPage.Disclaimer)) {
var disclaimerWidth = 180;
var disclaimerHeight = 40;
var disclaimerX = pageSize.GetWidth() - pageSideMargin - disclaimerWidth;
var disclaimerY = pageSize.GetHeight() - pageTopMargin - 50;
var disclaimerMargin = 5;
canvas.GetPdfCanvas().SetStrokeColor(ColorConstants.BLACK)
.SetLineWidth(1.0f)
.Rectangle(disclaimerX, disclaimerY, disclaimerWidth, -disclaimerHeight)
.Stroke();
canvas.Add(new Paragraph(settings.CoverPage.Disclaimer)
.SetTextAlignment(TextAlignment.LEFT)
.SetVerticalAlignment(VerticalAlignment.BOTTOM)
.SetFontSize(10)
.SetFixedPosition(1, disclaimerX + disclaimerMargin, disclaimerY - disclaimerHeight + disclaimerMargin, disclaimerWidth - 2 * disclaimerMargin));
}
// Title
canvas.Add(new Paragraph(ResolvePlaceholders(settings.CoverPage.Title, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(24)
.SetBold()
.SetFixedPosition(1, pageSideMargin + textSideMargin, pageSize.GetHeight() - pageTopMargin - 250, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin));
// Subtitle
canvas.Add(new Paragraph(ResolvePlaceholders(settings.CoverPage.Subtitle, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(18)
.SetBold()
.SetFixedPosition(1, pageSideMargin + textSideMargin, pageSize.GetHeight() - pageTopMargin - 280, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin));
// Version
canvas.Add(new Paragraph(ResolvePlaceholders(settings.CoverPage.Version, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(16)
.SetFixedPosition(1, pageSideMargin + textSideMargin, pageSize.GetHeight() - pageTopMargin - 370, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin));
// Author
canvas.Add(new Paragraph(ResolvePlaceholders(settings.CoverPage.Author, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(16)
.SetFixedPosition(1, pageSideMargin + textSideMargin, pageSize.GetHeight() - pageTopMargin - 400, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin));
// Date
canvas.Add(new Paragraph(ResolvePlaceholders(settings.CoverPage.Date, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(16)
.SetFixedPosition(1, pageSideMargin + textSideMargin, pageSize.GetHeight() - pageTopMargin - 430, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin));
// Frames
float orgTextSize = 14;
var orgTextWidth = !string.IsNullOrEmpty(settings.CoverPage.Organization) ? font.GetWidth(settings.CoverPage.Organization, orgTextSize) + 8 : 0;
var framesTopY = pageSize.GetHeight() - pageTopMargin - 170;
var mainBoxHeight = framesTopY - 20 - pageBottomMargin - 100;
canvas.GetPdfCanvas().SetStrokeColor(ColorConstants.BLACK)
.SetLineWidth(1.0f)
.SetFillColor(ColorConstants.BLACK)
.Rectangle(pageSideMargin + textSideMargin, framesTopY, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin - orgTextWidth, -15)
.FillStroke()
.Stroke();
canvas.GetPdfCanvas().SetStrokeColor(ColorConstants.BLACK)
.SetLineWidth(1.0f)
.Rectangle(pageSideMargin + textSideMargin, framesTopY - 20, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin, -mainBoxHeight)
.Stroke();
// Organization
if (!string.IsNullOrEmpty(settings.CoverPage.Organization)) {
canvas.Add(new Paragraph(ResolvePlaceholders(settings.CoverPage.Organization, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.RIGHT)
.SetFontSize(orgTextSize)
.SetBold()
.SetFixedPosition(1, pageSize.GetWidth() - pageSideMargin - textSideMargin - orgTextWidth, framesTopY - 18, orgTextWidth));
}
// Signature Area
if (settings.CoverPage.ShowSignatureArea) {
var sigAreaHeight = 80;
var sigAreaTop = framesTopY - 20 - mainBoxHeight + 2*sigAreaHeight;
canvas.GetPdfCanvas().SetStrokeColor(ColorConstants.BLACK)
.SetLineWidth(1.0f)
.Rectangle(pageSideMargin + textSideMargin, sigAreaTop, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin, -sigAreaHeight)
.Stroke();
var authorText = "Author";
if (!string.IsNullOrWhiteSpace(settings.CoverPage.RoleAuthor)) {
authorText += $" ({settings.CoverPage.RoleAuthor})";
}
canvas.Add(new Paragraph(ResolvePlaceholders(authorText, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.LEFT)
.SetFontSize(12)
.SetFixedPosition(1, pageSideMargin + textSideMargin + 10, sigAreaTop - 20, pageSize.GetWidth() / 3));
canvas.GetPdfCanvas().SetStrokeColor(ColorConstants.BLACK)
.SetLineWidth(1.0f)
.Rectangle(pageSideMargin + textSideMargin, sigAreaTop - sigAreaHeight, pageSize.GetWidth() - 2 * pageSideMargin - 2 * textSideMargin, -sigAreaHeight)
.Stroke();
var approverText = "Approver";
if (!string.IsNullOrWhiteSpace(settings.CoverPage.RoleApprover)) {
approverText += $" ({settings.CoverPage.RoleApprover})";
}
canvas.Add(new Paragraph(ResolvePlaceholders(approverText, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.LEFT)
.SetFontSize(12)
.SetFixedPosition(1, pageSideMargin + textSideMargin + 10, sigAreaTop - sigAreaHeight - 20, pageSize.GetWidth() / 3));
// Adobe Sign Tags
var signaturePlaceholder = settings.CoverPage.AdobeSignTagPattern ?? "";
if (settings.CoverPage.AddAdobeSignTags) {
if (String.IsNullOrWhiteSpace(signaturePlaceholder)) {
signaturePlaceholder = "{{SigB_es_:signer{sigNum}:signatureblock}}";
}
canvas.Add(new Paragraph(ResolvePlaceholders(signaturePlaceholder, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.LEFT)
.SetFontSize(12)
.SetFixedPosition(1, pageSideMargin + textSideMargin + 10, sigAreaTop - 40, pageSize.GetWidth() / 3));
canvas.Add(new Paragraph(ResolvePlaceholders(signaturePlaceholder, coverPdf, 1, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.LEFT)
.SetFontSize(12)
.SetFixedPosition(1, pageSideMargin + textSideMargin + 10, sigAreaTop - sigAreaHeight - 40, pageSize.GetWidth() / 3));
}
}
}
coverPdf.SetFlushUnusedObjects(true);
coverWriter.SetCompressionLevel(9);
}
// Add the cover page to document
using (var coverPdf = new PdfDocument(new PdfReader(coverTempFilename))) {
var merger = new PdfMerger(outputPdf);
merger.Merge(coverPdf, 1, 1);
merger.Merge(inputPdf, 1, inputPdf.GetNumberOfPages());
merger.Close();
}
}
try {
// Delete temporary files
if (File.Exists(coverTempFilename)) {
File.Delete(coverTempFilename);
}
}
catch (Exception) {
LogError("Error: Temporary cover page file could not be deleted");
Console.WriteLine("Continuing...");
}
}
catch (Exception ex) {
LogError($"Error: {ex.Message}");
LogError($"Error: Cover page could not be generated");
Console.WriteLine("Exiting...");
exitCode = 1;
return Task.FromResult(exitCode);
}
try {
// Add header and footer to all pages except the cover page
var tempOutput2Filename = GetTempOutputFilename(outputFile);
var output2File = new FileInfo(tempOutput2Filename);
using (var reader = new PdfReader(outputFile)) {
using var writer = GetPdfWriter(output2File);
if (writer == null) {
exitCode = 1;
return Task.FromResult(exitCode);
}
using var pdf = new PdfDocument(reader, writer);
var numOfPages = pdf.GetNumberOfPages();
using var document = new Document(pdf, pdf.GetDefaultPageSize(), false);
const float textLineHeight = 15;
const float fontSize = 9;
var StyledParagraph = (string text) => {
return new Paragraph(text)
.SetMargin(0)
.SetFont(PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN))
.SetFontSize(fontSize)
.SetFontColor(ColorConstants.BLACK);
};
for (int i = 1; i <= numOfPages; i++) {
Console.Write($"Processing page {i}...\r");
PdfPage pdfPage = pdf.GetPage(i);
var pageSize = pdfPage.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(pdfPage.NewContentStreamBefore(), pdfPage.GetResources(), pdf);
using (Canvas canvas = new Canvas(pdfCanvas, pdfPage.GetCropBox())) {
if (i > 1 || !settings.PageHeader.ExcludeCoverPage) {
// Add page header - Left
Paragraph p = StyledParagraph(ResolvePlaceholders(settings.PageHeader.TextLeft1, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.LEFT)
.SetFixedPosition(i, pageSideMargin, pageSize.GetHeight() - pageTopMargin, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
p = StyledParagraph(ResolvePlaceholders(settings.PageHeader.TextLeft2, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.LEFT)
.SetFixedPosition(i, pageSideMargin, pageSize.GetHeight() - pageTopMargin - textLineHeight, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
// Add page header - Center
p = StyledParagraph(ResolvePlaceholders(settings.PageHeader.TextCenter1, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.CENTER)
.SetFixedPosition(i, pageSideMargin, pageSize.GetHeight() - pageTopMargin, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
p = StyledParagraph(ResolvePlaceholders(settings.PageHeader.TextCenter2, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.CENTER)
.SetFixedPosition(i, pageSideMargin, pageSize.GetHeight() - pageTopMargin - textLineHeight, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
// Add page header - Right
p = StyledParagraph(ResolvePlaceholders(settings.PageHeader.TextRight1, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.RIGHT)
.SetFixedPosition(i, pageSideMargin, pageSize.GetHeight() - pageTopMargin, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
p = StyledParagraph(ResolvePlaceholders(settings.PageHeader.TextRight2, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.RIGHT)
.SetFixedPosition(i, pageSideMargin, pageSize.GetHeight() - pageTopMargin - textLineHeight, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
// Draw header line
if (settings.PageHeader.DrawLine) {
canvas.GetPdfCanvas().SetStrokeColor(ColorConstants.BLACK)
.SetLineWidth(0.5f)
.MoveTo(pageSideMargin, pageSize.GetHeight() - pageTopMargin - textLineHeight - 3).LineTo(pageSize.GetWidth() - pageSideMargin, pageSize.GetHeight() - pageTopMargin - textLineHeight - 3)
.Stroke();
}
}
if (i > 1 || !settings.PageFooter.ExcludeCoverPage) {
// Add page number to the footer - Left
var p = StyledParagraph(ResolvePlaceholders(settings.PageFooter.TextLeft1, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.LEFT)
.SetFixedPosition(i, pageSideMargin, pageBottomMargin + textLineHeight, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
p = StyledParagraph(ResolvePlaceholders(settings.PageFooter.TextLeft2, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.LEFT)
.SetFixedPosition(i, pageSideMargin, pageBottomMargin, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
// Add page number to the footer - Center
p = StyledParagraph(ResolvePlaceholders(settings.PageFooter.TextCenter1, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.CENTER)
.SetFixedPosition(i, pageSideMargin, pageBottomMargin + textLineHeight, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
p = StyledParagraph(ResolvePlaceholders(settings.PageFooter.TextCenter2, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.CENTER)
.SetFixedPosition(i, pageSideMargin, pageBottomMargin, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
// Add page number to the footer - Right
p = StyledParagraph(ResolvePlaceholders(settings.PageFooter.TextRight1, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.RIGHT)
.SetFixedPosition(i, pageSideMargin, pageBottomMargin + textLineHeight, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
p = StyledParagraph(ResolvePlaceholders(settings.PageFooter.TextRight2, pdf, i, settings.PageNumberOffset))
.SetTextAlignment(TextAlignment.RIGHT)
.SetFixedPosition(i, pageSideMargin, pageBottomMargin, pageSize.GetWidth() - 2 * pageSideMargin);
canvas.Add(p);
// Draw footer line
if (settings.PageFooter.DrawLine) {
canvas.GetPdfCanvas().SetStrokeColor(ColorConstants.BLACK)
.SetLineWidth(0.5f)
.MoveTo(pageSideMargin, pageBottomMargin + textLineHeight + fontSize + 5).LineTo(pageSize.GetWidth() - pageSideMargin, pageBottomMargin + textLineHeight + fontSize + 5)
.Stroke();
}
}
canvas.Flush();
}
pdfCanvas.Release();
if (settings.RemoveAnnotationsOtherThanLinks) {
// Clear existing annotations/comments
var annotations = pdfPage.GetAnnotations();
foreach (var annotation in annotations) {
if (!annotation.GetSubtype().Equals(PdfName.Link)) {
pdfPage.RemoveAnnotation(annotation);
}
}
}
}
Console.Write($" \r");
pdf.SetFlushUnusedObjects(true);
writer.SetCompressionLevel(9);
}
File.Delete(outputFile.FullName);
File.Move(output2File.FullName, outputFile.FullName);
}
catch (Exception ex) {
LogError($"Error: {ex.Message}");
LogError($"Error: Header and footer could not be added");
Console.WriteLine("Exiting...");
exitCode = 1;
return Task.FromResult(exitCode);
}
#region Replace input file (if requested)
if (useInputFileAsOutputFile) {
// Apply the changes to the input file
try {
// Replace input file with temporary output file
if (File.Exists(outputFile.FullName)) {
File.Delete(inputFile.FullName);
File.Move(outputFile.FullName, inputFile.FullName);
outputFile = inputFile;
}
}
catch (Exception ex) {
LogError($"Error: {ex.Message}");
LogError("The changes could not be applied to the input file (keeping temporary file)");
exitCode = 1;
}
}
#endregion
#region Show some statistics
Console.WriteLine($"Output file: {outputFile.FullName}");
#endregion
return Task.FromResult(exitCode);
},
inputFileOption, outputFileOption, overwriteOption);
return await command.InvokeAsync(args);
#endregion
#region Define command line options
// Define command line options
Option<FileInfo?> DefineInputFileOption()
{
var inputFileOption = new Option<FileInfo?>(
name: "--inputFile",
description: "The PDF file to process.",
parseArgument: result => {
if (result.Tokens.Count == 0) {
result.ErrorMessage = "Option '--inputFile' is required.";
return null;
}
string? filePath = result.Tokens.Single().Value;
if (!File.Exists(filePath)) {
result.ErrorMessage = "Input file does not exist";
return null;
}
else {
return new FileInfo(filePath);
}
}) { IsRequired = true };
inputFileOption.AddAlias("-f");
return inputFileOption;
}
Option<FileInfo?> DefineOutputFileOption()
{
var outputFileOption = new Option<FileInfo?>(
name: "--outputFile",
description: "The output PDF file path.");
outputFileOption.AddAlias("-o");
return outputFileOption;
}
Option<bool?> DefineOverwriteOption()
{
var overwriteOption = new Option<bool?>(
name: "--overwrite-yes",
description: "Overwrite the existing output file without confirmation.",
getDefaultValue: () => false);
overwriteOption.AddAlias("-y");
return overwriteOption;
}
#endregion
#region Helper functions
static void LogError(string message)
{
var fgcolor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ForegroundColor = fgcolor;
}
static PdfWriter? GetPdfWriter(FileInfo outputFile)
{
PdfWriter? writer = null;
FileStream? os = null;
int retryCount = 3;
int retryDelaySeconds = 5;
do {
try {
os = new FileStream(outputFile.FullName, FileMode.OpenOrCreate, FileAccess.Write);
}
catch (Exception) {
LogError($"Output file could not be opened for writing. Retrying {retryCount} times after {retryDelaySeconds} seconds...");
Thread.Sleep(retryDelaySeconds * 1000);
}
retryCount--;
} while (os == null && retryCount > 0);
if (os != null) {
writer = new PdfWriter(os);
}
return writer;
}
static string GetTempOutputFilename(FileInfo? baseFileInfo)
{
if (baseFileInfo == null) {
baseFileInfo = new FileInfo("TempOutput");
}
return baseFileInfo.Directory.FullName + System.IO.Path.DirectorySeparatorChar + baseFileInfo.Name + "-" +
HashCode.Combine(baseFileInfo.FullName, DateTime.Now.Ticks.ToString()) + baseFileInfo.Extension;
}
static string? ResolvePlaceholders(string text, PdfDocument pdfDocument, int currentPageNumber, int pageNumberOffset = 0)
{
if (string.IsNullOrWhiteSpace(text)) return string.Empty;
string result = text;
var placeholders = RegExs.PlaceholderRegEx.Matches(text);
for (int i = 0; i < placeholders.Count; i++) {
var placeholder = placeholders[i];
var index = i.ToString();
if (placeholder.Groups[0].Value.Contains("date")) {
// {date[:<format>]}, see also: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
result = result.Replace("date", index);
try {
result = String.Format(result, DateTime.Now);
}
catch (Exception) {
LogError($"Invalid date format specified: {text}");
Console.WriteLine($"Using default: dd.MM.yyyy");
return String.Format("{" + index + ":dd.MM.yyyy}", DateTime.Now);
}
}
else if (placeholder.Groups[0].Value.Contains("sigNum")) {
// {sigNum}
result = result.Replace("{sigNum}", (Globals.CurrentSigNum++).ToString());
}
else if (placeholder.Groups[0].Value.Contains("pageNum")) {
// {pageNum}
result = (currentPageNumber == 1) ? "{numOfPages} pages" : result.Replace("{pageNum}", (currentPageNumber + pageNumberOffset).ToString());
}
else if (placeholder.Groups[0].Value.Contains("numOfPages")) {
// {numOfPages}
result = result.Replace("{numOfPages}", (pdfDocument.GetNumberOfPages() + pageNumberOffset).ToString());
}
}
return result;
}
#endregion