Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Converting PowerPoint Presentations to Images Using C# Interop

Tech May 15 1

(1) Add a referance to the COM component Microsoft.Office.Interop.PowerPoint.

(2) Create an instance of Microsoft.Office.Interop.PowerPoint.Application.

(3) Open the PowerPoint file using Application.Presentations.Open.

(4) Determine the output dimensions based on the slide aspect ratio (PageSetup.SlideWidth and PageSetup.SlideHeight).

(5) Iterate through the Presentation.Slides collection.

(6) Export each slide as an image using the Slide.Export method.

  1. Importent Notes

(1) The image export process is synchronous. If needed, treat each slide export as an atomic operation and run them asynchronously to avoid blocking the main thread.

(2) The path used to open the PowerPoint file must use backslashes (\). Replace any forward slashes (/) with backslashes.

(3) Apply the same backslash treatment to the output directory path for the exported images.

  1. Example Code

(1) SlideExporter.cs

using System;
using Microsoft.Office.Interop.PowerPoint;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.Office.Core;

namespace OfficeTools.Tools
{
    public class SlideExporter
    {
        private Application _powerPointApp;

        public void Initialize()
        {
            _powerPointApp = new Application { DisplayAlerts = PpAlertLevel.ppAlertsNone };
        }

        public void Cleanup()
        {
            try
            {
                _powerPointApp?.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            _powerPointApp = null;
            GC.Collect();
        }

        public bool ExportSlidesAsImages(string pptFilePath, string outputDirectory,
            ImageFormat imageFormat, int imageWidth, ref int imageHeight)
        {
            pptFilePath = pptFilePath.Replace('/', '\\');
            if (!File.Exists(pptFilePath))
            {
                return false;
            }

            Presentation pptPresentation = null;
            try
            {
                var baseName = Path.GetFileNameWithoutExtension(pptFilePath);

                outputDirectory = outputDirectory.Replace('/', '\\').TrimEnd('\\');
                outputDirectory = $"{outputDirectory}\\{baseName}";
                if (!Directory.Exists(outputDirectory))
                {
                    Directory.CreateDirectory(outputDirectory);
                }

                pptPresentation = _powerPointApp.Presentations.Open(
                    pptFilePath,
                    MsoTriState.msoTrue,   // ReadOnly: true
                    MsoTriState.msoTrue,   // Untitled: true
                    MsoTriState.msoFalse); // WithWindow: false

                var originalWidth = pptPresentation.PageSetup.SlideWidth;
                var originalHeight = pptPresentation.PageSetup.SlideHeight;
                imageHeight = (int)(imageWidth * originalHeight / originalWidth);

                var extension = imageFormat.ToString().ToLower();
                var slideNumber = 0;
                foreach (Slide slide in pptPresentation.Slides)
                {
                    var imagePath = $"{outputDirectory}\\{++slideNumber}.{extension}";
                    slide.Export(imagePath, extension, imageWidth, imageHeight);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
            finally
            {
                pptPresentation?.Close();
            }

            return true;
        }
    }
}

(2) Usage

public void ProcessConversion()
{
    var exporter = new SlideExporter();
    exporter.Initialize();

    var pptPath = @"D:\presentation.pptx";
    var width = 1920;
    var height = width;

    exporter.ExportSlidesAsImages(pptPath, Environment.CurrentDirectory,
        ImageFormat.Png, width, ref height);

    exporter.Cleanup();
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.