pdf文件显示

由于项目需要在.net下将pdf转换为普通图像格式,在网上搜了好久终于找到一个解决方案,于是采用拿来主义直接用。来源见代码中注释,感谢原作者。

 

 

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Runtime.InteropServices;  
  5. using System.Collections;  
  6. /** 
  7. Convert PDF to Image Format(JPEG) using Ghostscript API 
  8.   
  9. convert a pdf to jpeg using ghostscript command line: 
  10. 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 
  11. see also:http://www.mattephraim.com/blog/2009/01/06/a-simple-c-wrapper-for-ghostscript/ 
  12. and: http://www.codeproject.com/KB/cs/GhostScriptUseWithCSharp.aspx 
  13. Note:copy gsdll32.dll to system32 directory before using this ghostscript wrapper. 
  14.  *  
  15.  */  
  16. namespace ConvertPDF  
  17. {  
  18.     /// <summary>  
  19.     ///   
  20.     /// Class to convert a pdf to an image using GhostScript DLL  
  21.     /// Credit for this code go to:Rangel Avulso  
  22.     /// i only fix a little bug and refactor a little  
  23.     /// http://www.hrangel.com.br/index.php/2006/12/04/converter-pdf-para-imagem-jpeg-em-c/  
  24.     /// </summary>  
  25.     /// <seealso cref="http://www.hrangel.com.br/index.php/2006/12/04/converter-pdf-para-imagem-jpeg-em-c/"/>  
  26.     class PDFConvert  
  27.     {  
  28.         #region GhostScript Import  
  29.         /// <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.  
  30.         ///  At this stage, Ghostscript supports only one instance. </summary>  
  31.         /// <param name="pinstance"></param>  
  32.         /// <param name="caller_handle"></param>  
  33.         /// <returns></returns>  
  34.         [DllImport("gsdll32.dll", EntryPoint="gsapi_new_instance")]  
  35.         private static extern int gsapi_new_instance (out IntPtr pinstance, IntPtr caller_handle);  
  36.         /// <summary>This is the important function that will perform the conversion</summary>  
  37.         /// <param name="instance"></param>  
  38.         /// <param name="argc"></param>  
  39.         /// <param name="argv"></param>  
  40.         /// <returns></returns>  
  41.         [DllImport("gsdll32.dll", EntryPoint="gsapi_init_with_args")]  
  42.         private static extern int gsapi_init_with_args (IntPtr instance, int argc, IntPtr argv);  
  43.         /// <summary>  
  44.         /// Exit the interpreter. This must be called on shutdown if gsapi_init_with_args() has been called, and just before gsapi_delete_instance().   
  45.         /// </summary>  
  46.         /// <param name="instance"></param>  
  47.         /// <returns></returns>  
  48.         [DllImport("gsdll32.dll", EntryPoint="gsapi_exit")]  
  49.         private static extern int gsapi_exit (IntPtr instance);  
  50.         /// <summary>  
  51.         /// 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.   
  52.         /// </summary>  
  53.         /// <param name="instance"></param>  
  54.         [DllImport("gsdll32.dll", EntryPoint="gsapi_delete_instance")]  
  55.         private static extern void gsapi_delete_instance (IntPtr instance);  
  56.         #endregion  
  57.         #region Variables  
  58.         private string _sDeviceFormat;  
  59.         private int _iWidth;  
  60.         private int _iHeight;  
  61.         private int _iResolutionX;  
  62.         private int _iResolutionY;  
  63.         private int _iJPEGQuality;  
  64.         private Boolean _bFitPage;  
  65.         private IntPtr _objHandle;  
  66.         #endregion  
  67.         #region Proprieties  
  68.         public string OutputFormat  
  69.         {  
  70.             get { return _sDeviceFormat; }  
  71.             set { _sDeviceFormat = value; }  
  72.         }  
  73.         public int Width  
  74.         {  
  75.             get { return _iWidth; }  
  76.             set { _iWidth = value; }  
  77.         }  
  78.         public int Height  
  79.         {  
  80.             get { return _iHeight; }  
  81.             set { _iHeight = value; }  
  82.         }  
  83.         public int ResolutionX  
  84.         {  
  85.             get { return _iResolutionX; }  
  86.             set { _iResolutionX = value; }  
  87.         }  
  88.         public int ResolutionY  
  89.         {  
  90.             get { return _iResolutionY; }  
  91.             set { _iResolutionY = value; }  
  92.         }  
  93.         public Boolean FitPage  
  94.         {  
  95.             get { return _bFitPage; }  
  96.             set { _bFitPage = value; }  
  97.         }  
  98.         /// <summary>Quality of compression of JPG</summary>  
  99.         public int JPEGQuality  
  100.         {  
  101.             get { return _iJPEGQuality; }  
  102.             set { _iJPEGQuality = value; }  
  103.         }  
  104.         #endregion  
  105.         #region Init  
  106.         public PDFConvert(IntPtr objHandle)  
  107.         {  
  108.             _objHandle = objHandle;  
  109.         }  
  110.         public PDFConvert()  
  111.         {  
  112.             _objHandle = IntPtr.Zero;  
  113.         }  
  114.         #endregion  
  115.         private byte[] StringToAnsiZ(string str)  
  116.         {  
  117.             //' Convert a Unicode string to a null terminated Ansi string for Ghostscript.  
  118.             //' The result is stored in a byte array. Later you will need to convert  
  119.             //' this byte array to a pointer with GCHandle.Alloc(XXXX, GCHandleType.Pinned)  
  120.             //' and GSHandle.AddrOfPinnedObject()  
  121.             int intElementCount;  
  122.             int intCounter;  
  123.             byte[] aAnsi;  
  124.             byte bChar;  
  125.             intElementCount = str.Length;  
  126.             aAnsi = new byte[intElementCount+1];  
  127.             for(intCounter = 0; intCounter < intElementCount;intCounter++)  
  128.             {  
  129.                 bChar = (byte)str[intCounter];  
  130.                 aAnsi[intCounter] = bChar;  
  131.             }  
  132.             aAnsi[intElementCount] = 0;  
  133.             return aAnsi;  
  134.         }  
  135.         /// <summary>Convert the file!</summary>  
  136.         public void Convert(string inputFile,string outputFile,  
  137.             int firstPage, int lastPage, string deviceFormat, int width, int height)  
  138.         {  
  139.             //Avoid to work when the file doesn't exist  
  140.             if (!System.IO.File.Exists(inputFile))  
  141.             {  
  142.                 System.Windows.Forms.MessageBox.Show(string.Format("The file :'{0}' doesn't exist",inputFile));  
  143.                 return;  
  144.             }  
  145.             int intReturn;  
  146.             IntPtr intGSInstanceHandle;  
  147.             object[] aAnsiArgs;  
  148.             IntPtr[] aPtrArgs;  
  149.             GCHandle[] aGCHandle;  
  150.             int intCounter;  
  151.             int intElementCount;  
  152.             IntPtr callerHandle;  
  153.             GCHandle gchandleArgs;  
  154.             IntPtr intptrArgs;  
  155.             string[] sArgs = GetGeneratedArgs(inputFile,outputFile,  
  156.                 firstPage, lastPage, deviceFormat, width, height);  
  157.             // Convert the Unicode strings to null terminated ANSI byte arrays  
  158.             // then get pointers to the byte arrays.  
  159.             intElementCount = sArgs.Length;  
  160.             aAnsiArgs = new object[intElementCount];  
  161.             aPtrArgs = new IntPtr[intElementCount];  
  162.             aGCHandle = new GCHandle[intElementCount];  
  163.             // Create a handle for each of the arguments after   
  164.             // they've been converted to an ANSI null terminated  
  165.             // string. Then store the pointers for each of the handles  
  166.             for(intCounter = 0; intCounter< intElementCount; intCounter++)  
  167.             {  
  168.                 aAnsiArgs[intCounter] = StringToAnsiZ(sArgs[intCounter]);  
  169.                 aGCHandle[intCounter] = GCHandle.Alloc(aAnsiArgs[intCounter], GCHandleType.Pinned);  
  170.                 aPtrArgs[intCounter] = aGCHandle[intCounter].AddrOfPinnedObject();  
  171.             }  
  172.             // Get a new handle for the array of argument pointers  
  173.             gchandleArgs = GCHandle.Alloc(aPtrArgs, GCHandleType.Pinned);  
  174.             intptrArgs = gchandleArgs.AddrOfPinnedObject();  
  175.             intReturn = gsapi_new_instance(out intGSInstanceHandle, _objHandle);  
  176.             callerHandle = IntPtr.Zero;  
  177.             try  
  178.             {  
  179.                 intReturn = gsapi_init_with_args(intGSInstanceHandle, intElementCount, intptrArgs);  
  180.             }  
  181.             catch (Exception ex)  
  182.             {  
  183.                 //System.Windows.Forms.MessageBox.Show(ex.Message);  
  184.                   
  185.             }  
  186.             finally  
  187.             {  
  188.                 for (intCounter = 0; intCounter < intReturn; intCounter++)  
  189.                 {  
  190.                     aGCHandle[intCounter].Free();  
  191.                 }  
  192.                 gchandleArgs.Free();  
  193.                 gsapi_exit(intGSInstanceHandle);  
  194.                 gsapi_delete_instance(intGSInstanceHandle);  
  195.             }  
  196.         }  
  197.         private string[] GetGeneratedArgs(string inputFile, string outputFile,  
  198.             int firstPage, int lastPage, string deviceFormat, int width, int height)  
  199.         {  
  200.             this._sDeviceFormat = deviceFormat;  
  201.             this._iResolutionX = width;  
  202.             this._iResolutionY = height;  
  203.             // Count how many extra args are need - HRangel - 11/29/2006, 3:13:43 PM  
  204.             ArrayList lstExtraArgs = new ArrayList();  
  205.             if ( _sDeviceFormat=="jpg" && _iJPEGQuality > 0 && _iJPEGQuality < 101)  
  206.                 lstExtraArgs.Add("-dJPEGQ=" + _iJPEGQuality);  
  207.             if (_iWidth > 0 && _iHeight > 0)  
  208.                 lstExtraArgs.Add("-g" + _iWidth + "x" + _iHeight);  
  209.             if (_bFitPage)  
  210.                 lstExtraArgs.Add("-dPDFFitPage");  
  211.             if (_iResolutionX > 0)  
  212.             {  
  213.                 if (_iResolutionY > 0)  
  214.                     lstExtraArgs.Add("-r" + _iResolutionX + "x" + _iResolutionY);  
  215.                 else  
  216.                     lstExtraArgs.Add("-r" + _iResolutionX);  
  217.             }  
  218.             // Load Fixed Args - HRangel - 11/29/2006, 3:34:02 PM  
  219.             int iFixedCount = 17;  
  220.             int iExtraArgsCount = lstExtraArgs.Count;  
  221.             string[] args = new string[iFixedCount + lstExtraArgs.Count];  
  222.             /* 
  223.             // Keep gs from writing information to standard output 
  224.         "-q",                      
  225.         "-dQUIET", 
  226.         
  227.         "-dPARANOIDSAFER", // Run this command in safe mode 
  228.         "-dBATCH", // Keep gs from going into interactive mode 
  229.         "-dNOPAUSE", // Do not prompt and pause for each page 
  230.         "-dNOPROMPT", // Disable prompts for user interaction            
  231.         "-dMaxBitmap=500000000", // Set high for better performance 
  232.          
  233.         // Set the starting and ending pages 
  234.         String.Format("-dFirstPage={0}", firstPage), 
  235.         String.Format("-dLastPage={0}", lastPage),    
  236.          
  237.         // Configure the output anti-aliasing, resolution, etc 
  238.         "-dAlignToPixels=0", 
  239.         "-dGridFitTT=0", 
  240.         "-sDEVICE=jpeg", 
  241.         "-dTextAlphaBits=4", 
  242.         "-dGraphicsAlphaBits=4", 
  243.             */  
  244.             args[0]="pdf2img";//this parameter have little real use  
  245.             args[1]="-dNOPAUSE";//I don't want interruptions  
  246.             args[2]="-dBATCH";//stop after  
  247.             //args[3]="-dSAFER";  
  248.             args[3] = "-dPARANOIDSAFER";  
  249.             args[4]="-sDEVICE="+_sDeviceFormat;//what kind of export format i should provide  
  250.             args[5] = "-q";  
  251.             args[6] = "-dQUIET";  
  252.             args[7] = "-dNOPROMPT";  
  253.             args[8] = "-dMaxBitmap=500000000";  
  254.             args[9] = String.Format("-dFirstPage={0}", firstPage);  
  255.             args[10] = String.Format("-dLastPage={0}", lastPage);  
  256.             args[11] = "-dAlignToPixels=0";  
  257.             args[12] = "-dGridFitTT=0";  
  258.             args[13] = "-dTextAlphaBits=4";  
  259.             args[14] = "-dGraphicsAlphaBits=4";  
  260.             //For a complete list watch here:  
  261.             //http://pages.cs.wisc.edu/~ghost/doc/cvs/Devices.htm  
  262.             //Fill the remaining parameters  
  263.             for (int i=0; i < iExtraArgsCount; i++)  
  264.             {  
  265.                 args[15+i] = (string) lstExtraArgs[i];  
  266.             }  
  267.             //Fill outputfile and inputfile  
  268.             args[15 + iExtraArgsCount] = string.Format("-sOutputFile={0}",outputFile);  
  269.             args[16 + iExtraArgsCount] = string.Format("{0}",inputFile);  
  270.             return args;  
  271.         }  
  272.         public void pdf2jpgTest()  
  273.         {              
  274.             this.Convert(@"C://tmp//pdfimg//test1.pdf",@"C://tmp//pdfimg//out.jpg",1,1,"jpeg",100,100);  
  275.             //this.Convert(@"C://tmp//pdfimg//test.pdf", @"C://tmp//pdfimg//out2.jpg", 291, 291, "jpeg", 800, 800);  
  276.         }  
  277.     }  
  278. }  

 

 

