Updating
This commit is contained in:
+93
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using PdfSharp.Pdf;
|
||||
using PdfSharp.Pdf.IO;
|
||||
using Serilog;
|
||||
using Newtonsoft.Json;
|
||||
using LCU.Library.Internal.FileOperationsModels.Models;
|
||||
using LCU.Api.Internal.FileOperations.Services.FileActionServices;
|
||||
using LCU.Api.Internal.FileOperations.Validations;
|
||||
using LCU.Library.Internal.LCUServiceFactory.Configurations;
|
||||
namespace LCU.Api.Internal.FileOperations.Services.PdfServices;
|
||||
|
||||
public class BatchPdfParserService : FileActionService, IFileActionService, IBatchPdfParserService
|
||||
{
|
||||
public BatchPdfParserService(ServicesFactoryConfiguration servicesFactoryConfiguration)
|
||||
: base(servicesFactoryConfiguration)
|
||||
{
|
||||
}
|
||||
|
||||
public RequestResponse ExecuteAction(QueueRequest queueRequest)
|
||||
{
|
||||
var requestResponse = new RequestResponse();
|
||||
try
|
||||
{
|
||||
var request = JsonConvert.DeserializeObject<BatchParsePdfRequest>(queueRequest.Request);
|
||||
requestResponse = PerformRequest(request);
|
||||
requestResponse.ReturnResponse = request;
|
||||
return requestResponse;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
return RequestResponseHelper.ExceptionUpdateRequestResponse(requestResponse,
|
||||
queueRequest.FileOperationType,
|
||||
exception.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public RequestResponse PerformRequest(BatchParsePdfRequest request)
|
||||
{
|
||||
return OperationService.PerformOperation(request, IsRequestValid, BatchParsePdfs);
|
||||
}
|
||||
|
||||
public void BatchParsePdfs(BatchParsePdfRequest batchParsePdfRequest)
|
||||
{
|
||||
try
|
||||
{
|
||||
var inputDocument = PdfReader.Open(batchParsePdfRequest.FullPdfPath, PdfDocumentOpenMode.Import);
|
||||
foreach(var batchPdf in batchParsePdfRequest.BatchPdfs)
|
||||
{
|
||||
ParseAndSavePdf(batchParsePdfRequest, batchPdf, inputDocument);
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Log.Error(exception, $"Failure to Batch Parse Pdfs. ParsePdfRequest:{JsonConvert.SerializeObject(batchParsePdfRequest)}");
|
||||
throw new Exception($"Failure to Batch Parse Pdfs. ExceptionMessage:{exception.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void ParseAndSavePdf(BatchParsePdfRequest batchParsePdfRequest, BatchPdf batchPdf, PdfDocument inputDocument)
|
||||
{
|
||||
var outputDocument = AddPdfPagesToOutputDocument(batchPdf.PageStart, batchPdf.PageStop, inputDocument);
|
||||
string name = Path.GetFileNameWithoutExtension(batchParsePdfRequest.PdfName);
|
||||
var newPdfName = string.IsNullOrWhiteSpace(batchPdf.ParsedPdfname) ? $"{name}.{batchPdf.PageStart}.pdf" : batchPdf.ParsedPdfname;
|
||||
var newPath = Path.Combine(batchParsePdfRequest.RootPath, newPdfName);
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
outputDocument.Save(newPath);
|
||||
}
|
||||
|
||||
public PdfDocument AddPdfPagesToOutputDocument(int pageStart, int pageStop, PdfDocument inputDocument)
|
||||
{
|
||||
var startIndex = pageStart - 1;
|
||||
var stopIndex = pageStop - 1;
|
||||
var outputDocument = new PdfDocument();
|
||||
for (int page = startIndex; page <= stopIndex; page++)
|
||||
{
|
||||
outputDocument.Version = inputDocument.Version;
|
||||
outputDocument.Info.Title = inputDocument.Info.Title;
|
||||
outputDocument.Info.Creator = inputDocument.Info.Creator;
|
||||
outputDocument.AddPage(inputDocument.Pages[page]);
|
||||
}
|
||||
|
||||
return outputDocument;
|
||||
}
|
||||
|
||||
public RequestResponse IsRequestValid(BatchParsePdfRequest request, RequestResponse requestResponse)
|
||||
{
|
||||
requestResponse = DirectoryValidation.ValidateDirectoryExists(request.RootPath, requestResponse);
|
||||
requestResponse = FileValidation.ValidateFileExists(request.FullPdfPath, requestResponse);
|
||||
return requestResponse;
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using Serilog;
|
||||
using Newtonsoft.Json;
|
||||
using LCU.Library.Internal.Exceptions;
|
||||
using LCU.Library.Internal.FileOperationsModels.Models.HtmlToPdfModels;
|
||||
using LCU.Api.Internal.FileOperations.Configurations;
|
||||
using System.Threading;
|
||||
namespace LCU.Api.Internal.FileOperations.Services.PdfServices;
|
||||
|
||||
public class HtmlToPdfService : IHtmlToPdfService
|
||||
{
|
||||
private readonly ApiConfiguration _apiConfiguration;
|
||||
private readonly IDirectFileService _directFileService;
|
||||
|
||||
public HtmlToPdfService(ApiConfiguration apiConfiguration, IDirectFileService directFileService)
|
||||
{
|
||||
_apiConfiguration = apiConfiguration;
|
||||
_directFileService = directFileService;
|
||||
}
|
||||
|
||||
public byte[] ConvertHtmlToPdf(HtmlToPdfRequest htmlToPdfRequest)
|
||||
{
|
||||
try
|
||||
{
|
||||
var output = CreateHtmlOutput(htmlToPdfRequest);
|
||||
var finalOutput = CleanUpUnusedTagsFromOutput(output);
|
||||
|
||||
File.WriteAllText($"{htmlToPdfRequest.FinalHtmlSaveFilePath}{htmlToPdfRequest.PdfName}.html", finalOutput);
|
||||
var fileCreated = CreatePdfFromHtml(htmlToPdfRequest);
|
||||
|
||||
if (!fileCreated)
|
||||
{
|
||||
throw new ServiceException($"Pdf file was not created. HtmlToPdfRequest: {JsonConvert.SerializeObject(htmlToPdfRequest)}");
|
||||
}
|
||||
|
||||
var pdfBytes = _directFileService.GetFileBytes(htmlToPdfRequest.FinalPdfSaveFilePathWithFile);
|
||||
|
||||
CleanUpHtmlAndPdfFiles(htmlToPdfRequest);
|
||||
|
||||
return pdfBytes;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
var message = "Failure to Convert Html To Pdf.";
|
||||
Log.Error(exception, $"{message} HtmlToPdfRequest:{JsonConvert.SerializeObject(htmlToPdfRequest)}");
|
||||
throw new ServiceException($"{message}. ExceptionMessage:{exception.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public string CreateHtmlOutput(HtmlToPdfRequest htmlToPdfRequest)
|
||||
{
|
||||
var templateOutput = AddBodyValuesToTemplateOutput(htmlToPdfRequest);
|
||||
templateOutput = BuildOutputFromCollectionValues(htmlToPdfRequest.BodyValueCollections, templateOutput);
|
||||
return templateOutput;
|
||||
}
|
||||
|
||||
public string AddBodyValuesToTemplateOutput(HtmlToPdfRequest htmlToPdfRequest)
|
||||
{
|
||||
var templateOutput = File.ReadAllText(htmlToPdfRequest.HtmlTemplateFilePath);
|
||||
templateOutput = AddTagValuesToOutput(templateOutput, htmlToPdfRequest.BodyTagValues);
|
||||
return templateOutput;
|
||||
}
|
||||
|
||||
public string BuildOutputFromCollectionValues(List<ValueCollection> valueCollections, string output)
|
||||
{
|
||||
if (valueCollections == null || !valueCollections.Any())
|
||||
{
|
||||
return output;
|
||||
}
|
||||
|
||||
foreach (var bodyValueCollection in valueCollections)
|
||||
{
|
||||
var rowTemplateOutput = File.ReadAllText(bodyValueCollection.CollectionHtmlTemplateFilePath);
|
||||
var rowsBuilder = new StringBuilder();
|
||||
rowsBuilder = AddCollectionItemsToStringBuilder(bodyValueCollection.ValueCollectionItems, rowTemplateOutput, rowsBuilder);
|
||||
output = output.Replace($"{{{bodyValueCollection.CollectionTag}}}", rowsBuilder.ToString());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public string AddTagValuesToOutput(string output, List<TagValue> tagValues)
|
||||
{
|
||||
foreach (var tagValue in tagValues)
|
||||
{
|
||||
output = output.Replace($"{{{tagValue.Tag}}}", tagValue.Value);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public StringBuilder AddCollectionItemsToStringBuilder(List<ValueCollectionItem> valueCollectionItems, string output, StringBuilder builder)
|
||||
{
|
||||
foreach (var valueCollectionItem in valueCollectionItems)
|
||||
{
|
||||
var tempOutput = output;
|
||||
tempOutput = AddTagValuesToOutput(tempOutput, valueCollectionItem.TagValues);
|
||||
|
||||
if (valueCollectionItem.ValueCollections != null && valueCollectionItem.ValueCollections.Any())
|
||||
{
|
||||
tempOutput = BuildItemValueCollectionsOutput(valueCollectionItem.ValueCollections, tempOutput);
|
||||
}
|
||||
|
||||
builder.Append(tempOutput);
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
|
||||
public string BuildItemValueCollectionsOutput(List<ValueCollection> valueCollections, string templateOutput)
|
||||
{
|
||||
if (valueCollections == null)
|
||||
{
|
||||
return templateOutput;
|
||||
}
|
||||
|
||||
templateOutput = BuildOutputFromCollectionValues(valueCollections, templateOutput);
|
||||
return templateOutput;
|
||||
}
|
||||
|
||||
public string CleanUpUnusedTagsFromOutput(string output)
|
||||
{
|
||||
var pattern = @"{[A-Za-z0-9]*}";
|
||||
var finalOutput = Regex.Replace(output, pattern, string.Empty);
|
||||
return finalOutput;
|
||||
}
|
||||
|
||||
public void SaveHtmlToFilePath(HtmlToPdfRequest htmlToPdfRequest, string htmlOutput)
|
||||
{
|
||||
|
||||
using (StreamWriter outputFile = new StreamWriter($"{htmlToPdfRequest.FinalHtmlSaveFilePath}{htmlToPdfRequest.PdfName}.html"))
|
||||
{
|
||||
outputFile.Write(htmlOutput);
|
||||
}
|
||||
}
|
||||
|
||||
public bool CreatePdfFromHtml(HtmlToPdfRequest htmlToPdfRequest)
|
||||
{
|
||||
try
|
||||
{
|
||||
var url = $"{htmlToPdfRequest.FinalHtmlSaveFilePath}{htmlToPdfRequest.PdfName}.html";
|
||||
var output = Path.Combine(htmlToPdfRequest.FinalPdfSaveFilePath, $"{htmlToPdfRequest.PdfName}.pdf");
|
||||
using (var process = new Process())
|
||||
{
|
||||
process.StartInfo.FileName = _apiConfiguration.ChromePath;
|
||||
process.StartInfo.Arguments = $"--user-data-dir={_apiConfiguration.FileOperationsChromeProfileFolderPath} " +
|
||||
$"--headless --disable-gpu --print-to-pdf={output} {url} --no-pdf-header-footer";
|
||||
process.Start();
|
||||
process.WaitForExit();
|
||||
}
|
||||
|
||||
var attempts = 0;
|
||||
var fileCreated = false;
|
||||
|
||||
while (!fileCreated)
|
||||
{
|
||||
fileCreated = File.Exists(htmlToPdfRequest.FinalPdfSaveFilePathWithFile);
|
||||
attempts++;
|
||||
|
||||
if (attempts > _apiConfiguration.MaxFileCheckAttempts)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
Thread.Sleep(1000);
|
||||
}
|
||||
|
||||
return fileCreated;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
var message = $"Failure to Create Pdf From Html.";
|
||||
Log.Error(exception, message);
|
||||
throw new Exception($"{message}. Exception Message: {exception.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void CleanUpHtmlAndPdfFiles(HtmlToPdfRequest htmlToPdfRequest)
|
||||
{
|
||||
if (!htmlToPdfRequest.KeepHtmlFile)
|
||||
{
|
||||
File.Delete(htmlToPdfRequest.FinalHtmlSaveFilePathWithFile);
|
||||
}
|
||||
|
||||
if (!htmlToPdfRequest.KeepPdfFile)
|
||||
{
|
||||
File.Delete(htmlToPdfRequest.FinalPdfSaveFilePathWithFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
using LCU.Library.Internal.FileOperationsModels.Models;
|
||||
namespace LCU.Api.Internal.FileOperations.Services;
|
||||
|
||||
public interface IBatchPdfParserService
|
||||
{
|
||||
RequestResponse ExecuteAction(QueueRequest queueRequest);
|
||||
RequestResponse IsRequestValid(BatchParsePdfRequest request, RequestResponse requestResponse);
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
using LCU.Library.Internal.FileOperationsModels.Models.HtmlToPdfModels;
|
||||
namespace LCU.Api.Internal.FileOperations.Services.PdfServices;
|
||||
|
||||
public interface IHtmlToPdfService
|
||||
{
|
||||
byte[] ConvertHtmlToPdf(HtmlToPdfRequest htmlToPdfRequest);
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
using LCU.Library.Internal.FileOperationsModels.Models;
|
||||
|
||||
namespace LCU.Api.Internal.FileOperations.Services
|
||||
{
|
||||
public interface IPdfParserService
|
||||
{
|
||||
string ParsePdf(ParsePdfRequest parsePdfRequest);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using PdfSharp.Pdf;
|
||||
using PdfSharp.Pdf.IO;
|
||||
using Serilog;
|
||||
using Newtonsoft.Json;
|
||||
using LCU.Library.Internal.Exceptions;
|
||||
using LCU.Library.Internal.FileOperationsModels.Models;
|
||||
namespace LCU.Api.Internal.FileOperations.Services.PdfServices;
|
||||
|
||||
public class PdfParserService : IPdfParserService
|
||||
{
|
||||
public string ParsePdf(ParsePdfRequest parsePdfRequest)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fullPath = Path.Combine(parsePdfRequest.RootPath, parsePdfRequest.PdfName);
|
||||
var inputDocument = PdfReader.Open(fullPath, PdfDocumentOpenMode.Import);
|
||||
|
||||
|
||||
var startIndex = parsePdfRequest.PageStart - 1;
|
||||
var stopIndex = parsePdfRequest.PageStop - 1;
|
||||
var outputDocument = new PdfDocument();
|
||||
for (int page = startIndex; page <= stopIndex; page++)
|
||||
{
|
||||
outputDocument.Version = inputDocument.Version;
|
||||
outputDocument.Info.Title = inputDocument.Info.Title;
|
||||
outputDocument.Info.Creator = inputDocument.Info.Creator;
|
||||
outputDocument.AddPage(inputDocument.Pages[page]);
|
||||
}
|
||||
|
||||
string name = Path.GetFileNameWithoutExtension(parsePdfRequest.PdfName);
|
||||
var newPdfName = string.IsNullOrWhiteSpace(parsePdfRequest.ParsedPdfname) ? $"{name}.{parsePdfRequest.PageStart}.pdf" : parsePdfRequest.ParsedPdfname;
|
||||
var newPath = Path.Combine(parsePdfRequest.RootPath, newPdfName);
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
outputDocument.Save(newPath);
|
||||
|
||||
return newPdfName;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Log.Error(exception, $"Failure to Parse Pdf. ParsePdfRequest:{JsonConvert.SerializeObject(parsePdfRequest)}");
|
||||
throw new ServiceException($"Failure to Parse Pdf. ExceptionMessage:{exception.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user