forked from ddrilling/AsbCloudServer
71 lines
2.9 KiB
C#
71 lines
2.9 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
|
|
internal class ConvertToPdf
|
|
{
|
|
private 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}");
|
|
await result.ExecuteAsync(token);
|
|
}
|
|
|
|
public 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();
|
|
foreach (var fileName in listFileNames)
|
|
{
|
|
var fileExt = Path.GetExtension(fileName.inputFile);
|
|
if (fileExt != ".pdf")
|
|
{
|
|
await StartConvertProcessAsync(fileName.inputFile, fileName.convertedFile, token);
|
|
}
|
|
}
|
|
MergeFiles(listFileNames.Select(c => c.convertedFile), resultPath);
|
|
}
|
|
}
|
|
#nullable disable
|
|
}
|