We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Problem with InputFileStream

Hi,
I convert the stream of a pdf viewer into a string:

string text = Convert.ToBase64String(ReadFully(pdfViewerControl.InputFileStream));

private static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

That's work fine, but when i try to do the inverse process, i have this error:

Stream str = new MemoryStream(Convert.FromBase64String(text));
pdfViewerControl.InputFileStream = str;

Syncfusion.Pdf.PdfException: 'Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.'


What is the solution for this?
Thanks.


PD: The objective is can save the string, and in any moment, can convert it into a stream and print it in a pdf viewer.

1 Reply

SS Sathish Sivakumar Syncfusion Team April 1, 2019 12:59 PM UTC

Hi Joan,

Greetings from Syncfusion.

On analysing the issue, we confirmed that the exception is not due to our PdfViewer control. It occurs because the stream is not read into string properly. Since the "InputFileStream" is manipulated inside PdfViewer for its own operations, its "Position" property may be random. For instance if the position is set to 9, in the method given in the last update "ReadFully(Stream input)", the converted string will only have the data from the 9th position to the end of the stream.

So, in order to resolve the exception we need to reset the position of the stream to 0. Please find the necessary code change below.

private static byte[] ReadFully(Stream input)
{
if (input.CanSeek)
input.Position = 0;
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}

Regards,
Sathish 


Loader.
Up arrow icon