C# pdf 文件转图片
直接贴代码,代码借鉴别人的修改的:
using O2S.Components.PDFRender4NET; using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace eService.Code { public static class Pdf2Pic { public enum Definition { One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10 } /// <summary> /// 将PDF文档转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageOutputPath">图片输出路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); pageImage.Save(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat); pageImage.Dispose(); } pdfFile.Dispose(); } /// <summary> /// pdf转图片 /// </summary> /// <param name="pdfInputPath">输入pdf文件</param> /// <param name="imageOutputPath">输出文件夹</param> /// <param name="imageName">图片名称</param> /// <param name="imageFormat">图片格式</param> /// <returns>图片完整路径</returns> public static string ConvertPDFToImage(string pdfInputPath, string imageOutputPath, string imageName, ImageFormat imageFormat) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } Bitmap pageImage = pdfFile.GetPageImage(0, 56 * (int)Definition.Ten); string imagePath = imageOutputPath + imageName + "." + imageFormat.ToString(); pageImage.Save(imagePath, imageFormat); pdfFile.Dispose(); return imagePath; } } }
调用代码:
string imagePath= Pdf2Pic.ConvertPDFToImage(pdfPath, HttpContext.Current.Server.MapPath(ReportFile)+"\\", Common.GuId(), ImageFormat.Jpeg);