using iTextSharp.text; using iTextSharp.text.pdf; using System.Collections.Generic; using System.IO; using System.Linq; using CliWrap; using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services.DrillingProgram.Convert { internal class ConvertToPdf { private readonly string[] fileExtension = { ".xlsx", ".xls", ".ods", ".odt", ".doc", ".docx", ".pdf" }; public static void DoMergedAsync(IEnumerable 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) { var result = Cli.Wrap("/usr/bin/soffice") .WithArguments($"--headless --convert-to pdf {inputFileName} --outdir {outFileName}"); await result.ExecuteAsync(); } public async Task GetConverteAndMergedFileAsync(IEnumerable filesNames, string resultPath) { var filteredFilesNames = filesNames .Distinct() .Where(f => fileExtension.Any(fe => f.ToLower().EndsWith(fe))) .ToList(); var listFileNames = filteredFilesNames .ToList() .Select(o => new { inputFile = o, convertedFile = Path.ChangeExtension(o, ".pdf") }); foreach (var fileName in listFileNames) { if (!fileName.inputFile.ToLower().EndsWith(".pdf")) await StartConvertProcessAsync(fileName.inputFile, fileName.convertedFile); } DoMergedAsync(listFileNames.Select(c => c.convertedFile), resultPath); } } }