用Ghostscript API将PDF格式转换为图像格式(C#)
原文:用Ghostscript API将PDF格式转换为图像格式(C#)

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

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

posted on 2014-03-23 13:30 NET未来之路 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/3618964.html

用Ghostscript API将PDF格式转换为图像格式(C#)相关推荐

  1. 如何将PDF格式转换为WORD文档

    经常在PDF形式上看到有好的文件时,想把它拿出来,但是却是不行,所以我第一步就是找一下有没有可以到PDF格式与WORD文档的转换,在网上找了一下,原来还真的有很多,今天我就把这些方法也传上来,不过我也 ...

  2. 图文教你把PDF格式转换为CAD格式

    我还是一个爱岗经验的好员工,生活中都要分担时间去搞好工作上的事情.我们如何好好的进行工作上这麻烦的事情呢. 在我的工作单位中,对图纸的编辑.批注.修改以及文件格式的转换过程中,我的效率明显比同事的高. ...

  3. PDF格式转换为WORD格式

    Solid Converter PDF 3.0 Build 275 [url]http://nj.onlinedown.net/soft/37438.htm[/url] <?xml:namesp ...

  4. 简要介绍word文档转换为pdf格式文档的工具

    找了很多工具,其实都是乱七八糟的,没几个好用的,最好还是用Adobe Acrobat Pro吧,这个就很方便了,而且转换的也不错. ABC Amber PDF Converter ABC Amber ...

  5. 如何在 Linux 中使用 Calibre 将 PDF 文件转换为 EPUB 格式?

    在这个现代时代,一切都被数字化了,电子书已成为主流,电子书有多种格式,如 PDF.EPUB.MOBI.AZW3 和 IBA 等. 大多数电子书阅读器支持几乎所有格式,但是,某些电子书阅读器可能不支持特 ...

  6. pdf格式怎么转jpg格式?非常简单方便的方法分享给你!

    PDF是我们在办公中经常使用的文件格式之一,它不仅能够保存图像.文字和数据等多种元素,而且具有可读性强.易于打印.传输和存储等优点.然而,PDF文件相对于其他文件格式来说,占用内存较大.因此,如果能够 ...

  7. 将PDF和Gutenberg文档格式转换为文本:生产中的自然语言处理

    Estimates state that 70%–85% of the world's data is text (unstructured data). Most of the English an ...

  8. Office文档上传后实时转换为PDF格式_图片文件上传后实时裁剪_实现在线预览Office文档

    Office文档上传后实时转换为PDF格式_图片文件上传后实时裁剪 前置条件 安装LibreOffice 安装OpenOffice 安装Unoconv 安装ImageMagick.x86_64 安装G ...

  9. 将PDF文件转换为JPG格式图片的3种简单方法

    如何在线将PDF文件转换成图片格式?如果您在使用PDF文件时只需要其中一页或几页的内容,将PDF转换为图片可以使您更方便地使用这些内容.下面介绍三种简单易用的PDF转图片的方法. 方法一:记灵在线工具 ...

最新文章

  1. java 详解 搭建 框架_maven 基本框架搭建详解
  2. ASP.NET 发邮件方法
  3. 人脸对齐--Face Alignment by Explicit Shape Regression
  4. 上周热点回顾(9.7-9.13)
  5. 科大星云诗社动态20210415
  6. vue 版本发布 在线跟新用户操作解决方案_Vue3.0正式发布,本次发布所有总结,一起看看!【附在线视频】...
  7. 开放科学背景下的科学数据开放共享:国家青藏高原科学数据中心的实践
  8. 是否担心别人将你的博客文章全部爬下来?3行代码教你检测爬虫
  9. 【高并发】java JUC中的Semaphore(信号量)
  10. Windows Mina 2.0.7 环境搭建
  11. 转 TCP中的序号和确认号
  12. OOP,Object Oriented Programming 面向对象的三大特性 五大基本原则
  13. 20000条笑话保证笑死你
  14. SSH连接服务器断开
  15. flutter编译遇到unknown revision or path not in the working tree的错误
  16. 2021:不要在一件事上纠缠太久!
  17. 想破解游戏协议?你知道客户端和服务器是怎么通信的?我来告诉你怎么定义的
  18. C++ opencv之像素值统计(minMaxLoc,meanStdDev)
  19. 生活随记 - 立冬 暖阳高照
  20. C++学习第一天(初步认识-程序流的分支-循环-数据类型)

热门文章

  1. 【linux家常菜】redhat 6.5 安装yum
  2. 斯特林公式(Stirling's approximation)
  3. [以太坊源代码分析] I.区块和交易,合约和虚拟机
  4. 以太坊geth结构解析和源码分析
  5. Android6.0 keyguard锁屏加载流程分析
  6. Android源码分析--MediaServer源码分析(二)
  7. Android Binder 分析——数据传递者(Parcel)
  8. ARM64的启动过程之(二):创建启动阶段的页表
  9. asp.net html table,在ASP.NET中利用HtmlTable动态创建表格 | 学步园
  10. java和node.js 2018_2018,Node.js社区最值得关注的三个话题