-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
679 lines (571 loc) · 20.3 KB
/
Copy pathProgram.cs
File metadata and controls
679 lines (571 loc) · 20.3 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
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
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using UglyToad.PdfPig;
using UglyToad.PdfPig.Content;
var result = AppOptionsParser.Parse(args);
if (!result.Success)
{
Console.Error.WriteLine(result.Error);
Console.WriteLine();
AppOptionsParser.PrintUsage();
return 1;
}
var options = result.Options!;
Directory.CreateDirectory(options.OutputPath);
var pdfFiles = PdfFileFinder.Find(options.InputPath, options.Recursive).ToArray();
if (pdfFiles.Length == 0)
{
Console.WriteLine("PDF files were not found.");
return 0;
}
var converter = new PdfFolderConverter(options);
var failed = 0;
foreach (var pdfFile in pdfFiles)
{
try
{
var output = converter.Convert(pdfFile);
Console.WriteLine($"OK: {pdfFile}");
Console.WriteLine($" Output: {output.OutputDirectory}");
Console.WriteLine($" Pages: {output.PageCount}, images: {output.ImageCount}");
}
catch (Exception ex)
{
failed++;
Console.Error.WriteLine($"ERROR: {pdfFile}");
Console.Error.WriteLine($" {ex.Message}");
}
}
Console.WriteLine();
Console.WriteLine($"Done. Processed: {pdfFiles.Length - failed}, failed: {failed}.");
return failed == 0 ? 0 : 2;
internal enum OutputFormat
{
Txt,
Docx,
Both
}
internal sealed record AppOptions(
string InputPath,
string OutputPath,
OutputFormat Format,
bool Recursive,
bool Overwrite);
internal sealed record ParseResult(bool Success, AppOptions? Options, string? Error)
{
public static ParseResult Ok(AppOptions options) => new(true, options, null);
public static ParseResult Fail(string error) => new(false, null, error);
}
internal static class AppOptionsParser
{
public static ParseResult Parse(string[] args)
{
if (args.Length == 0)
{
return ParseResult.Fail("No arguments specified.");
}
if (args.Any(IsHelp))
{
PrintUsage();
Environment.Exit(0);
}
string? input = null;
string? output = null;
var format = OutputFormat.Both;
var recursive = false;
var overwrite = true;
var positional = new List<string>();
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
switch (arg.ToLowerInvariant())
{
case "-i":
case "--input":
if (!TryReadValue(args, ref i, arg, out input, out var inputError))
{
return ParseResult.Fail(inputError);
}
break;
case "-o":
case "--output":
if (!TryReadValue(args, ref i, arg, out output, out var outputError))
{
return ParseResult.Fail(outputError);
}
break;
case "-f":
case "--format":
if (!TryReadValue(args, ref i, arg, out var formatValue, out var formatError))
{
return ParseResult.Fail(formatError);
}
if (!TryParseFormat(formatValue, out format))
{
return ParseResult.Fail("Format must be txt, docx, or both.");
}
break;
case "-r":
case "--recursive":
recursive = true;
break;
case "--no-overwrite":
overwrite = false;
break;
default:
if (arg.StartsWith('-'))
{
return ParseResult.Fail($"Unknown argument: {arg}");
}
positional.Add(arg);
break;
}
}
if (input is null && positional.Count > 0)
{
input = positional[0];
}
if (output is null && positional.Count > 1)
{
output = positional[1];
}
if (input is null)
{
return ParseResult.Fail("Input folder or PDF file is required.");
}
var inputPath = Path.GetFullPath(input);
if (!Directory.Exists(inputPath) && !File.Exists(inputPath))
{
return ParseResult.Fail($"Input path does not exist: {inputPath}");
}
if (File.Exists(inputPath) && !inputPath.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
{
return ParseResult.Fail("Input file must be a PDF.");
}
var defaultOutput = File.Exists(inputPath)
? Path.Combine(Path.GetDirectoryName(inputPath)!, "converted")
: Path.Combine(inputPath, "converted");
var outputPath = Path.GetFullPath(output ?? defaultOutput);
return ParseResult.Ok(new AppOptions(inputPath, outputPath, format, recursive, overwrite));
}
public static void PrintUsage()
{
Console.WriteLine("""
Usage:
PdfToTextDocx --input <folder-or-pdf> [--output <folder>] [--format txt|docx|both] [--recursive]
Examples:
PdfToTextDocx --input "C:\PDF" --output "C:\PDF\out" --format both
PdfToTextDocx -i "C:\PDF\file.pdf" -o "C:\PDF\out" -f docx
Notes:
- Each PDF gets its own output folder.
- Extracted images are saved in an images subfolder.
- TXT and DOCX files contain relative links to saved images.
""");
}
private static bool IsHelp(string value)
{
return value.Equals("-h", StringComparison.OrdinalIgnoreCase)
|| value.Equals("--help", StringComparison.OrdinalIgnoreCase)
|| value.Equals("/?", StringComparison.OrdinalIgnoreCase);
}
private static bool TryReadValue(string[] args, ref int index, string argumentName, out string value, out string error)
{
if (index + 1 >= args.Length)
{
value = string.Empty;
error = $"Argument {argumentName} requires a value.";
return false;
}
value = args[++index];
error = string.Empty;
return true;
}
private static bool TryParseFormat(string value, out OutputFormat format)
{
switch (value.ToLowerInvariant())
{
case "txt":
format = OutputFormat.Txt;
return true;
case "docx":
format = OutputFormat.Docx;
return true;
case "both":
format = OutputFormat.Both;
return true;
default:
format = OutputFormat.Both;
return false;
}
}
}
internal static class PdfFileFinder
{
public static IEnumerable<string> Find(string inputPath, bool recursive)
{
if (File.Exists(inputPath))
{
yield return inputPath;
yield break;
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
foreach (var file in Directory.EnumerateFiles(inputPath, "*.pdf", searchOption))
{
yield return file;
}
}
}
internal sealed record ConversionOutput(string OutputDirectory, int PageCount, int ImageCount);
internal sealed record DocumentContent(string SourceFileName, IReadOnlyList<PageContent> Pages)
{
public int ImageCount => Pages.Sum(page => page.Images.Count);
}
internal sealed record PageContent(int PageNumber, IReadOnlyList<string> Lines, IReadOnlyList<SavedImage> Images);
internal sealed record SavedImage(string RelativePath, string FullPath, int PageNumber, int ImageNumber, bool Converted);
internal sealed class PdfFolderConverter
{
private readonly AppOptions options;
public PdfFolderConverter(AppOptions options)
{
this.options = options;
}
public ConversionOutput Convert(string pdfPath)
{
var outputDirectory = GetOutputDirectory(pdfPath);
var imagesDirectory = Path.Combine(outputDirectory, "images");
Directory.CreateDirectory(outputDirectory);
Directory.CreateDirectory(imagesDirectory);
var content = ExtractContent(pdfPath, imagesDirectory, outputDirectory);
var baseName = FileNameTools.Sanitize(Path.GetFileNameWithoutExtension(pdfPath));
if (options.Format is OutputFormat.Txt or OutputFormat.Both)
{
var txtPath = Path.Combine(outputDirectory, $"{baseName}.txt");
WriteWithOverwritePolicy(txtPath, () => TxtWriter.Write(txtPath, content));
}
if (options.Format is OutputFormat.Docx or OutputFormat.Both)
{
var docxPath = Path.Combine(outputDirectory, $"{baseName}.docx");
WriteWithOverwritePolicy(docxPath, () => DocxWriter.Write(docxPath, content));
}
return new ConversionOutput(outputDirectory, content.Pages.Count, content.ImageCount);
}
private DocumentContent ExtractContent(string pdfPath, string imagesDirectory, string outputDirectory)
{
using var document = PdfDocument.Open(pdfPath);
var pages = new List<PageContent>();
var baseName = FileNameTools.Sanitize(Path.GetFileNameWithoutExtension(pdfPath));
foreach (var page in document.GetPages())
{
var lines = PageTextExtractor.ExtractLines(page).ToArray();
var images = ImageExtractor.SaveImages(page, imagesDirectory, outputDirectory, baseName).ToArray();
pages.Add(new PageContent(page.Number, lines, images));
}
return new DocumentContent(Path.GetFileName(pdfPath), pages);
}
private string GetOutputDirectory(string pdfPath)
{
var inputIsFile = File.Exists(options.InputPath);
var inputDirectory = inputIsFile ? Path.GetDirectoryName(options.InputPath)! : options.InputPath;
var relativeDirectory = Path.GetRelativePath(inputDirectory, Path.GetDirectoryName(pdfPath)!);
var baseName = FileNameTools.Sanitize(Path.GetFileNameWithoutExtension(pdfPath));
if (relativeDirectory == "." || relativeDirectory.StartsWith(".."))
{
return Path.Combine(options.OutputPath, baseName);
}
return Path.Combine(options.OutputPath, relativeDirectory, baseName);
}
private void WriteWithOverwritePolicy(string path, Action write)
{
if (!options.Overwrite && File.Exists(path))
{
throw new IOException($"Output file already exists: {path}");
}
write();
}
}
internal static class PageTextExtractor
{
public static IEnumerable<string> ExtractLines(Page page)
{
var words = page.GetWords()
.Where(word => !string.IsNullOrWhiteSpace(word.Text))
.Select(word => new WordBox(
word.Text,
word.BoundingBox.Left,
word.BoundingBox.Right,
word.BoundingBox.Bottom,
word.BoundingBox.Top,
word.BoundingBox.Height))
.OrderByDescending(word => word.CenterY)
.ThenBy(word => word.Left)
.ToList();
if (words.Count == 0)
{
if (!string.IsNullOrWhiteSpace(page.Text))
{
yield return NormalizeWhitespace(page.Text);
}
yield break;
}
var tolerance = Math.Max(2.0, words.Select(word => word.Height).DefaultIfEmpty(10).Average() * 0.45);
var lines = new List<LineBox>();
foreach (var word in words)
{
var line = lines.FirstOrDefault(item => Math.Abs(item.CenterY - word.CenterY) <= tolerance);
if (line is null)
{
lines.Add(new LineBox(word.CenterY, [word]));
}
else
{
line.Words.Add(word);
line.CenterY = line.Words.Average(item => item.CenterY);
}
}
foreach (var line in lines.OrderByDescending(line => line.CenterY))
{
var lineText = string.Join(" ", line.Words.OrderBy(word => word.Left).Select(word => word.Text));
if (!string.IsNullOrWhiteSpace(lineText))
{
yield return NormalizeWhitespace(lineText);
}
}
}
private static string NormalizeWhitespace(string text)
{
var builder = new StringBuilder(text.Length);
var previousWasWhitespace = false;
foreach (var ch in text)
{
if (char.IsWhiteSpace(ch))
{
if (!previousWasWhitespace)
{
builder.Append(' ');
previousWasWhitespace = true;
}
continue;
}
builder.Append(ch);
previousWasWhitespace = false;
}
return builder.ToString().Trim();
}
private sealed record WordBox(string Text, double Left, double Right, double Bottom, double Top, double Height)
{
public double CenterY => (Top + Bottom) / 2;
}
private sealed class LineBox
{
public LineBox(double centerY, List<WordBox> words)
{
CenterY = centerY;
Words = words;
}
public double CenterY { get; set; }
public List<WordBox> Words { get; }
}
}
internal static class ImageExtractor
{
public static IEnumerable<SavedImage> SaveImages(Page page, string imagesDirectory, string outputDirectory, string sourceBaseName)
{
var imageNumber = 0;
foreach (var image in page.GetImages())
{
imageNumber++;
var saved = SaveImage(image, imagesDirectory, outputDirectory, sourceBaseName, page.Number, imageNumber);
if (saved is not null)
{
yield return saved;
}
}
}
private static SavedImage? SaveImage(IPdfImage image, string imagesDirectory, string outputDirectory, string sourceBaseName, int pageNumber, int imageNumber)
{
var converted = true;
byte[] bytes;
string? extension;
if (image.TryGetPng(out var pngBytes) && pngBytes.Length > 0)
{
bytes = pngBytes;
extension = ".png";
}
else
{
var rawBytes = image.RawBytes.ToArray();
extension = ImageTypeDetector.GetExtension(rawBytes);
if (extension is null && image.TryGetBytes(out var decodedBytes))
{
rawBytes = decodedBytes.ToArray();
extension = ImageTypeDetector.GetExtension(rawBytes);
}
if (extension is null)
{
if (rawBytes.Length == 0)
{
return null;
}
converted = false;
extension = ".bin";
}
bytes = rawBytes;
}
var fileName = $"{sourceBaseName}_p{pageNumber:000}_img{imageNumber:000}{extension}";
var fullPath = Path.Combine(imagesDirectory, fileName);
File.WriteAllBytes(fullPath, bytes);
var relativePath = Path.GetRelativePath(outputDirectory, fullPath).Replace('\\', '/');
return new SavedImage(relativePath, fullPath, pageNumber, imageNumber, converted);
}
}
internal static class ImageTypeDetector
{
public static string? GetExtension(IReadOnlyList<byte> bytes)
{
if (StartsWith(bytes, [0xFF, 0xD8, 0xFF]))
{
return ".jpg";
}
if (StartsWith(bytes, [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]))
{
return ".png";
}
if (StartsWith(bytes, [0x47, 0x49, 0x46, 0x38]))
{
return ".gif";
}
if (StartsWith(bytes, [0x42, 0x4D]))
{
return ".bmp";
}
if (StartsWith(bytes, [0x49, 0x49, 0x2A, 0x00]) || StartsWith(bytes, [0x4D, 0x4D, 0x00, 0x2A]))
{
return ".tif";
}
if (bytes.Count >= 12
&& bytes[4] == 0x6A
&& bytes[5] == 0x50
&& bytes[6] == 0x20
&& bytes[7] == 0x20)
{
return ".jp2";
}
return null;
}
private static bool StartsWith(IReadOnlyList<byte> bytes, byte[] marker)
{
if (bytes.Count < marker.Length)
{
return false;
}
for (var i = 0; i < marker.Length; i++)
{
if (bytes[i] != marker[i])
{
return false;
}
}
return true;
}
}
internal static class TxtWriter
{
private static readonly UTF8Encoding Utf8WithBom = new(encoderShouldEmitUTF8Identifier: true);
public static void Write(string txtPath, DocumentContent content)
{
var builder = new StringBuilder();
builder.AppendLine(content.SourceFileName);
builder.AppendLine(new string('=', content.SourceFileName.Length));
builder.AppendLine();
foreach (var page in content.Pages)
{
builder.AppendLine($"Page {page.PageNumber}");
builder.AppendLine(new string('-', 16));
foreach (var line in page.Lines)
{
builder.AppendLine(line);
}
foreach (var image in page.Images)
{
builder.AppendLine();
builder.AppendLine(BuildImageLabel(image));
}
builder.AppendLine();
}
File.WriteAllText(txtPath, builder.ToString(), Utf8WithBom);
}
public static string BuildImageLabel(SavedImage image)
{
var suffix = image.Converted ? string.Empty : " (raw bytes, unsupported image encoding)";
return $"[Image page {image.PageNumber}, #{image.ImageNumber}: {image.RelativePath}{suffix}]";
}
}
internal static class DocxWriter
{
public static void Write(string docxPath, DocumentContent content)
{
using var document = WordprocessingDocument.Create(docxPath, WordprocessingDocumentType.Document);
var mainPart = document.AddMainDocumentPart();
mainPart.Document = new Document(new Body());
var body = mainPart.Document.Body!;
body.Append(CreateParagraph(content.SourceFileName, bold: true, fontSizeHalfPoints: 28));
foreach (var page in content.Pages)
{
body.Append(CreateParagraph($"Page {page.PageNumber}", bold: true, fontSizeHalfPoints: 24));
foreach (var line in page.Lines)
{
body.Append(CreateParagraph(line));
}
foreach (var image in page.Images)
{
body.Append(CreateImageLinkParagraph(mainPart, image));
}
}
body.Append(new SectionProperties());
mainPart.Document.Save();
}
private static Paragraph CreateParagraph(string text, bool bold = false, int? fontSizeHalfPoints = null)
{
var runProperties = new RunProperties();
if (bold)
{
runProperties.Append(new Bold());
}
if (fontSizeHalfPoints is not null)
{
runProperties.Append(new FontSize { Val = fontSizeHalfPoints.Value.ToString() });
}
return new Paragraph(new Run(runProperties, new Text(text) { Space = SpaceProcessingModeValues.Preserve }));
}
private static Paragraph CreateImageLinkParagraph(MainDocumentPart mainPart, SavedImage image)
{
var label = TxtWriter.BuildImageLabel(image);
var relationship = mainPart.AddHyperlinkRelationship(new Uri(image.RelativePath, UriKind.Relative), true);
var hyperlink = new DocumentFormat.OpenXml.Wordprocessing.Hyperlink(
new Run(
new RunProperties(
new Color { Val = "0563C1" },
new Underline { Val = UnderlineValues.Single }),
new Text(label) { Space = SpaceProcessingModeValues.Preserve }))
{
Id = relationship.Id
};
return new Paragraph(hyperlink);
}
}
internal static class FileNameTools
{
public static string Sanitize(string value)
{
var invalid = Path.GetInvalidFileNameChars();
var builder = new StringBuilder(value.Length);
foreach (var ch in value)
{
builder.Append(invalid.Contains(ch) ? '_' : ch);
}
var result = builder.ToString().Trim();
return string.IsNullOrWhiteSpace(result) ? "pdf" : result;
}
}