【问题标题】:Save PowerPoint slide as image from VSTO application从 VSTO 应用程序将 PowerPoint 幻灯片另存为图像
【发布时间】:2021-08-26 10:29:48
【问题描述】:

我正在使用 C# 为 PowerPoint 开发 VSTO 应用程序。目标是每 5 秒将打开的 PowerPoint 演示文稿的选定幻灯片导出到用户计算机上的 PNG 文件。 PowerPoint API 提供以下方式来导出幻灯片:

(Slide)Application.ActiveWindow.View.Slide.Export("D:/path", "png")

但是,每次调用此方法时,PowerPoint 窗口都会冻结(可能停用?)一瞬间,因此所有展开的菜单都会关闭(例如,通过右键单击幻灯片打开的菜单、菜单用于插入形状等)

我正在寻找一种方法来避免这种情况。使用 Slide.Export 方法时有没有办法解决这个问题?或者也许有一些替代方法可以使用它?

我尝试使用 Aspose.Slides 等自定义库,它们可以解决此问题,但会导致更糟糕的问题:它们无法访问 PowerPoint 程序集呈现的 Presentation 对象,因此为了在您的程序集中使用它们,您必须将副本保存到计算机并打开它,这对我来说是一个糟糕的解决方案。

任何关于如何解决我的问题的想法都会非常有帮助。

编辑:要重现该问题,请为 PowerPoint 创建一个 VSTO 加载项项目并将 ThisAddIn 替换为以下代码:

public partial class ThisAddIn
{
    public Form form = new Form
    {
        Opacity = 0.01,
        Visible = false,
    };
    delegate void InvokeEventHandler();

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        form.Show();

        var del = new InvokeEventHandler(() => Timer_Tick());
        form.Invoke(del);
        var timer = new System.Timers.Timer();
        timer.Interval = 5000;
        timer.Elapsed += (s, ea) => form.Invoke(del);
        timer.Start();
    }

    private void Timer_Tick()
    {
        try
        {
            var slide = (Slide)Application.ActiveWindow.View.Slide;
            slide.Export(Path.Combine(Path.GetTempPath(), "test"), "png");
        }
        catch
        {
            return;
        }
    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
    }

    #region VSTO generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }
    
    #endregion
}

当 PowerPoint 打开时,右键单击幻灯片并等待几秒钟。当计时器计时,菜单将关闭。

【问题讨论】:

  • 你能发布你的计时器代码吗?
  • @EylM 我在底部添加了 ThisAddIn 代码
  • 我敢打赌,您正在从不同的线程 (System.Timers.Timer) 访问 Powerpoint 对象。您应该通过 Invoke 使用主线程。
  • 我试过这样做,但结果是一样的(见上面更新的代码)。不过我可能做错了,你能检查一下吗?

标签: c# powerpoint vsto


【解决方案1】:

指定的图形格式必须在 Windows 注册表中注册导出过滤器。您可以指定注册的扩展名或注册的过滤器名称。 Microsoft PowerPoint 将首先在注册表中搜索匹配的扩展名。如果未找到与指定字符串匹配的扩展名,PowerPoint 将查找匹配的筛选器名称。

尝试改用 JPG 文件格式:

With Application.ActivePresentation.Slides(3)
    .Export "c:\my documents\Graphic Format\" & _
        "Slide 3 of Annual Sales", "JPG"
End With

【讨论】:

  • 我试过了,但是,每当调用 Slide.Export("{path}", "JPG") 时,PowerPoint 窗口都会冻结片刻。只有在计时器调用 Slide.Export 时才能重现此场景,因为如果您在事件处理程序中调用它(例如,在单击按钮后),您将不会注意到它。但是,如果将它绑定到计时器,您会注意到每个计时器滴答声,窗口都会在瞬间停止响应。例如,如果您右键单击幻灯片并打开幻灯片上下文菜单,它将在下一个计时器滴答时自动关闭。对不起,解释太长了,希望我的问题现在更清楚了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多