C#: PDF转图片(ghostscript)

用过很多其它的转换方法,大部分都有点小毛病。比如:二维码变成了黑块,汉字变成了乱码,有些还要收费……

后面发现了 Ghostscript 这个好东东,不过需要安装,但是也非常简单,也能用于代码之中。

一、下载 Ghostscript for Windows (64 bit)

官方网站:

https://www.ghostscript.com/download/gsdnld.html

CSDN:

Ghostscript9.26forWindows(64bit)_windows安装ghostscript,windows安装ghostscript-网络基础工具类资源-CSDN下载

二、安装下载好的文件,记录下exe文件安装位置,比如我的是:

D:\Program Files\gs\gs9.26\bin\gswin64.exe

三、相关脚本:

官方参考文档:

How to Use Ghostscript

其它参考文档:

使用ghostscript将pdf转图片_weixin_30782331的博客-CSDN博客

GhostScript命令参数详解_catoop的博客-CSDN博客_ghostscript 命令

四、C# 调用方法:

        /// <summary>
        /// PDF转png
        /// </summary>
        /// <param name="pdfPath"></param>
        /// <param name="pngPath"></param>
        /// <returns></returns>
        public static bool Pdf2Jpg(string pdfPath, string pngPath)
        {
            try
            {
                string gsPath = "D:\\Program Files\\gs\\gs9.26\\bin";
                //方法传入的参数  name   是文件名地址 下面会用到。 
                StringBuilder str = new StringBuilder();
                //引用CMD的东西
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                p.Start();//启动CMD程序
                p.StandardInput.WriteLine("path " + gsPath);    //定位到安装目录下
                p.StandardInput.AutoFlush = true;
                str.AppendFormat(@"gswin64.exe -r600*600 -q -dNOPAUSE -sDEVICE=pngalpha -sOutputFile={0} {1} -c quit", pngPath, pdfPath);
                p.StandardInput.WriteLine(str);//向CMD输出 组装后的str
                p.StandardInput.WriteLine("exit");//结束 不然可能会假死
                string output = p.StandardOutput.ReadToEnd();//读取CMD的返回结果
                Console.WriteLine("CMD界面返回结果\n" + output + "\n");
                p.WaitForExit();//等待程序执行完退出进程
                p.Close();
                return true;
            }
            catch (Exception ex)
            {
                //日志记录异常
                return false;
            }
        }

---------------------------- 后记 -------------------------------

后面发现:发票 pdf 转图片,图章上的中文错位。

处理方法,下载:

ghostscript 8.6.1 完美版

注意:安装时下面两个地方都要打上勾。不安装字体就会有问题。

 

C#代码里的路径对应改一下就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值