测试WinForm:

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

 PDFConvert convertor = new PDFConvert();
 convertor.pdf2jpgTest();

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using ConvertPDF;  
  10. namespace PDF2Img  
  11. {  
  12.     public partial class Form1 : Form  
  13.     {  
  14.         public Form1()  
  15.         {  
  16.             InitializeComponent();  
  17.               
  18.         }  
  19.         private void button1_Click(object sender, EventArgs e)  
  20.         {  
  21.             PDFConvert convertor = new PDFConvert();  
  22.             convertor.pdf2jpgTest();  
  23.             Image img = Image.FromFile(@"C://tmp//pdfimg//out.jpg");  
  24.             myBitmap = new Bitmap(img);  
  25.   
  26.             Graphics G = this.CreateGraphics();  
  27.             GraphicsUnit GU = G.PageUnit;  
  28.             BMPContainer = myBitmap.GetBounds(ref GU); //X,Y = 0  
  29.   
  30.            // Graphics g = this.CreateGraphics();  
  31.             //g.DrawImage(myBitmap, 1, 1);  
  32.             this.Invalidate();  
  33.         }  
  34.         private Bitmap myBitmap;  
  35.         private RectangleF BMPContainer;  
  36.         protected override void OnPaint(PaintEventArgs e)  
  37.         {  
  38.             Graphics G = e.Graphics;  
  39.             if (myBitmap != null)  
  40.             {             
  41.                 G.DrawImage(myBitmap, BMPContainer);  
  42.             }  
  43.             base.OnPaint(e);  
  44.         }  
  45.     }  
  46. }  

posted @ 2014-03-21 17:04  雨中的阳光  阅读(786)  评论(2编辑  收藏  举报