[C#]MS PowerPoint 轉存為圖檔

  • 1273
  • 0
  • C#
  • 2018-05-07

MS PowerPoint 轉存為圖檔

近日收到第一則來信,請教小弟如何轉PPT至圖檔,週末閒來無事Coding兩段來填補內心的空虛(到底多空虛)

雖不是什麼很難的技術,但學海無涯;也希望能藉由這楊幫助到需要的人。

這次延續上一篇[C#]MS Word 轉存為圖檔會使用兩種方式將POWER POINT轉成圖檔

今天使用的PPT有兩頁,而輸出的圖檔共為4張(因為使用兩種涵式庫)。

第一個使用Microsoft.Office.Interop.PowerPoint

這個方法需要引用兩個參考(可以直接重NuGet取得):

1. Microsoft.Office.Interop.PowerPoint

2. Microsoft.Office.Core

        /// <summary>
        /// Microsoft.Office.Interop.PowerPoint  將PPT轉圖片
        /// </summary>
        /// <param name="pptPath">PPT檔案位置(FullPath)</param>
        /// <param name="outPutPath">PPT圖檔輸出位置</param>
        public void convertPttToImgByOffice(string pptPath, string outPutPath) {
            try {
                Microsoft.Office.Interop.PowerPoint.Application pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();
                Microsoft.Office.Interop.PowerPoint.Presentation pptPresentation = pptApplication.Presentations.Open(pptPath, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
                int i = 0;
                //將一頁頁的簡報匯出成圖檔
                foreach (Microsoft.Office.Interop.PowerPoint.Slide pptSlide in pptPresentation.Slides) {
                    string fileName = string.Format("Interop.PowerPoint-img-{0}.png", i);

                    //C:\Users\Egan\Desktop\DocPrinter.Test\DocFolder\ + Interop.PowerPoint-img-{0}.png
                    pptSlide.Export(outPutPath + fileName, "PNG", 1024, 768);
                    i++;
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }
        }

第二個使用Spire.Presentation

Spire.Presentation是一個免費可對PPT進行各種操作的涵式庫,這邊僅把它用來將每一頁簡報書櫥成圖檔

涵式庫下載從NuGet就能取得了。

        /// <summary>
        /// Spire.Presentation 將PPT轉圖片
        /// </summary>
        /// <param name="pptPath">PPT檔案位置(FullPath)</param>
        /// <param name="outPutPath">PPT圖檔輸出位置</param>
        public void convertPttToImgBySpirePresentation(string pptPath, string outPutPath) {
            try {
                Presentation presentation = new Presentation();
                presentation.LoadFromFile(pptPath);
                for (int i = 0; i < presentation.Slides.Count; i++) {
                    Image image = presentation.Slides[i].SaveAsImage();
                    string fileName = string.Format("SpirePresentation-img-{0}.png", i);
                    image.Save(outPutPath + fileName, System.Drawing.Imaging.ImageFormat.Png);
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }
        }

備註:兩種方式都能成功將PPT轉為圖檔,但第二種使用Spire.Presentation所轉換的圖檔上方會出現該涵式褲帶入的浮水印(下圖第一張)

egan2608@gmail.com