PDF转图片
FreeSpire.Pdf 将PDF转图片
工作中遇到一个需求,要将PDF转成图片保存,就是干!!!然后找了一圈 nuget 包 基本上都是有水印的
在gitee上中到一个 只支持 x86 的 [pdf2image] (https://gitee.com/zendu/pdf2image) ,这个倒是没有水印,但是不能x64,不够完美,作为一个处女座的码农怎么能允许这种事情发生!!
于是继续去nuget继续寻找,终于 找到了 --- FreeSpire.Pdf (https://www.nuget.org/packages/FreeSpire.PDF)
然后代码很简单,直接上
using Spire.Pdf;
public class PdfExtendProvider
{
/// <summary>
/// pdf 文件 转换成图片
/// </summary>
/// <param name="pdfPath">pdf文件所在的物理路径(全路径,如:C:\Users\Administrator\Desktop\1234.pdf )</param>
/// <param name="IsOne">转换的pic是每一页一张图片,还是整个pdf一张图片,默认整个pdf一张图片</param>
/// <param name="picPath">转换的pic存储的物理路径,默认和pdf文件同路径</param>
/// <param name="picName">pic文件名前缀,默认和pdf文件同名</param>
/// <param name="format">转换成图片的格式,默认jpg</param>
/// <param name="picDpiX">图像水平方向上的dpi</param>
/// <param name="picDpiY">图像垂直方向上的dpi</param>
/// <param name="startIndex">pdf文件中要转换的起始页,默认从第一页开始</param>
/// <param name="endIndex">pdf文件中要转换的终止页,默认到最后一页结束</param>
/// <returns></returns>
public Pdf2PicResult ConvertPdf2Pic(string pdfPath, string picPath = "", string picName = "", bool IsOne = true, int startIndex = 1, int endIndex = -1, int picDpiX = 500, int picDpiY = 500)
{
#region ================= 参数验证 ====================
// PDF 路径的正则
string pdfPattern = "^[C-Z]:\\\\([^\\\\?\\/\\*\\|<>:\"]+\\\\)*[^\\\\?\\/\\*\\|<>:\"]+\\.pdf$";
Regex reg = new Regex(pdfPattern, RegexOptions.IgnoreCase);
if (!reg.IsMatch(pdfPath))
{
throw new ArgumentException("pdfPath error");
}
// 文件是否存在
if (!File.Exists(pdfPath))
{
throw new FileNotFoundException(pdfPath + " not found");
}
//打开PDF
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile(pdfPath);
// 文件页数
int pagecount = pdf.Pages.Count;
if (pagecount <= 0)
{
throw new Exception(pdfPath + "pdf file page number must be greater than 0 ");
}
string[] array = pdfPath.Split('\\');
string pdfNameWithExtension = array[array.Length - 1];
// 文件名
if (string.IsNullOrEmpty(picName))
{
picName = pdfNameWithExtension.Split('.')[0];
}
// 存储路径
if (string.IsNullOrEmpty(picPath))
{
picPath = pdfPath.Replace(pdfNameWithExtension, "");
}
string picPattern = @"^[a-zA-Z]:(((\\(?! )[^/:*?<>\""|\\]+)+\\?)|(\\)?)\s*$";
Regex regex = new Regex(picPattern);
if (!regex.IsMatch(picPath) || picPath.Trim().Length <= 0)
{
throw new ArgumentException("picPath error");
}
// x dpi
if (picDpiX <= 0 || picDpiX > 1000)
{
throw new ArgumentException("picDpiX must be between 0 and 1000");
}
// y dpi
if (picDpiY <= 0 || picDpiY > 1000)
{
throw new ArgumentException("picDpiY must be between 0 and 1000");
}
// 起始页
if (startIndex <= 0)
{
throw new ArgumentException("startIndex must be greater than 0 ");
}
// 结束页
if (endIndex == -1)
{
endIndex = pagecount;
}
if (endIndex < startIndex)
{
throw new ArgumentException("endIndex must be greater than startIndex");
}
#endregion
Pdf2PicResult returnResult = new Pdf2PicResult()
{
IsSussess = false,
PicPath = null,
Message = "",
};
try
{
// 配置图片
List<string> picSavePath = new List<string>();
// 生成图片
//遍历PDF每一页
for (int i = 0; i < pagecount; i++)
{
//将PDF页转换成Bitmap图形
Image bmp = pdf.SaveAsImage(i, picDpiX, picDpiY);
//将Bitmap图形保存为Jpg格式的图片
string fileName = string.Format(@"{0}{1}_{2}.jpg", picPath, picName, i + 1);
picSavePath.Add(fileName);
bmp.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
// 整个pdf一张图
if (IsOne)
{
string result = MergePic(picSavePath, picDpiX, picDpiY);
returnResult.PicPath = new List<string>() { result };
}
else
{
returnResult.PicPath = picSavePath;
}
returnResult.IsSussess = true;
}
catch (Exception ex)
{
returnResult.IsSussess = false;
returnResult.Message = ex.Message;
}
return returnResult;
}
private string MergePic(List<string> pathList, int picDpiX, int picDpiY, string picName = "")
{
if (pathList == null || pathList.Count <= 0)
{
throw new ArgumentException("pathList is null or Empty");
}
List<Image> imgList = new List<Image>();
//最大宽度和高度
int maxLength = 0, totalHegiht = 0;
//循环遍历获取文件的最大宽度与总高度
foreach (var item in pathList)
{
if (!File.Exists(item))
{
throw new FileNotFoundException(item + " is not found");
}
Image image = Image.FromStream(new System.IO.MemoryStream(File.ReadAllBytes(item)));
imgList.Add(image);
if (image.Width > maxLength)
{
maxLength = image.Width;
}
totalHegiht += image.Height;
}
if (totalHegiht == 0 || maxLength == 0)
{
throw new ArgumentException("picture is null");
}
Bitmap map = new Bitmap(maxLength, totalHegiht);//定义画布
map.SetResolution(picDpiX, picDpiY);// 设置 dpi
Graphics graphics = Graphics.FromImage(map);//定义画笔
graphics.Clear(Color.White);//把画布更改为白色
int y = 0;//y轴坐标
foreach (var item in imgList)
{
graphics.DrawImage(item, new Point(0, y));
y += item.Height;
}
string savePath = "";
if (string.IsNullOrEmpty(picName))
{
// 也可以用 正则 将‘_*.jpg’ 替换为 ‘.jpg’
var list = pathList[0].Split('\\');
string nameWithExtension = list[list.Length - 1];
savePath = pathList[0].Replace(nameWithExtension, "");
var tempName = nameWithExtension.Split('.')[0];
var picNameArray = tempName.Split('_');
string picNameTemp = "_" + picNameArray[picNameArray.Length - 1];
picName = tempName.Replace(picNameTemp, "");
}
savePath = Path.Combine(savePath, picName + ".jpg");
//把合并的图片进行保存为jpg格式
map.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
return savePath;
}
}
public class Pdf2PicResult
{
/// <summary>
/// pdf每一页转换的图片的物理路径
/// </summary>
public List<string> PicPath { get; set; }
/// <summary>
///
/// </summary>
public string Message { set; get; }
/// <summary>
///
/// </summary>
public bool IsSussess { set; get; }
}
冬日艳阳 夏日清凉 🍃

浙公网安备 33010602011771号