如何在C#或Perl中以编程方式打开并将PowerPoint演示文稿另存为HTML/JPEG?

8 c# perl powerpoint ole

我正在寻找一个代码片段,它可以做到这一点,最好是在C#甚至Perl中.

我希望这不是一项大任务;)

Dol*_*hin 26

以下将打开C:\presentation1.ppt并保存幻灯片C:\Presentation1\slide1.jpg等.

如果需要获取互操作程序集,可以在Office安装程序的"工具"下找到它,也可以从此处下载(office 2003).如果您有更新版本的办公室,您应该能够从那里找到其他版本的链接.

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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑: 使用导出的Sinan版本看起来是更好的选择,因为您可以指定输出分辨率.对于C#,将上面的最后一行更改为:

file.Export(@"C:\presentation1.jpg", "JPG", 1024, 768);
Run Code Online (Sandbox Code Playgroud)

  • 为C#解决方案+1(当我可以再次投票时应该在另外8个小时左右;-) (2认同)
  • 这太棒了。对于 Office 2010 及更高版本的所有用户,库“Microsoft.Office.Core”[lib 实际上是一个 COM 库](http://stackoverflow.com/questions/5932794/microsoft-office-core-reference-missing),不是需要加载的扩展。 (2认同)

Sin*_*nür 7

正如Kev所指出的,不要在Web服务器上使用它.但是,以下Perl脚本非常适合脱机文件转换等:

#!/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;
}
Run Code Online (Sandbox Code Playgroud)