PPT转换图片
1、转换步骤
(1) 引入COM组件Microsoft.Office.Interop.PowerPoint;
(2) 创建Microsoft.Office.Interop.PowerPoint.Application;
(3) 打开PPT文档Application.Presentations.Open;
(4) 根据PPT宽高比(PageSetup.SlideWidth、PageSetup.SlideHeight)设置合适的宽高;
(5) 遍历幻灯片集合Presentation.Slides;
(6) 使用幻灯片(Slide)的Export方法导出图片。
2、注意事项
(1) PPT导出图片的过程是阻塞执行的,可根据情况将每一页的导出作为原子操作,实现异步执行;
(2) 打开PPT的路径不能使用“/”,应将“/”替换为“\”;
(3) 保存的PPT每一页图片路径同上处理。
3、示例代码
(1) PptTool.cs
using System; using Microsoft.Office.Interop.PowerPoint; using System.Drawing.Imaging; using System.IO; using Microsoft.Office.Core; namespace OfficeTools.Tools { public class PptTool { private Application _app; public void Init() { _app = new Application { DisplayAlerts = PpAlertLevel.ppAlertsNone }; } public void UnInit() { try { _app?.Quit(); } catch (Exception e) { Console.WriteLine(e); } _app = null; GC.Collect(); } public bool Convert2Images(string filePath, string imageFolder, ImageFormat imageFormat, int width, ref int height) { //正斜杠替换为反斜杠 filePath = filePath.Replace('/', '\\'); if (!File.Exists(filePath)) { return false; } Presentation presentation = null; try { var fileName = Path.GetFileNameWithoutExtension(filePath); imageFolder = imageFolder.Replace('/', '\\'); imageFolder = imageFolder.TrimEnd('\\'); imageFolder += $"\\{fileName}"; if (!Directory.Exists(imageFolder)) { Directory.CreateDirectory(imageFolder); } //以非只读方式打开,方便操作结束后保存 presentation = _app.Presentations.Open( filePath, MsoTriState.msoTrue, //ReadOnly: true MsoTriState.msoTrue, //Untitled: true MsoTriState.msoFalse); //WithWindow: false //获取真实分辨率及其比率 //SlideWidth:幻灯片的宽度(以磅为单位) //SlideHeight:幻灯片的高度(以磅为单位) var slideWidth = presentation.PageSetup.SlideWidth; var slideHeight = presentation.PageSetup.SlideHeight; height = (int) (width * slideHeight / slideWidth); var suffix = imageFormat.ToString().ToLower(); var index = 0; foreach (Slide slide in presentation.Slides) { var newFileName = $"{imageFolder}\\{++index}.{suffix}"; slide.Export(newFileName, suffix, width, height); } } catch (Exception e) { Console.WriteLine(e); return false; } finally { presentation?.Close(); } return true; } } }
(2) 调用代码
public void Test() { var pptTool = new PptTool(); pptTool.Init(); var filePath = @"D:\test.pptx"; var width = 1920; var height = width; pptTool.Convert2Images(filePath, Environment.CurrentDirectory, ImageFormat.Png, width, ref height); pptTool.UnInit(); }