views:

1596

answers:

5

I am looking for a code snippet that does just this, preferably in C# or even Perl.

I hope this not a big task ;)

A: 

If you're planning on doing this on a web server then please don't. Office products aren't recommended for automation use:

Considerations for server-side Automation of Office (MS KB257757)

You're better off looking into a product such as Aspose Slides which doesn't rely on Office being installed.

Kev
+2  A: 

As Kev points out, don't use this on a web server. However, the following Perl script is perfectly fine for offline file conversion etc:

#!/usr/bin/perl

use strict;
use warnings;

use Win32::OLE;
use Win32::OLE::Const 'Microsoft PowerPoint';
$Win32::OLE::Warn = 3;

use File::Basename;
use File::Spec::Functions qw( catfile );

my $EXPORT_DIR = catfile $ENV{TEMP}, 'ppt';

my ($ppt) = @ARGV;
defined $ppt or do {
    my $progname = fileparse $0;
    warn "Usage: $progname output_filename\n";
    exit 1;
};

my $app = get_powerpoint();
$app->{Visible} = 1;

my $presentation = $app->Presentations->Open($ppt);
die "Could not open '$ppt'\n" unless $presentation;

$presentation->Export(
    catfile( $EXPORT_DIR, basename $ppt ),
    'JPG',
    1024,
    768,
);

sub get_powerpoint {
    my $app;
    eval { $app = Win32::OLE->GetActiveObject('PowerPoint.Application') };
    die "$@\n" if $@;

    unless(defined $app) {
        $app = Win32::OLE->new('PowerPoint.Application',
            sub { $_[0]->Quit }
        ) or die sprintf(
            "Cannot start PowerPoint: '%s'\n", Win32::OLE->LastError
        );
    }
    return $app;
}
Sinan Ünür
+3  A: 

The following will open C:\presentation1.ppt and save the slides as C:\Presentation1\slide1.jpg etc.

If you need to get the interop assembly, it is available under 'Tools' in the Office install program, or you can download it from here (office 2003). You should be able to find the links for other versions from there if you have a newer version of office.

using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;

namespace PPInterop
{
  class Program
  {
 static void Main(string[] args)
 {
  var app = new PowerPoint.Application();

  var pres = app.Presentations;

  var file = pres.Open(@"C:\Presentation1.ppt", MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);

  file.SaveCopyAs(@"C:\presentation1.jpg", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoTrue);
 }
  }
}

Edit: Sinan's version using export looks to be a bit better option since you can specify an output resolution. For C#, change the last line above to:

file.Export(@"C:\presentation1.jpg", "JPG", 1024, 768);
Dolphin
+1 for the C# solution (when I can vote again which should be in another eight hours or so ;-)
Sinan Ünür