当前位置: 首页 > 工具软件 > Ghostscript > 使用案例 >

PDF转图片 Ghostscript.NET

章阳波
2023-12-01

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

 类似资料: