Refactor to use streams for PDF handling
Refactored `IPdfDigitalSignatureService` to replace `byte[]` with `Stream` for input and output, improving memory efficiency and scalability. Updated `PdfDigitalSignatureService` implementation to support stream-based operations, including signing, checking, and extracting PDFs. Modified `SignPdfAsync` to handle multiple signatures sequentially using streams and ensured proper disposal of intermediate streams. Updated `CheckPdfSignatureAsync` and `ExtractOriginalPdfAsync` to use streams, reducing memory overhead. Refactored `PdfSignatureController` to use streams for file handling, enabling efficient processing of large files. Introduced helper methods for stream handling and enhanced cancellation support. Improved code maintainability by consolidating common logic and reducing duplication.
This commit is contained in:
@@ -39,14 +39,6 @@ public class PdfSignatureController(IPdfDigitalSignatureService signatureService
|
||||
if (!file.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
|
||||
return BadRequest("Only PDF files are supported.");
|
||||
|
||||
byte[] sourcePdf;
|
||||
await using (var input = file.OpenReadStream())
|
||||
using (var ms = new MemoryStream())
|
||||
{
|
||||
await input.CopyToAsync(ms, cancel);
|
||||
sourcePdf = ms.ToArray();
|
||||
}
|
||||
|
||||
var signOptions = new PdfSignOptionsDto
|
||||
{
|
||||
UUID = request.UUID,
|
||||
@@ -58,9 +50,12 @@ public class PdfSignatureController(IPdfDigitalSignatureService signatureService
|
||||
CertificationLevel = PdfSignatureCertificationLevel.FormFillingAndAnnotations
|
||||
};
|
||||
|
||||
byte[] signedPdf = await signatureService.SignPdfAsync(sourcePdf, signOptions, cancel);
|
||||
await using var input = file.OpenReadStream();
|
||||
await using var output = new MemoryStream();
|
||||
await signatureService.SignPdfAsync(input, output, signOptions, cancel);
|
||||
output.Position = 0;
|
||||
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
|
||||
return File(signedPdf, "application/pdf", $"{fileName}-signed.pdf");
|
||||
return File(output, "application/pdf", $"{fileName}-signed.pdf");
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
@@ -76,15 +71,8 @@ public class PdfSignatureController(IPdfDigitalSignatureService signatureService
|
||||
if (!file.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
|
||||
return BadRequest("Only PDF files are supported.");
|
||||
|
||||
byte[] sourcePdf;
|
||||
await using (var input = file.OpenReadStream())
|
||||
using (var ms = new MemoryStream())
|
||||
{
|
||||
await input.CopyToAsync(ms, cancel);
|
||||
sourcePdf = ms.ToArray();
|
||||
}
|
||||
|
||||
var result = await signatureService.CheckPdfSignatureAsync(sourcePdf, cancel);
|
||||
await using var input = file.OpenReadStream();
|
||||
var result = await signatureService.CheckPdfSignatureAsync(input, cancel);
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user