C# PDF 转成图片利用GhostScript

如何把pdf文件的每一页都转成一个图片呢?首先说一下GhostScript这个软件。

Ghostscript是一套建基于Adobe、PostScript及可移植文档格式(PDF)的页面描述语言等而编译成的免费软件。详情请参考

百度百科:“http://baike.baidu.com/link?url=S1cISfrHO3F3K19xOKSmB10Vt3K4h02yS9fJH8zm27A2vIqEvtNVIlyi3AvoATv_”

Ghostscript官网:“http://www.ghostscript.com/

参考资料:http://www.ghostscript.com/doc/current/Use.htm

使用方法:

Ghostscript使用方法很简单。我用的是gs906w32这个版本。点击安装即可。

  /// <summary>
        /// PDF转成图片
        /// </summary>
        /// <param name="pdfFile">PDF文件路径</param>
        /// <param name="imgPath">图片输出路径</param>
        /// <returns>图片数量</returns>
        public static int PDFToImg(string pdfFile, string imgPath)
        {
            PDFFile doc = PDFFile.Open(pdfFile);
            int pageCount = doc.PageCount;
            string pdfFileName = Path.GetFileName(pdfFile);

            string imgFile = Path.Combine(imgPath, "page");//转换成的图片文件

            if (pageCount == 0) return 0;
            if (pageCount == 1)
            {
                imgFile += ".jpg";
                if (File.Exists(imgFile))
                {
                    File.Delete(imgFile);
                }
            }
            else
            {
                //检查是否存在相同名称的图片文件
                for (int i = 0; i < pageCount; i++)
                {
                    string _imgFile = imgFile + (i).ToString() + ".jpg";
                    if (File.Exists(_imgFile))
                    {
                        File.Delete(_imgFile);
                    }
                }
                imgFile += "%d.jpg";
            }
            //启动一个新的进程。传入转换参数
            Process prc = new Process();
            prc.StartInfo.UseShellExecute = false;
            prc.StartInfo.CreateNoWindow = true;
            prc.EnableRaisingEvents = true;
            prc.Exited += new EventHandler(prc_Exited);
            //-r150 图片质量,数字越大越清晰,sDEVICE=png 转换的图片格式,imgFile 图片输出路径(含文件名),pdfFile pdf文件地址
            prc.StartInfo.Arguments = "-dSAFER -dBATCH -dNOPAUSE -r150 -sDEVICE=jpeg -dGraphicsAlphaBits=4" + @" -sOutputFile=" + imgFile + "  " + pdfFile;

            //这里是gswin32.exe文件的路径。请按照安装路径查找
            prc.StartInfo.FileName = @"C:Program Filesgsgs9.06ingswin32.exe";
            prc.Start();
            return pageCount;
        }

但是里有一个问题。那就是没转换玩一个都会提示你“转换成功”。解决办法,就是使用user32.dll。根据提示窗口名称,抓取桌面的提示对话框。获得该对话框后,使确定按钮获取焦点然后,根据sendKey 模拟敲击回车。

如果谁有好的办法,希望留言告知 谢谢 嘿嘿

原文地址:https://www.cnblogs.com/ywtk/p/3291034.html