47 lines
1.9 KiB
C#
47 lines
1.9 KiB
C#
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}");
|
|
}
|
|
}
|
|
} |