DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/DrillingProgram/Convert/ConvertToPdf.cs
2023-01-20 08:32:22 +05:00

79 lines
3.3 KiB
C#

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CliWrap;
using System.Threading.Tasks;
using System.Threading;
namespace AsbCloudInfrastructure.Services.DrillingProgram.Convert
{
#nullable enable
sealed internal class ConvertToPdf
{
private static readonly string[] filesExtensions = { ".xlsx", ".xls", ".ods", ".odt", ".doc", ".docx", ".pdf" };
private static void MergeFiles(IEnumerable<string> inputFiles, string outFile)
{
using var stream = new FileStream(outFile, FileMode.Create);
using var doc = new Document();
using var pdf = new PdfCopy(doc, stream);
doc.Open();
var inputFilesList = inputFiles.ToList();
foreach (var file in inputFilesList)
{
var reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
pdf.AddPage(pdf.GetImportedPage(reader, i + 1));
}
pdf.FreeReader(reader);
reader.Close();
};
}
private static async Task StartConvertProcessAsync(string inputFileName, string outFileName, CancellationToken token)
{
//var result = Cli.Wrap("/usr/bin/soffice")
// .WithArguments($"--headless --convert-to pdf {inputFileName} --outdir {outFileName}");
var result = Cli.Wrap("C:\\Program Files\\LibreOffice\\program\\soffice.exe")
.WithArguments($"-headless -convert-to pdf {inputFileName} --outdir {outFileName}");
await result.ExecuteAsync(token);
}
public static async Task GetConverteAndMergedFileAsync(IEnumerable<string> filesNames, string resultPath, CancellationToken token)
{
var badFiles = filesNames.Where(f => !filesExtensions.Contains(Path.GetExtension(f)));
if (badFiles.Any())
{
throw new FileFormatException($"Файлы: {string.Join(", ", badFiles)} - неподдерживаемого формата. " +
$"Они не могут быть добавлены в список файлов для конвертации и слияния в общий файл программы бурения.");
}
var listFileNames = filesNames
.Distinct()
.Select(f => new {
inputFile = f,
convertedFile = Path.ChangeExtension(f, ".pdf")
})
.ToList();
var listFilesToDelete = new List<string>();
foreach (var fileName in listFileNames)
{
var fileExt = Path.GetExtension(fileName.inputFile);
if (fileExt != ".pdf")
{
await StartConvertProcessAsync(fileName.inputFile, fileName.convertedFile, token);
listFilesToDelete.Add(fileName.convertedFile);
}
}
MergeFiles(listFileNames.Select(c => c.convertedFile), resultPath);
foreach (var file in listFilesToDelete)
{
File.Delete(file);
}
}
}
#nullable disable
}