Handle non seekable stream by copying it into a memory stream and fix #1146

This commit is contained in:
BobLd
2025-09-14 08:43:06 +01:00
parent 44e638ee4d
commit eb906a776d
2 changed files with 21 additions and 3 deletions

View File

@@ -44,9 +44,23 @@
internal static PdfDocument Open(Stream stream, ParsingOptions? options) internal static PdfDocument Open(Stream stream, ParsingOptions? options)
{ {
var streamInput = new StreamInputBytes(stream, false); StreamInputBytes streamInput;
long initialPosition;
var initialPosition = stream.Position; if (stream is { CanRead: true, CanSeek: false })
{
// We need the stream to be seekable
var ms = new MemoryStream();
stream.CopyTo(ms); // Copy the non seekable stream in memory (seekable)
ms.Position = 0;
streamInput = new StreamInputBytes(ms, true); // The created memory stream will be disposed on document dispose
initialPosition = ms.Position;
}
else
{
streamInput = new StreamInputBytes(stream, false);
initialPosition = stream.Position;
}
try try
{ {

View File

@@ -112,10 +112,14 @@
/// <summary> /// <summary>
/// Creates a <see cref="PdfDocument"/> for reading from the provided stream. /// Creates a <see cref="PdfDocument"/> for reading from the provided stream.
/// <para>
/// If the stream provided is not seekable (<see cref="Stream.CanSeek"/> is <c>false</c>), the stream will be copied into a new <see cref="MemoryStream"/>.
/// </para>
/// The caller must manage disposing the stream. The created PdfDocument will not dispose the stream. /// The caller must manage disposing the stream. The created PdfDocument will not dispose the stream.
/// </summary> /// </summary>
/// <param name="stream"> /// <param name="stream">
/// A stream of the file contents, this must support reading and seeking. /// A stream of the file contents, this must support reading and seeking.
/// <para>If the stream provided is not seekable (<see cref="Stream.CanSeek"/> is <c>false</c>), the stream will be copied into a new <see cref="MemoryStream"/>.</para>
/// The PdfDocument will not dispose of the provided stream. /// The PdfDocument will not dispose of the provided stream.
/// </param> /// </param>
/// <param name="options">Optional parameters controlling parsing.</param> /// <param name="options">Optional parameters controlling parsing.</param>