这么做的好处是可以通过代码判断客户机的Office版本动态调用对应方法.(适用于少数不兼容的方法.)
public class Ppt2JpgLazyBinding { private object pptApp; private Type pptType; private object presentations; private object presentation; private object slides; public void ExportToImage(string pptFile) { var progId = "PowerPoint.Application"; pptType = Type.GetTypeFromProgID(progId); if (pptType != null) { var imgSaveDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "imgs"); if (!Directory.Exists(imgSaveDir)) Directory.CreateDirectory(imgSaveDir); pptApp = Activator.CreateInstance(pptType); presentations = pptType.InvokeMember("Presentations", System.Reflection.BindingFlags.GetProperty, null, pptApp, null); try { presentation = presentations.GetType() .InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, presentations, new object[] { pptFile, true, false, false }); slides = presentation.GetType() .InvokeMember("Slides", System.Reflection.BindingFlags.GetProperty, null, presentation, null); slides.GetType() .InvokeMember("Count", System.Reflection.BindingFlags.GetProperty, null, slides, null); var enumeratorObj = slides.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, slides, null); var enumerator = enumeratorObj as IEnumerator; if (enumerator != null) { var pageNo = 1; while (enumerator.MoveNext()) { var slideObj = enumerator.Current; slideObj?.GetType() .InvokeMember("Export", BindingFlags.InvokeMethod, null, slideObj, new object[] { $"{imgSaveDir}//{pageNo++.ToString("000")}.jpg", "JPG" }); } } } catch (Exception e) { throw new Exception("将PPT导出图片期间异常.", e); } pptType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, pptApp, null); } } }