Monday, July 29, 2013

Welcome Nimitz



My  Rat Terrier puppy named Nimitz.





Wednesday, July 17, 2013

Using Microsoft.Office.Interop.PowerPoint to convert PPT to PDF

Microsoft PowerPoint can create some pretty good PDF using it's built in Save As functionality. The Interop library allows to code this functionality for large batch jobs.

One notable issues is that trying to open a password protected file, where the password wasn't known and would have preferred a graceful fail as with the Interop.Word library, would pop open a password dialog box and block the batch processing until a user could manually click on cancel.

After a few days of trial and error, I got the following advice from friends at StackOverflow.com - just append a bogus password to the file name when opening the PPT in the form of "c:\temp\filename.ppt::BOGUS_PASSWORD::" - if the PPT file required a password it is ignored, if it's the wrong password it throws an exception, but no password prompt is open on the screen.

Very nice


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using Microsoft.Office;
using Microsoft.Office.Interop.PowerPoint;

using MT = Microsoft.Office.Core.MsoTriState;

namespace PowerPointConverter
{
 public class PowerPointConverter : IDisposable
 {
  Application app;
  public PowerPointConverter()
  {
   app = new Microsoft.Office.Interop.PowerPoint.Application();
   app.DisplayAlerts = PpAlertLevel.ppAlertsNone;
   app.ShowWindowsInTaskbar = MT.msoFalse;
   app.WindowState = PpWindowState.ppWindowMinimized;
  }

  public bool ConvertToPDF(FileInfo sourceFile, DirectoryInfo destDir)
  {
   bool success = true;
   

   FileInfo destFile = new FileInfo(destDir.Name + "\\" +
    Path.GetFileNameWithoutExtension(sourceFile.Name) + ".pdf");

   Thread pptThread = new Thread(delegate()
   {
    try
    {
     string openString = sourceFile.FullName + "::BOGUS_PASSWORD::";
     
     Presentation ppt = null;
     ppt = app.Presentations.Open(openString, MT.msoTrue, MT.msoTrue, MT.msoFalse);
     ppt.SaveAs(destFile.FullName, PpSaveAsFileType.ppSaveAsPDF, MT.msoFalse);
     ppt.Close();
     System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ppt);
    }
    catch (System.Runtime.InteropServices.COMException comEx)
    {
     success = false;
    }
   });

   pptThread.Start();
   if (!pptThread.Join(20000))
   {
    pptThread.Abort();
    success = false;
   }

   return success;
  }

    
  public void Dispose()
  {
   Thread appThread = new Thread(delegate()
   {
    try
    {
     if (null != app)
     {
      app.Quit();
      System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
     }
    }
    catch (System.Runtime.InteropServices.COMException) { }
   });

   appThread.Start();
   if (!appThread.Join(10000))
   {
    appThread.Abort();
   }
  }
 }
}