PPT转图片解决方案
使用Aspose组件转换图片
使用Aspose组件的好处是,不需要用户的机器上安装Office,也可以完成我们想要的功能。这个优势实在是太明显了,所以,我最终选折了这个方案。而且,Aspose完全支持word、ppt、和pdf,甚至excel也没问题。
首先我们要准备好Aspose的dll 引用到我们项目中,这里是下载链接: https://pan.baidu.com/s/11gMa_G05KvQSSrq31Db2Kw
下面的代码就摘自示范Demo中。
上传文件js,Form表单提交代码:
//保存上传的课件 function Save() { if ($("#txtTitle").val() == "") { layer.msg('课件名称不能为空', function () { }); return; } if ($("#upfile").val() == "") { layer.msg('上传文件不能为空', function () { }); return; } if ($("#iid").val()==0) { layer.msg('关联章节课程不能为空', function () { }); return; } $('#form-horizontalid').ajaxSubmit({ url: "/Resources_Add/Upload", type: "POST", dataType: "json", data: $('#form-horizontalid').serialize(), beforeSend: function (xhr, self) { var index = layer.load(0, { shade: false }); //0代表加载的风格,支持0-2 if ($("#WaitingUp").html() != "") { $("#WaitingUp").html("(正在上传)"); } if ($("#WaitingUp_img").html() != "") { $("#WaitingUp_img").html("(正在上传)"); } }, success: function (data) { layer.closeAll(); if (data == "-1") { layer.msg('上传文件格式错误', function () { }); return; } if (data > 0) { if (data == "888") { layer.msg('PPT文件异常,请检查文件!', { icon: 2 }); return; } if (data == "999") { layer.msg('课件名称已存在', function () { }); } else if (data == "0") { layer.msg('操作失败', { icon: 2 }); } else { layer.msg('操作成功!', { icon: 1 }); if ($("#WaitingUp").html() != "") { $("#WaitingUp").html("(上传成功)"); } if ($("#WaitingUp_img").html() != "") { $("#WaitingUp_img").html("(上传成功)"); } setTimeout("window.location.href = '/Admin/Resources'", 1000); } return; } else { layer.msg('操作失败', { icon: 2 }); return; } }, error: function (data) { layer.closeAll(); layer.msg('上传文件异常!', { icon: 2 }); } }); }
#region 1.0上传文件时调用转换图片的方法 public string Upload() { double FileSize = 0; string imgName = string.Empty; string imgUrl = "/img/Map"; //课程id string Curriculumid = Request["Curriculumid"]; //章id string Chapterid = Request["Chapterid"]; //课程节id string SectionId = Request["iid"]; string url = string.Empty; string filePath = string.Empty; string CourseName = Request["txtTitle"]; HttpPostedFileBase hpFile = Request.Files["upfile"]; //1.0判断文件是否为空 if (hpFile != null) { //1.1获取文件后缀名 string FileType = System.IO.Path.GetExtension(hpFile.FileName); //1.2获取路径 string FileName = Path.GetFileName(hpFile.FileName).Replace(FileType, "").Replace(".", "") + FileType; url = ResourceConversionURL(FileName); filePath = Server.MapPath(url); hpFile.SaveAs(filePath); //获取文件大小 System.IO.FileInfo fileinfo = new System.IO.FileInfo(Server.MapPath(url)); FileSize = System.Math.Ceiling(fileinfo.Length/1024.0);
//这里在执行转换图片的时候需要调用Aspose类 LicenseHelper.ModifyInMemory.ActivateMemoryPatching(); if (FileType == ".pptx" || FileType == ".ppt") { PictureConversion pc = new PictureConversion(); imgName = pc.ConvertToImage_PPT(filePath, Server.MapPath(imgUrl), 0, 0, 145, FileType, imgUrl); if (imgName=="888") { return "888"; } if (imgName != "" || imgName != null) { int i = 0; i = Add(Curriculumid, Chapterid, SectionId, CourseName, FileType, imgName); if (i > 0) { return "1"; } else if (i==-2) { return "999"; } else { return "0"; } } } else if (FileType == ".mp4") { if (FileSize>0) { int i = 0; i = Add(Curriculumid, Chapterid, SectionId, CourseName, FileType, url); if (i > 0) { return "1"; } else if (i == -2) { return "999"; } else { return "0"; } } } else { return "-1"; } } return ""; } #endregion
ModifyInMemory类代码:
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Xml; namespace LicenseHelper { public static class ModifyInMemory { private static string AsposeList = "Aspose.3D.dll, Aspose.BarCode.dll, Aspose.BarCode.Compact.dll, Aspose.BarCode.WPF.dll, Aspose.Cells.GridDesktop.dll, Aspose.Cells.GridWeb.dll, Aspose.CAD.dll, Aspose.Cells.dll, Aspose.Diagram.dll, Aspose.Email.dll, Aspose.Imaging.dll, Aspose.Note.dll, Aspose.OCR.dll, Aspose.Pdf.dll, Aspose.Slides.dll, Aspose.Tasks.dll, Aspose.Words.dll"; public static void ActivateMemoryPatching() { Assembly[] arr = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in arr) { if (AsposeList.IndexOf(assembly.FullName.Split(',')[0] + ".dll") != -1) ActivateForAssembly(assembly); } AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(ActivateOnLoad); } private static void ActivateOnLoad(object sender, AssemblyLoadEventArgs e) { if (AsposeList.IndexOf(e.LoadedAssembly.FullName.Split(',')[0] + ".dll") != -1) ActivateForAssembly(e.LoadedAssembly); } private static void ActivateForAssembly(Assembly assembly) { MethodInfo miLicensed1 = typeof(ModifyInMemory).GetMethod("InvokeMe1", BindingFlags.NonPublic | BindingFlags.Static); MethodInfo miLicensed2 = typeof(ModifyInMemory).GetMethod("InvokeMe2", BindingFlags.NonPublic | BindingFlags.Static); MethodInfo miEvaluation = null; Dictionary<string, MethodInfo> miDict = new Dictionary<string, MethodInfo>() { {"System.DateTime" , miLicensed1}, {"System.Xml.XmlElement", miLicensed2} }; Type[] arrType = null; bool isFound = false; int nCount = 0; try { arrType = assembly.GetTypes(); } catch (ReflectionTypeLoadException err) { arrType = err.Types; } foreach (Type type in arrType) { if (isFound) break; if (type == null) continue; MethodInfo[] arrMInfo = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static); foreach (MethodInfo info in arrMInfo) { if (isFound) break; try { string strMethod = info.ToString(); if ((strMethod.IndexOf("(System.Xml.XmlElement, System.String)") > 0) && (miDict.ContainsKey(info.ReturnType.ToString()))) { miEvaluation = info; MemoryPatching(miEvaluation, miDict[miEvaluation.ReturnType.ToString()]); nCount++; if (((assembly.FullName.IndexOf("Aspose.Pdf") == -1) && (nCount == 2)) || ((assembly.FullName.IndexOf("Aspose.Pdf") != -1) && (nCount == 6))) { isFound = true; break; } } } catch { throw new InvalidOperationException("MemoryPatching for \"" + assembly.FullName + "\" failed !"); } } } String[] aParts = assembly.FullName.Split(','); string fName = aParts[0]; if (fName.IndexOf("Aspose.BarCode.") != -1) fName = "Aspose.BarCode"; else if (fName.IndexOf("Aspose.3D") != -1) fName = "Aspose.ThreeD"; try { Type type2 = assembly.GetType(fName + ".License"); MethodInfo mi = type2.GetMethod("SetLicense", new Type[] { typeof(Stream) }); string LData = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5MaWNlbnNlZTwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPmxpY2Vuc2VlQGVtYWlsLmNvbTwvRW1haWxUbz4KICAgIDxMaWNlbnNlVHlwZT5EZXZlbG9wZXIgT0VNPC9MaWNlbnNlVHlwZT4KICAgIDxMaWNlbnNlTm90ZT5MaW1pdGVkIHRvIDEwMDAgZGV2ZWxvcGVyLCB1bmxpbWl0ZWQgcGh5c2ljYWwgbG9jYXRpb25zPC9MaWNlbnNlTm90ZT4KICAgIDxPcmRlcklEPjc4NDM3ODU3Nzg1PC9PcmRlcklEPgogICAgPFVzZXJJRD4xMTk3ODkyNDM3OTwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIFByb2R1Y3QgRmFtaWx5PC9Qcm9kdWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+e0YyQjk3MDQ1LTFCMjktNEIzRi1CRDUzLTYwMUVGRkExNUFBOX08L1NlcmlhbE51bWJlcj4KICAgIDxTdWJzY3JpcHRpb25FeHBpcnk+MjA5OTEyMzE8L1N1YnNjcmlwdGlvbkV4cGlyeT4KICAgIDxMaWNlbnNlVmVyc2lvbj4zLjA8L0xpY2Vuc2VWZXJzaW9uPgogIDwvRGF0YT4KICA8U2lnbmF0dXJlPlFYTndiM05sTGxSdmRHRnNJRkJ5YjJSMVkzUWdSbUZ0YVd4NTwvU2lnbmF0dXJlPgo8L0xpY2Vuc2U+"; Stream stream = new MemoryStream(Convert.FromBase64String(LData)); stream.Seek(0, SeekOrigin.Begin); mi.Invoke(Activator.CreateInstance(type2, null), new Stream[] { stream }); } catch { //throw new InvalidOperationException("SetLicense for \"" + assembly.FullName + "\" failed !"); } } private static DateTime InvokeMe1(XmlElement element, string name) { return DateTime.MaxValue; } private static XmlElement InvokeMe2(XmlElement element, string name) { if (element.LocalName == "License") { string License64 = "PERhdGE+PExpY2Vuc2VkVG8+R3JvdXBEb2NzPC9MaWNlbnNlZFRvPjxMaWNlbnNlVHlwZT5TaXRlIE9FTTwvTGljZW5zZVR5cGU+PExpY2Vuc2VOb3RlPkxpbWl0ZWQgdG8gMTAgZGV2ZWxvcGVyczwvTGljZW5zZU5vdGU+PE9yZGVySUQ+MTMwNzI0MDQwODQ5PC9PcmRlcklEPjxPRU0+VGhpcyBpcyBhIHJlZGlzdHJpYnV0YWJsZSBsaWNlbnNlPC9PRU0+PFByb2R1Y3RzPjxQcm9kdWN0PkFzcG9zZS5Ub3RhbDwvUHJvZHVjdD48L1Byb2R1Y3RzPjxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT48U2VyaWFsTnVtYmVyPjliNTc5NTAxLTUyNjEtNDIyMC04NjcwLWZjMmQ4Y2NkZDkwYzwvU2VyaWFsTnVtYmVyPjxTdWJzY3JpcHRpb25FeHBpcnk+MjAxNDA3MjQ8L1N1YnNjcmlwdGlvbkV4cGlyeT48TGljZW5zZVZlcnNpb24+Mi4yPC9MaWNlbnNlVmVyc2lvbj48L0RhdGE+PFNpZ25hdHVyZT5udFpocmRoL3I0QS81ZFpsU2dWYnhac0hYSFBxSjZ5UVVYa0RvaW4vS2lVZWhUUWZET0lQdHdzUlR2NmRTUVplOVdXekNnV3RGdkdROWpmR2QySmF4YUQvbkx1ZEk2R0VVajhqeVhUMG4vbWRrMEF1WVZNYlBXRjJYd3dSTnFlTmRrblYyQjhrZVFwbDJ2RzZVbnhxS2J6VVFxS2Rhc1pzZ2w1Q0xqSFVEWms9PC9TaWduYXR1cmU+"; element.InnerXml = new UTF8Encoding().GetString(Convert.FromBase64String(License64)); } if (element.LocalName == "BlackList") { string BlackList64 = "PERhdGE+PC9EYXRhPjxTaWduYXR1cmU+cUJwMEx1cEVoM1ZnOWJjeS8vbUVXUk9KRWZmczRlY25iTHQxYlNhanU2NjY5RHlad09FakJ1eEdBdVBxS1hyd0x5bmZ5VWplYUNGQ0QxSkh2RVUxVUl5eXJOTnBSMXc2NXJIOUFyUCtFbE1lVCtIQkZ4NFMzckFVMnd6dkxPZnhGeU9DQ0dGQ2UraTdiSHlGQk44WHp6R1UwdGRPMGR1RTFoRTQ5M1RNY3pRPTwvU2lnbmF0dXJlPg=="; element.InnerXml = new UTF8Encoding().GetString(Convert.FromBase64String(BlackList64)); } XmlNodeList elementsByTagName = element.GetElementsByTagName(name); if (elementsByTagName.Count <= 0) { return null; } return (XmlElement)elementsByTagName[0]; } private static unsafe void MemoryPatching(MethodBase miEvaluation, MethodBase miLicensed) { IntPtr IntPtrEval = GetMemoryAddress(miEvaluation); IntPtr IntPtrLicensed = GetMemoryAddress(miLicensed); if (IntPtr.Size == 8) *((long*)IntPtrEval.ToPointer()) = *((long*)IntPtrLicensed.ToPointer()); else *((int*)IntPtrEval.ToPointer()) = *((int*)IntPtrLicensed.ToPointer()); } private static unsafe IntPtr GetMemoryAddress(MethodBase mb) { RuntimeHelpers.PrepareMethod(mb.MethodHandle); if ((Environment.Version.Major >= 4) || ((Environment.Version.Major == 2) && (Environment.Version.MinorRevision >= 3053))) { return new IntPtr(((int*)mb.MethodHandle.Value.ToPointer() + 2)); } UInt64* location = (UInt64*)(mb.MethodHandle.Value.ToPointer()); int index = (int)(((*location) >> 32) & 0xFF); if (IntPtr.Size == 8) { ulong* classStart = (ulong*)mb.DeclaringType.TypeHandle.Value.ToPointer(); ulong* address = classStart + index + 10; return new IntPtr(address); } else { uint* classStart = (uint*)mb.DeclaringType.TypeHandle.Value.ToPointer(); uint* address = classStart + index + 10; return new IntPtr(address); } } } } //End
PictureConversion代码:
using Aspose.Cells; using BSI_InsuranceProject_DBUtility.Error; using ESBasic; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BSI_InsuranceProject_DBUtility { /*************************************************************** FileName:文件转图片工具类(支持格式:pdf、ppt、word) Author:邵 Create Date:2018-5月15号 ******************************************************************/ public class PictureConversion { /// <summary> /// 将Word文档转换为图片的方法 /// </summary> /// <param name="wordInputPath">Word文件路径</param> /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为Word所在路径</param> /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param> /// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param> /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param> public string ConvertToImage_Words(string wordInputPath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution, string imgUrl) { try { Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath); if (doc == null) { throw new Exception("Word文件无效或者Word文件被加密!"); } if (imageOutputDirPath.Trim().Length == 0) { imageOutputDirPath = Path.GetDirectoryName(wordInputPath); } if (!Directory.Exists(imageOutputDirPath)) { Directory.CreateDirectory(imageOutputDirPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > doc.PageCount || endPageNum <= 0) { endPageNum = doc.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } if (imageFormat == null) { imageFormat = ImageFormat.Png; } if (resolution <= 0) { resolution = 128; } string imageName = Path.GetFileNameWithoutExtension(wordInputPath); Aspose.Words.Saving.ImageSaveOptions imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png); imageSaveOptions.Resolution = resolution; string imgName = string.Empty; for (int i = startPageNum; i <= endPageNum; i++) { MemoryStream stream = new MemoryStream(); imageSaveOptions.PageIndex = i - 1; string imgPath = Path.Combine(imageOutputDirPath, imageName) + "_" + i.ToString("000") + "." + imageFormat.ToString(); imgName += imgUrl + "/" + imageName + "_" + i.ToString("000") + "." + imageFormat.ToString() + "|"; doc.Save(stream, imageSaveOptions); System.Drawing.Image img = System.Drawing.Image.FromStream(stream); System.Drawing.Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f); bm.Save(imgPath, imageFormat); img.Dispose(); stream.Dispose(); bm.Dispose(); System.Threading.Thread.Sleep(200); } if (!string.IsNullOrEmpty(imgName)) { imgName = imgName.Substring(0, imgName.Length - 1); } return imgName; } catch (Exception ex) { ErrorHandler.WriteError(ex); throw; } } /// <summary> /// 将PPT、Excel、Txt文档转换为图片的方法 /// </summary> /// <param name="originFilePath">ppt文件路径</param> /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为pdf所在路径</param> /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param> /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param> public string ConvertToImage_PPT(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution, string Format, string imgUrl) { try { //先将文件转换为pdf临时文件 string tmpPdfPath = originFilePath.Replace(Format, "pdf"); if (Format == ".xls" || Format == ".xlsx" || Format == ".txt") { Workbook wb = new Workbook(originFilePath); wb.Save(tmpPdfPath, SaveFormat.Pdf); } else { Aspose.Slides.Presentation doc = new Aspose.Slides.Presentation(originFilePath); if (doc == null) { throw new Exception("ppt文件无效或者ppt文件被加密!"); } if (imageOutputDirPath.Trim().Length == 0) { imageOutputDirPath = Path.GetDirectoryName(originFilePath); } if (!Directory.Exists(imageOutputDirPath)) { Directory.CreateDirectory(imageOutputDirPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > doc.Slides.Count || endPageNum <= 0) { endPageNum = doc.Slides.Count; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } if (resolution <= 0) { resolution = 128; } if (doc != null) { doc.Save(tmpPdfPath, Aspose.Slides.Export.SaveFormat.Pdf); } } //再将pdf转换为图片 string imgName = ConvertToImage_PDF(tmpPdfPath, imageOutputDirPath, startPageNum, endPageNum, resolution, imgUrl); //删除pdf临时文件 File.Delete(tmpPdfPath); return imgName; } catch (Exception ex) { ErrorHandler.WriteError(ex); return "888"; throw; } } /// <summary> /// 将pdf文档转换为图片的方法 /// </summary> /// <param name="originFilePath">pdf文件路径</param> /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为pdf所在路径</param> /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param> /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param> public string ConvertToImage_PDF(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution, string imgUrl) { try { Aspose.Pdf.Document doc = new Aspose.Pdf.Document(originFilePath); if (doc == null) { throw new Exception("pdf文件无效或者pdf文件被加密!"); } if (imageOutputDirPath.Trim().Length == 0) { imageOutputDirPath = Path.GetDirectoryName(originFilePath); } if (!Directory.Exists(imageOutputDirPath)) { Directory.CreateDirectory(imageOutputDirPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > doc.Pages.Count || endPageNum <= 0) { endPageNum = doc.Pages.Count; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } if (resolution <= 0) { resolution = 128; } string imageNamePrefix = Path.GetFileNameWithoutExtension(originFilePath); string imgName = string.Empty; for (int i = startPageNum; i <= endPageNum; i++) { MemoryStream stream = new MemoryStream(); string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + ".jpg"; imgName += imgUrl + "/" + imageNamePrefix + "_" + i.ToString("000") + ".jpg|"; Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100); jpegDevice.Process(doc.Pages[i], stream); Image img = Image.FromStream(stream); Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f); bm.Save(imgPath, ImageFormat.Jpeg); img.Dispose(); stream.Dispose(); bm.Dispose(); System.Threading.Thread.Sleep(200); } if (!string.IsNullOrEmpty(imgName)) { imgName = imgName.Substring(0, imgName.Length - 1); } return imgName; } catch (Exception ex) { ErrorHandler.WriteError(ex); throw; } } } }
到这里就可以完美转换图片了.....