Reputation: 588
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
Upvotes: 2
Views: 3487
Reputation: 1410
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();
}
}
Upvotes: 2
Reputation: 31199
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.
Upvotes: 3