欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

pdf转换成jpg示例分享

程序员文章站 2024-02-23 16:13:52
复制代码 代码如下:using system;  using system.collections.generic;  using system.tex...

复制代码 代码如下:

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
see 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 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 is passed to most other gsapi functions. the caller_handle will be provided to callback functions. 
        ///  at this stage, ghostscript supports 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 will 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 be 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 you call this, ghostscript must have finished. if ghostscript has been initialised, you must call gsapi_exit before gsapi_delete_instance.  
        /// </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 will 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 after  
            // 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 into interactive mode
        "-dnopause", // do 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); 
        } 
    } 

测试winform:

可以采用下面的方式测试调用上面的功能,如:

复制代码 代码如下:

 pdfconvert convertor = new pdfconvert();
 convertor.pdf2jpgtest();
 

复制代码 代码如下:

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); 
        } 
    } 
}