不稳定的办公室(Powerpoint)自动化

本文关键字:自动化 Powerpoint 办公室 不稳定 | 更新日期: 2023-09-27 17:50:53

我正在开发一个应用程序,允许用户上传演示文稿,编辑它,然后下载最终输出作为另一个PowerPoint演示文稿。

对于我上传的不同演示文稿,我的行为非常不稳定:

  1. 有时改变后的图像模糊(不知道为什么?)

  2. 有时会返回不正确的形状id,因此我无法将更改的工作与现有的PowerPoint形状合并。

    var shape = (PowerPoint.Shape)item;
    var shapeid=shape.ID; //this is different from what interop has returned on first presentation read.
    
  3. 动画没有被正确复制(有时可以,有时不可以)。

          newshape.AnimationSettings.EntryEffect = oldshape.AnimationSettings.EntryEffect;
          newshape.AnimationSettings.AdvanceMode=oldshape.AnimationSettings.AdvanceMode;        
          newshape.AnimationSettings.AdvanceTime=oldshape.AnimationSettings.AdvanceTime;
          newshape.AnimationSettings.AfterEffect=oldshape.AnimationSettings.AfterEffect;
          newshape.AnimationSettings.Animate=oldshape.AnimationSettings.Animate;
          newshape.AnimationSettings.AnimateBackground = oldshape.AnimationSettings.AnimateBackground;
          newshape.AnimationSettings.TextLevelEffect = PowerPoint.PpTextLevelEffect.ppAnimateByAllLevels;
          newshape.AnimationSettings.AnimateTextInReverse=oldshape.AnimationSettings.AnimateTextInReverse;
    

我知道服务器端自动化可能有不稳定的行为或死锁。然而,没有任何文档准确地记录了这种行为的不稳定性。
这些行为(以上两种)是否属于同一类别,还是我在这里遗漏了什么?如何解决这些问题?

不稳定的办公室(Powerpoint)自动化

如果您仍然需要使用Interop,那么尝试释放COM对象并偶尔杀死PowerPoint实例,如下所述:

public static class PowerPointInterOp
{
    static PowerPoint.Application powerPointApp = null;
    static Object oMissing = System.Reflection.Missing.Value;
    static Object oTrue = true;
    static Object oFalse = false;
    static Object oCopies = 1;
    public static void InitializeInstance()
    {
        if (powerPointApp == null)
        {
            powerPointApp = new PowerPoint.ApplicationClass();
        }           
    }
    public static void KillInstances()
    {
        try
        {
            Process[] processes = Process.GetProcessesByName("POWERPNT");
            foreach(Process process in processes)
            {
                process.Kill();
            }
        }
        catch(Exception)
        {
        }
    }
    public static void CloseInstance()
    {
        if (powerPointApp != null)
        {
            powerPointApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(powerPointApp);
            powerPointApp = null;
        }
    }
    public static PowerPoint.Presentation OpenDocument(string documentPath)
    {
        InitializeInstance();
        PowerPoint.Presentation powerPointDoc = powerPointApp.Presentations.Open(documentPath, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
        return powerPointDoc;
    }
    public static void CloseDocument(PowerPoint.Presentation powerPointDoc)
    {
        if (powerPointDoc != null)
        {
            powerPointDoc.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(powerPointDoc);
            powerPointDoc = null;
        }           
    }

}