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

8

我正在寻找一个代码片段,可以用C#或者Perl实现这个功能。

希望这不是一个很大的任务 ;)


我认为你最好的选择是使用一些C#和PowerPoint Interop程序集...也许可以尝试研究一下这方面的内容。 - Cᴏʀʏ
1
运行该程序的计算机是否已安装PowerPoint? - Sinan Ünür
2个回答

27
以下将打开C:\presentation1.ppt并将幻灯片保存为C:\Presentation1\slide1.jpg等。
如果您需要获取Interop程序集,它可以在Office安装程序的“工具”下找到,或者您可以从此处(office 2003)下载。如果您有更新版本的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);
    }
  }
}

编辑: Sinan的方法使用导出功能似乎是更好的选择,因为你可以指定输出分辨率。对于C#,请将上面的最后一行更改为:

file.Export(@"C:\presentation1.jpg", "JPG", 1024, 768);

2
+1 给 C# 解决方案(当我可以再次投票时,大约还有八个小时;-)) - Sinan Ünür
2
这非常棒。对于所有使用Office 2010及更高版本的用户来说,库'Microsoft.Office.Core' lib实际上是一个COM库,而不是需要加载的扩展。 - Az Za

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接