2023-01-13 17:28:04 +05:00
using iTextSharp.text ;
using iTextSharp.text.pdf ;
using System.Collections.Generic ;
using System.IO ;
using System.Linq ;
using CliWrap ;
using System.Threading.Tasks ;
2023-01-17 11:11:40 +05:00
using System.Threading ;
2023-01-13 17:28:04 +05:00
namespace AsbCloudInfrastructure.Services.DrillingProgram.Convert
{
internal class ConvertToPdf
{
2023-01-17 12:09:58 +05:00
private readonly string [ ] filesExtensions = { ".xlsx" , ".xls" , ".ods" , ".odt" , ".doc" , ".docx" , ".pdf" } ;
2023-01-13 17:28:04 +05:00
2023-01-17 12:09:58 +05:00
public static void MergeFiles ( IEnumerable < string > inputFiles , string outFile )
2023-01-13 17:28:04 +05:00
{
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 ) ;
} ) ;
}
}
2023-01-17 11:11:40 +05:00
private async Task StartConvertProcessAsync ( string inputFileName , string outFileName , CancellationToken token )
2023-01-13 17:28:04 +05:00
{
var result = Cli . Wrap ( "/usr/bin/soffice" )
2023-01-17 11:11:40 +05:00
. WithArguments ( $"--headless --convert-to pdf {inputFileName} --outdir {outFileName}" ) ;
await result . ExecuteAsync ( token ) ;
2023-01-13 17:28:04 +05:00
}
2023-01-17 11:11:40 +05:00
public async Task GetConverteAndMergedFileAsync ( IEnumerable < string > filesNames , string resultPath , CancellationToken token )
2023-01-13 17:28:04 +05:00
{
2023-01-17 05:14:04 +05:00
foreach ( var file in filesNames )
{
var fileExt = Path . GetExtension ( file ) ;
2023-01-17 12:09:58 +05:00
if ( ! filesExtensions . Contains ( fileExt ) )
2023-01-17 05:14:04 +05:00
{
throw new FileFormatException ( $"Файл с именем: {file} - неподдерживаемого формата. Он не может быть добавлен в список файлов для конвертации и слияния в общий файл программы бурения." ) ;
}
}
var listFileNames = filesNames
2023-01-13 17:28:04 +05:00
. Distinct ( )
. Select ( o = > new {
inputFile = o ,
convertedFile = Path . ChangeExtension ( o , ".pdf" )
2023-01-17 05:14:04 +05:00
} )
. ToList ( ) ;
2023-01-13 17:28:04 +05:00
foreach ( var fileName in listFileNames )
{
2023-01-17 11:11:40 +05:00
var fileExt = Path . GetExtension ( fileName . inputFile ) ;
if ( fileExt ! = ".pdf" )
2023-01-17 12:09:58 +05:00
{
2023-01-17 11:11:40 +05:00
await StartConvertProcessAsync ( fileName . inputFile , fileName . convertedFile , token ) ;
}
2023-01-13 17:28:04 +05:00
}
2023-01-17 12:09:58 +05:00
MergeFiles ( listFileNames . Select ( c = > c . convertedFile ) , resultPath ) ;
2023-01-17 05:14:04 +05:00
}
2023-01-13 17:28:04 +05:00
}
}