I got this from somewhere on the web - can't remember exactly where but it works for me!
I just made it into a nice function.
It uses the GhostScript APIs (GSdll32.dll)
Examples of the imageFormat parameter are "jpeg", "tiff32nc", etc.
#region GhostScript API functions
[DllImport("gsdll32.dll", EntryPoint = "gsapi_new_instance")]
private static extern int CreateAPIInstance(out IntPtr pinstance,
IntPtr caller_handle);
[DllImport("gsdll32.dll", EntryPoint = "gsapi_init_with_args")]
private static extern int InitAPI(IntPtr instance, int argc, IntPtr argv);
[DllImport("gsdll32.dll", EntryPoint = "gsapi_exit")]
private static extern int ExitAPI(IntPtr instance);
[DllImport("gsdll32.dll", EntryPoint = "gsapi_delete_instance")]
private static extern void DeleteAPIInstance(IntPtr instance);
#endregion
public bool CreateImage(string inputPath, string outputPath, string imageFormat, int firstPage, int lastPage, int width, int height)
{
bool result = false;
try
{
string[] args = GetArgs(inputPath, outputPath, imageFormat, firstPage, lastPage, width, height);
var argStrHandles = new GCHandle[args.Length];
var argPtrs = new IntPtr[args.Length];
// Create a handle for each of the arguments after
// they've been converted to an ANSI null terminated
// string. Then store the pointers for each of the handles
for (int i = 0; i < args.Length; i++)
{
argStrHandles[i] = GCHandle.Alloc(StringToAnsi(args[i]), GCHandleType.Pinned);
argPtrs[i] = argStrHandles[i].AddrOfPinnedObject();
}
// Get a new handle for the array of argument pointers
var argPtrsHandle = GCHandle.Alloc(argPtrs, GCHandleType.Pinned);
// Get a pointer to an instance of the GhostScript API
// and run the API with the current arguments
IntPtr gsInstancePtr;
CreateAPIInstance(out gsInstancePtr, IntPtr.Zero);
InitAPI(gsInstancePtr, args.Length, argPtrsHandle.AddrOfPinnedObject());
// Cleanup arguments in memory
for (int i = 0; i < argStrHandles.Length; i++)
argStrHandles[i].Free();
argPtrsHandle.Free();
// Clear API
ExitAPI(gsInstancePtr);
DeleteAPIInstance(gsInstancePtr);
result = true;
}
catch(Exception e)
{
throw e;
}
return result;
}