1.安装
安装:nuget 包:Magick.NET-Q16-AnyCPU
安装:ghostscript .exe
找到 ghostscript .exe 安装目录:
<add key="PdfToImage" value="C:\Program Files\gs\gs9.53.3\bin\" />
2.使用
/// <summary>
/// 将PDF所有页转换为图片并返回图片路径
/// </summary>
/// <param name="pdfPath">pdf文件路径</param>
/// <param name="imgPath">生成图片路径</param>
/// <param name="imgName">图片名称前缀</param>
public static List<string> GetPdfAllPageImgs(string pdfPath, string imgPath, string imgName) {
var list = new List<string>();
MagickNET.SetGhostscriptDirectory(pdfToImage);
MagickReadSettings settings = new MagickReadSettings();
settings.Density = new Density(300, 300); //设置格式
MagickImageCollection images = new MagickImageCollection();
IMagickImage image = null;
try {
images.Read(pdfPath, settings);
if (images.Count > 0) {
image = images[0];
image.Alpha(AlphaOption.Remove);//遇到电子签章的此属性可以解决黑屏问题
image.Format = MagickFormat.Jpeg;
string path = imgPath + $"{imgName}.jpg";//相对路径
image.Write(path);
list.Add(path);
}
} catch (Exception ex) {
LogInfo.WriteLogInfo("PDFUntil", "PCService", "PDF转JPG失败,error:" + ex.ToString());
} finally {
image.Dispose();
images.Dispose();
images.Clear();
}
return list;
}
3.配置
MagickNET.SetGhostscriptDirectory(@"" + ConfigurationManager.AppSettings["PdfToImage"]);