PDF to Image using GhostScript. No image file has to be created

橙三吉。 提交于 2019-12-21 21:39:58

问题


I need to convert a PDF to JPEG (or any other image format as PNG...) with C#

I have the path to the PDF and I want to obtain a MemoryStream of the image.

I managed to do it with Ghostscript and GhostscriptSharp but I'm forced to create a file, the actual image, and then read this file to create the MemoryStream.

Can I do it without this step?

Thanks


回答1:


Yes, but you will need to interface directly to Ghostscript using the Ghostscript DLL (I'm assuming Windows since you mention C#).

The simplest solution is probably to use the display device which sends an in-memory bitmap back to the parent application, the default GS application then creates a window and a device context, and draws the bitmap in it.

You should be able to use the GS application as a starting point to see how this is done, and you don't need to create a device of your own which means you don't need to recompile the Ghostscript binary.




回答2:


Yes you can create a memory stream from the Ghostscript.Net rasterize function. Here is an example I used on a asp.net site.

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

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

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

            using (MemoryStream ms = new MemoryStream())
            {
                DrawImage 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();
    }
} 


来源:https://stackoverflow.com/questions/8669677/pdf-to-image-using-ghostscript-no-image-file-has-to-be-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!