MemoryStream (pdf) to Ghostscript to MemoryStream (jpg)

Adam Miller picture Adam Miller · Jan 3, 2014 · Viewed 7.9k times · Source

I did see "PDF to Image using GhostScript. No image file has to be created", but that only (sort of) answered half my question. Is it possible to use GhostScriptSharp (or the regular GhostScript dll) to convert a pdf in a MemoryStream to a jpg in a MemoryStream? I speak of a dynamically filled in pdf form with iTextSharp which I am already directing to a MemoryStream to save to a database or stream to a http response, and I'd really love to avoid saving to a file (and subsequent cleanup) if I can.

The sole answer in the answer I referenced claimed that one has to go down to the GhostScript dll to do the latter part, but it was obvious I would need to do a good bit of leg-work to figure out what that meant. Does anyone have a good resource that could help me on this journey?

Answer

RobbZ picture RobbZ · May 7, 2015

Ghostscript.Net is a wrapper to the Ghostscript dll. It now can take a stream object and can return an image that can be saved to an stream. Here is an example that I used on as ASP page to generate PDF's from a memory stream. I haven't completely figured out the best way to handle the ghostscript dll and where to locate it on the server.

 void PDFToImage(MemoryStream inputMS, int dpi)
    {
        GhostscriptRasterizer rasterizer = null;
        GhostscriptVersionInfo version = new GhostscriptVersionInfo(
                                                                new Version(0, 0, 0), @"C:\PathToDll\gsdll32.dll", 
                                                                string.Empty, GhostscriptLicense.GPL);

        using (rasterizer = new GhostscriptRasterizer())
        {
            rasterizer.Open(inputMS, version, false);

            for (int i = 1; i <= rasterizer.PageCount; i++)
            {

                using (MemoryStream ms = new MemoryStream())
                {
                    Image img = rasterizer.GetPage(dpi, dpi, i);
                    img.Save(ms, ImageFormat.Jpeg);
                    ms.Close();

                    AspImage newPage = new AspImage();
                    newPage.ImageUrl = "data:image/png;base64," + Convert.ToBase64String((byte[])ms.ToArray());

                    Document1Image.Controls.Add(newPage);
                }

            }

            rasterizer.Close();
        }
    }