PDF转图片 Ghostscript.NET

通过Ghostscript.NET在本地进行PDF转图片操作时遇到异常,但在服务器上正常。问题在于当PDF文件名包含中文时,会出现异常。优化代码以解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PDF转图片 Ghostscript.NET

public static void ConvertPdf2Img(string input, string outputPath, ref List<string> output, ref string status)
{
    GhostscriptJpegDevice dev = new GhostscriptJpegDevice();
    output = new List<string>();
    try
    {
        using (GhostscriptRasterizer ra = new GhostscriptRasterizer())
        {
            ra.Open(input);
            var cnt = ra.PageCount;
            for (int pageNumber = 1; pageNumber <= cnt; pageNumber++)
            {
                var pageFilePath = Path.Combine(outputPath, Guid.NewGuid().ToString() + ".jpg");
                var img = ra.GetPage(300, 300, pageNumber);

                img.Save(pageFilePath, ImageFormat.Jpeg);
                output.Add(pageFilePath);
                img.Dispose();
            }
        }
    }
    catch (Exception ex)
    {
        status = ex.Message;
        dev = null/* TODO Change to default(_) if this is not a reference type */;
    }
}

List<Image> img = new List<Image>();
    foreach (string str in fileList)
        img.Add(Image.FromFile(str));

本地运行报错,服务器上不报错,将代码优化一下

//gsdll64.dll拷贝到项目版本
var _lastInstalledVersion = new GhostscriptVersionInfo($"{System.Environment.CurrentDirectory}\\gsdll64.dll");
_rasterizer.Open(inputPdfPath, _lastInstalledVersion, false);

测试时发现PDF文件名是包含中文时,会抛出异常

// PDF转IMG时文件名包含中文
if(Regex.IsMatch(Path.GetFileName(fileName), @"[\u4e00-\u9fa5]"))
{
	newFilePath = Path.Combine(Path.GetDirectoryName(filePath), Guid.NewGuid().ToString & Path.GetExtension(filePath));
   File.Copy(oldfilePath, newFilePath);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值