feat(pdf): add option to preserve input stream on disposal

- Introduced `disposeInputStream` parameter in `Pdf<TInputStream, TOutputStream>` constructor.
- Updated `Dispose` and `DisposeAsync` to conditionally dispose the input stream based on this flag.
- Updated `Pdf.FromMemory(MemoryStream)` to not dispose the provided MemoryStream by default.
- Ensures better control over resource management when reusing input streams.
This commit is contained in:
tekh 2025-10-23 13:51:40 +02:00
parent 241e59fc7e
commit c456d67d03

View File

@ -20,7 +20,7 @@ namespace EnvelopeGenerator.PdfEditor
public static Pdf<MemoryStream, MemoryStream> FromMemory(MemoryStream stream)
{
return new Pdf<MemoryStream, MemoryStream>(stream, new MemoryStream());
return new Pdf<MemoryStream, MemoryStream>(stream, new MemoryStream(), disposeInputStream: false);
}
}
@ -34,13 +34,16 @@ namespace EnvelopeGenerator.PdfEditor
private readonly PdfReader _reader;
private readonly PdfWriter _writer;
public Pdf(TInputStream inputStream, TOutputStream outputStream)
private readonly bool _disposeInputStream;
public Pdf(TInputStream inputStream, TOutputStream outputStream, bool disposeInputStream = true)
{
_inputStream = inputStream;
_outputStream = outputStream;
_reader = new PdfReader(inputStream);
_writer = new PdfWriter(outputStream);
_doc = new PdfDocument(_reader, _writer);
_disposeInputStream = disposeInputStream;
}
/// <summary>
@ -152,7 +155,7 @@ namespace EnvelopeGenerator.PdfEditor
{
// Managed resources
_doc?.Close();
_inputStream?.Dispose();
if (_disposeInputStream) _inputStream?.Dispose();
_outputStream?.Dispose();
}
else
@ -160,7 +163,7 @@ namespace EnvelopeGenerator.PdfEditor
// When called by the finalizer, clean up only unmanaged resources
// Unmanaged resources such as PdfDocument, PdfReader, and PdfWriter are already IDisposable; we close them here
try { _doc?.Close(); } catch { }
try { _inputStream?.Dispose(); } catch { }
try { if(_disposeInputStream) _inputStream?.Dispose(); } catch { }
try { _outputStream?.Dispose(); } catch { }
}
@ -173,10 +176,13 @@ namespace EnvelopeGenerator.PdfEditor
return;
_doc?.Close();
if (_inputStream is IAsyncDisposable asyncInput)
await asyncInput.DisposeAsync();
else
_inputStream.Dispose();
if (_disposeInputStream)
{
if (_inputStream is IAsyncDisposable asyncInput)
await asyncInput.DisposeAsync();
else
_inputStream.Dispose();
}
if (_outputStream is IAsyncDisposable asyncOutput)
await asyncOutput.DisposeAsync();