网络上找了一堆博文,实验之后基本上很少能够有用的,很少能提供完整的Demo和Method,故写本篇文章来做记录。
1、新建项目UnitTestProject
2、右击项目==>>管理Nuget程序包==>Magick.NET-Q16-AnyCPU 安装最新版本7.14.5
注: Q8 Q16 指HDRI分别表示8位 和16位,AnyCPU、x64、x86 指计算机是32位还是64位系统,选择AnyCPU
3、下载安装ghostscript(根据所在服务器下载对应32还是64位版本)
http://ghostscript.com/download/gsdnld.html
如果不安装ghostscript,magick.net在执行Read函数读取pdf时会报错误.
4、加入以下方法,并添加引用 using ImageMagick;
/// <summary>
/// 将PDF所有页转换为图片并返回图片路径
/// </summary>
/// <param name="pdfPath">pdf文件路径</param>
/// <param name="imgPath">生成图片路径</param>
/// <param name="imgName">图片名称前缀</param>
public List<string> GetPdfAllPageImgs(string pdfPath, string imgPath, string imgName)
{
var list = new List<string>();
try
{
MagickReadSettings settings = new MagickReadSettings();
settings.Density = new Density(72, 72); //设置格式
using (MagickImageCollection images = new MagickImageCollection())
{
images.Read(pdfPath, settings);
int pageCount = images.Count;
for (int i = 0; i < pageCount; i++)
{
IMagickImage image = images[i];
image.Alpha(AlphaOption.Remove);//遇到电子签章的此属性可以解决黑屏问题
image.Format = MagickFormat.Jpeg;
string path = imgPath + $"{imgName}_{i}.jpg";//相对路径
image.Write(path);
list.Add(path);
}
}
}
catch (Exception ex)
{
}
return list;
}
5、在TestMethod方法中调用测试
[TestMethod]
public void TestMethod()
{
try
{
string filepath = @"D:\PDFFF\1565265812212742552810.pdf";
string imgpath = @"D:/PDFFF/";
var pathList= PdfHelper.GetPdfAllPageImgs(filepath, imgpath, "imgName");
}
catch (Exception ex)
{
}
}
6、右击TestMethod方法==>调试测试(注意打上断点)
请根据自己需要进行函数改写,本文只是示例,加入文件存储到云、文件检测等等
Demo地址(CSDN好像不可以设置免费下载了。。。有点不清真啊)
https://download.csdn.net/download/uianqian/11926634