Copy Code code as follows:
Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Runtime.InteropServices;
Using System.Collections;
/**
Convert PDF to Image Format (JPEG) using Ghostscript API
Convert a PDF to JPEG using Ghostscript command line:
Gswin32c-q-dquiet-dparanoidsafer-dbatch-dnopause-dnoprompt-dmaxbitmap=500000000-dfirstpage=1-daligntopixels=0- Dgridfittt=0-sdevice=jpeg-dtextalphabits=4-dgraphicsalphabits=4-r100x100-soutputfile=output.jpg test.pdf
also:http://www.mattephraim.com/blog/2009/01/06/a-simple-c-wrapper-for-ghostscript/
And:http://www.codeproject.com/kb/cs/ghostscriptusewithcsharp.aspx
Note:copy Gsdll32.dll to system32 directory before the using this Ghostscript wrapper.
*
*/
Namespace Convertpdf
{
<summary>
///
Class to convert a PDF to an image using Ghostscript DLL
Credit for this code go To:rangel avulso
I only fix a little bug and refactor a little
http://www.hrangel.com.br/index.php/2006/12/04/converter-pdf-para-imagem-jpeg-em-c/
</summary>
<seealso cref= "http://www.hrangel.com.br/index.php/2006/12/04/converter-pdf-para-imagem-jpeg-em-c/"/>
Class Pdfconvert
{
#region Ghostscript Import
<summary>create a new instance of Ghostscript. This instance was passed to most the other GSAPI functions. The caller_handle is provided to callback functions.
At this stage, Ghostscript supports is only one instance. </summary>
<param name= "Pinstance" ></param>
<param name= "Caller_handle" ></param>
<returns></returns>
[DllImport ("Gsdll32.dll", entrypoint= "Gsapi_new_instance")]
private static extern int gsapi_new_instance (out IntPtr pinstance, IntPtr caller_handle);
<summary>this is the important function that would perform the conversion</summary>
<param name= "instance" ></param>
<param name= "ARGC" ></param>
<param name= "argv" ></param>
<returns></returns>
[DllImport ("Gsdll32.dll", entrypoint= "Gsapi_init_with_args")]
private static extern int Gsapi_init_with_args (IntPtr instance, int argc, IntPtr argv);
<summary>
Exit the interpreter. This must is called on shutdown if Gsapi_init_with_args () has been called, and just before Gsapi_delete_instance ().
</summary>
<param name= "instance" ></param>
<returns></returns>
[DllImport ("Gsdll32.dll", entrypoint= "Gsapi_exit")]
private static extern int Gsapi_exit (IntPtr instance);
<summary>
Destroy an instance of Ghostscript. Before this, Ghostscript must have finished. If Ghostscript has been initialised, you are must call Gsapi_exit before.
</summary>
<param name= "instance" ></param>
[DllImport ("Gsdll32.dll", entrypoint= "Gsapi_delete_instance")]
private static extern void Gsapi_delete_instance (IntPtr instance);
#endregion
#region Variables
private string _sdeviceformat;
private int _iwidth;
private int _iheight;
private int _iresolutionx;
private int _iresolutiony;
private int _ijpegquality;
Private Boolean _bfitpage;
Private INTPTR _objhandle;
#endregion
#region Proprieties
public string OutputFormat
{
get {return _sdeviceformat;}
set {_sdeviceformat = value;}
}
public int Width
{
get {return _iwidth;}
set {_iwidth = value;}
}
public int Height
{
get {return _iheight;}
set {_iheight = value;}
}
public int Resolutionx
{
get {return _iresolutionx;}
set {_iresolutionx = value;}
}
public int Resolutiony
{
get {return _iresolutiony;}
set {_iresolutiony = value;}
}
Public Boolean Fitpage
{
get {return _bfitpage;}
set {_bfitpage = value;}
}
<summary>quality of compression of jpg</summary>
public int Jpegquality
{
get {return _ijpegquality;}
set {_ijpegquality = value;}
}
#endregion
#region Init
Public Pdfconvert (IntPtr objhandle)
{
_objhandle = Objhandle;
}
Public Pdfconvert ()
{
_objhandle = IntPtr.Zero;
}
#endregion
Private byte[] Stringtoansiz (String str)
{
' Convert a Unicode string to a null terminated Ansi string for Ghostscript.
' The result is stored in a byte array. Later you'll need to convert
' This byte-array to-a pointer with GCHandle.Alloc (XXXX, gchandletype.pinned)
' and Gshandle.addrofpinnedobject ()
int intelementcount;
int intcounter;
Byte[] Aansi;
BYTE Bchar;
Intelementcount = str. Length;
Aansi = new Byte[intelementcount+1];
for (intcounter = 0; intcounter < intelementcount;intcounter++)
{
Bchar = (byte) str[intcounter];
Aansi[intcounter] = Bchar;
}
Aansi[intelementcount] = 0;
return aansi;
}
<summary>convert the File!</summary>
public void Convert (string inputfile,string outputfile,
int firstpage, int lastpage, string deviceformat, int width, int height)
{
Avoid to work when the file doesn ' t exist
if (! System.IO.File.Exists (Inputfile))
{
System.Windows.Forms.MessageBox.Show (String. Format ("The file: ' {0} ' doesn ' t exist", inputfile));
Return
}
int intreturn;
IntPtr Intgsinstancehandle;
Object[] Aansiargs;
Intptr[] Aptrargs;
Gchandle[] Agchandle;
int intcounter;
int intelementcount;
IntPtr Callerhandle;
GCHandle Gchandleargs;
IntPtr Intptrargs;
string[] Sargs = Getgeneratedargs (Inputfile,outputfile,
FirstPage, LastPage, Deviceformat, width, height);
Convert the Unicode strings to null terminated ANSI byte arrays
Then get pointers to the byte arrays.
Intelementcount = Sargs.length;
Aansiargs = new Object[intelementcount];
Aptrargs = new Intptr[intelementcount];
Agchandle = new Gchandle[intelementcount];
Create a handle for each of the arguments
They ' ve been converted to an ANSI null terminated
String. Then store the pointers for each of the handles
for (intcounter = 0; intcounter< intelementcount; intcounter++)
{
Aansiargs[intcounter] = Stringtoansiz (Sargs[intcounter]);
Agchandle[intcounter] = GCHandle.Alloc (Aansiargs[intcounter], gchandletype.pinned);
Aptrargs[intcounter] = Agchandle[intcounter]. Addrofpinnedobject ();
}
Get a new handle for the array of argument pointers
Gchandleargs = GCHandle.Alloc (Aptrargs, gchandletype.pinned);
Intptrargs = Gchandleargs.addrofpinnedobject ();
Intreturn = Gsapi_new_instance (out intgsinstancehandle, _objhandle);
Callerhandle = IntPtr.Zero;
Try
{
Intreturn = Gsapi_init_with_args (Intgsinstancehandle, Intelementcount, Intptrargs);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show (ex. message);
}
Finally
{
for (intcounter = 0; intcounter < Intreturn; intcounter++)
{
Agchandle[intcounter]. Free ();
}
Gchandleargs.free ();
Gsapi_exit (Intgsinstancehandle);
Gsapi_delete_instance (Intgsinstancehandle);
}
}
Private string[] Getgeneratedargs (String inputfile, String outputfile,
int firstpage, int lastpage, string deviceformat, int width, int height)
{
This._sdeviceformat = Deviceformat;
This._iresolutionx = width;
This._iresolutiony = height;
Count how many extra args are need-hrangel-11/29/2006, 3:13:43 PM
ArrayList Lstextraargs = new ArrayList ();
if (_sdeviceformat== "JPG" && _ijpegquality > 0 && _ijpegquality < 101)
Lstextraargs.add ("-djpegq=" + _ijpegquality);
if (_iwidth > 0 && _iheight > 0)
Lstextraargs.add ("G" + _iwidth + "x" + _iheight);
if (_bfitpage)
Lstextraargs.add ("-dpdffitpage");
if (_iresolutionx > 0)
{
if (_iresolutiony > 0)
Lstextraargs.add ("R" + _iresolutionx + "x" + _iresolutiony);
Else
Lstextraargs.add ("R" + _iresolutionx);
}
Load Fixed args-hrangel-11/29/2006, 3:34:02 PM
int ifixedcount = 17;
int iextraargscount = Lstextraargs.count;
string[] args = new String[ifixedcount + Lstextraargs.count];
/*
Keep GS from writing information to standard output
"-Q",
"-dquiet",
"-dparanoidsafer",//Run This command in Safe mode
"-dbatch",//Keep GS from going to interactive mode
"-dnopause",//does not prompt and pause for each page
"-dnoprompt",//Disable prompts for user interaction
"-dmaxbitmap=500000000",//Set high for better performance
Set the starting and ending pages
String.Format ("-dfirstpage={0}", FirstPage),
String.Format ("-dlastpage={0}", LastPage),
Configure the output anti-aliasing, resolution, etc
"-daligntopixels=0",
"-dgridfittt=0",
"-sdevice=jpeg",
"-dtextalphabits=4",
"-dgraphicsalphabits=4",
*/
Args[0]= "pdf2img";//this parameter have little real use
Args[1]= "-dnopause";//i don ' t want interruptions
Args[2]= "-dbatch";//stop after
Args[3]= "-dsafer";
ARGS[3] = "-dparanoidsafer";
args[4]= "-sdevice=" +_sdeviceformat;//what kind of export format I should provide
ARGS[5] = "-Q";
ARGS[6] = "-dquiet";
ARGS[7] = "-dnoprompt";
ARGS[8] = "-dmaxbitmap=500000000";
ARGS[9] = String.Format ("-dfirstpage={0}", FirstPage);
ARGS[10] = String.Format ("-dlastpage={0}", LastPage);
ARGS[11] = "-daligntopixels=0";
ARGS[12] = "-dgridfittt=0";
ARGS[13] = "-dtextalphabits=4";
ARGS[14] = "-dgraphicsalphabits=4";
For a complete list watch here:
Http://pages.cs.wisc.edu/~ghost/doc/cvs/Devices.htm
Fill the remaining parameters
for (int i=0 i < iextraargscount; i++)
{
Args[15+i] = (string) lstextraargs[i];
}
Fill OutputFile and Inputfile
Args[15 + Iextraargscount] = string. Format ("-soutputfile={0}", outputfile);
Args[16 + Iextraargscount] = string. Format ("{0}", Inputfile);
return args;
}
public void Pdf2jpgtest ()
{
This. Convert (@ "c://tmp//pdfimg//test1.pdf", @ "C://tmp//pdfimg//out.jpg", 1,1, "JPEG", 100,100);
This. Convert (@ "c://tmp//pdfimg//test.pdf", @ "C://tmp//pdfimg//out2.jpg", 291, 291, "JPEG", 800, 800);
}
}
}
Test WinForm:
You can test the functionality above by invoking the following methods, such as:
Copy Code code as follows:
Pdfconvert convertor = new Pdfconvert ();
Convertor.pdf2jpgtest ();
Copy Code code as follows:
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Using Convertpdf;
Namespace Pdf2img
{
public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
}
private void Button1_Click (object sender, EventArgs e)
{
Pdfconvert convertor = new Pdfconvert ();
Convertor.pdf2jpgtest ();
Image img = image.fromfile (@ "c://tmp//pdfimg//out.jpg");
Mybitmap = new Bitmap (IMG);
Graphics G = this. CreateGraphics ();
GraphicsUnit GU = G.pageunit;
Bmpcontainer = Mybitmap.getbounds (ref GU); X,y = 0
Graphics g = this. CreateGraphics ();
G.drawimage (Mybitmap, 1, 1);
This. Invalidate ();
}
Private Bitmap Mybitmap;
Private RectangleF Bmpcontainer;
protected override void OnPaint (PaintEventArgs e)
{
Graphics G = e.graphics;
if (Mybitmap!= null)
{
G.drawimage (Mybitmap, Bmpcontainer);
}
Base. OnPaint (e);
}
}
}