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 ;
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 )
{
var result = Cli . Wrap ( "/usr/bin/soffice" )
. WithArguments ( $"--headless --convert-to pdf {inputFileName} --outdir {outFileName}" ) ;
await result . ExecuteAsync ( ) ;
}
public async Task GetConverteAndMergedFileAsync ( IEnumerable < string > filesNames , string resultPath )
{
2023-01-17 05:14:04 +05:00
foreach ( var file in filesNames )
{
var fileExt = Path . GetExtension ( file ) ;
if ( fileExtension . All ( fe = > fileExt ! = fe ) )
{
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 )
{
if ( ! fileName . inputFile . ToLower ( ) . EndsWith ( ".pdf" ) )
await StartConvertProcessAsync ( fileName . inputFile , fileName . convertedFile ) ;
}
DoMergedAsync ( listFileNames . Select ( c = > c . convertedFile ) , resultPath ) ;
2023-01-17 05:14:04 +05:00
}
2023-01-13 17:28:04 +05:00
}
}