DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/DrillingProgram/Convert/ConvertToPdf.cs

78 lines
3.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
{
internal class ConvertToPdf
{
private readonly string[] fileExtension = { ".xlsx", ".xls", ".ods", ".odt", ".doc", ".docx", ".pdf" };
public static void DoMergedAsync(IEnumerable<string> inputFiles, string outFile)
{
using (FileStream stream = new FileStream(outFile, FileMode.Create))
using (Document doc = new Document())
using (PdfCopy pdf = new PdfCopy(doc, stream))
{
doc.Open();
PdfReader reader = null;
PdfImportedPage page = null;
inputFiles.ToList().ForEach(file =>
{
reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
File.Delete(file);
});
}
}
private 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)
{
foreach (var file in filesNames)
{
var fileExt = Path.GetExtension(file);
if (fileExtension.All(fe => fileExt != fe))
{
throw new FileFormatException($"Файл с именем: {file} - неподдерживаемого формата. Он не может быть добавлен в список файлов для конвертации и слияния в общий файл программы бурения.");
}
}
var listFileNames = filesNames
.Distinct()
.Select(o => new {
inputFile = o,
convertedFile = Path.ChangeExtension(o, ".pdf")
})
.ToList();
foreach (var fileName in listFileNames)
{
var fileExt = Path.GetExtension(fileName.inputFile);
if (fileExt != ".pdf")
{
//FileInfo fileInfo = new FileInfo(fileName.inputFile);
await StartConvertProcessAsync(fileName.inputFile, fileName.convertedFile, token);
}
}
DoMergedAsync(listFileNames.Select(c => c.convertedFile), resultPath);
}
}
}