problem with GhostscriptRasterizer reading from MemoryStream and the solution

Jan 15, 2014 at 8:39 AM
Hello
There is a problem when Calling GhostscriptRasterizer.Open with a MemoryStream. It says that the format must be pdf, ps or eps. My file is eps and opens correctly in the Viewer sample.

I tracked the problem down to the method GhostScriptViewer.StoreMemoryStreamToTemporaryFile. It tries to figure out the file extensions by looking at a couple of bytes in the stream, but it fails to recognize my file data. There is something wrong with this check or perhaps my file is of a different version of the format.

Anyway I fixed it by adding an overloaded method that also take the extension as a paramater and then no check is needed. I only check that the parameter contains a valid extension. I also made a couple of other overloads to support opening using this method.

Great lib otherwise!
Coordinator
Jan 15, 2014 at 7:57 PM
Hi,

Thank you for reporting this problem and I'm glad you managed to find the solution. Can you please send me a link to the eps file you have tried to open so I can see what's the difference between that one and ones i was testing with?

Cheers,
Josip
Coordinator
Jan 17, 2014 at 3:27 PM
Edited Jan 17, 2014 at 3:28 PM
Just to keep others up-to-date.

With help from Chanan this problem is fixed. Now EPS files with the preview header signature are also supported.

Untill next release (1.1.3) here is the code that has to be replaced in Ghostscript.NET->Viewer->GhostscriptViewer.cs:
#region StoreMemoryStreamToTemporaryFile

private string StoreMemoryStreamToTemporaryFile(MemoryStream stream)
{
    if (stream.Length < 4)
    {
        throw new InvalidDataException();
    }

    byte[] test = new byte[4];

    stream.Read(test, 0, 4);

    stream.Position = 0;

    string extension = string.Empty;

    if (test[0] == 0x25 && test[1] == 0x21) // standard ps or eps signature
    {
        extension = ".ps";

        if (stream.Length > 23)
        {
            test = new byte[23];
            stream.Read(test, 0, 23);

            stream.Position = 0;

            string tmp = System.Text.Encoding.ASCII.GetString(test);

            if (tmp.ToUpper().Contains("EPS"))
            {
                extension = ".eps";
            }
        }
    }
    else if (test[0] == 0xc5 && test[1] == 0xd0 && test[2] == 0xd3 && test[3] == 0xc6) // eps with preview header signature / magic number (always C5D0D3C6)
    {
        extension = ".eps";
    }
    else if (test[0] == 0x25 && test[1] == 0x50 && test[2] == 0x44 && test[3] == 0x46) // pdf signature
    {
        extension = ".pdf";
    }
    else
    {
        throw new FormatException("Stream format is not valid! Please make sure it's PDF, PS or EPS.");
    }

    string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + extension);

    File.WriteAllBytes(path, stream.ToArray());

    _fileCleanupHelper.Add(path);

    return path;
}

#endregion