1

我想使用 C# 和 Microsoft.Office.Interop.PowerPoint 将 pps(x) 或 ppt(x) 转换为 PDF。为此,我使用执行以下编码的方法:

Microsoft.Office.Interop.PowerPoint.Presentation presentation = null;
Microsoft.Office.Interop.PowerPoint.Application application = null;
try
{
    application = new Microsoft.Office.Interop.PowerPoint.Application();
    presentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
    presentation.SaveAs(targetPath, PpSaveAsFileType.ppSaveAsPDF, Microsoft.Office.Core.MsoTriState.msoTrue);
    result = true;
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    result = false;
}
finally
{
    if (presentation != null)
    {
        presentation.Close();
        presentation = null;
    }
    if (application != null)
    {
        application.Quit();
        application = null;
    }
}
return result;

第一次调用该方法时,ppsx成功保存为pdf。但是当再次调用该方法时,会引发以下异常application = new Microsoft.Office.Interop.PowerPoint.Application();

异常消息是:Creating an instance of the COM component with CLSID {91493441-5A91-11CF-8700-00AA0060263B} from the IClassFactory failed due to the following error: 800706b5 The interface is unknown. (Exception from HRESULT: 0x800706B5).就在引发此异常之前,控制台显示另一个异常"System.Runtime.InteropServices.COMException" in mscorlib.dll

通过 F12导航到该界面时Microsoft.Office.Interop.PowerPoint.Application,该界面的 GUID 为 9149344 2 -5A91-11CF-8700-00AA0060263B。所以它与异常消息中的 GUID 略有不同。

想请教一下,这个问题怎么解决?

PS:本笔记本安装了Microsoft Office 2010(运行Microsoft Win 7)

感谢你并致以真诚的问候

4

3 回答 3

1

以下(可以说是愚蠢的)解决方法对我有用:

try
{
    app = new Application();
}
catch (COMException)
{
    app = new Application();
}

编辑:谢谢杰西:)

于 2013-04-11T02:17:22.040 回答
0

在返回值之前尝试关闭演示文稿和应用程序。

presentation.Close();
application.Quit();

否则文档和应用程序保持打开状态,无法访问

于 2013-10-25T11:58:14.520 回答
0

您可以尝试使用此代码将任何 ppt 文件转换为具有互操作性的 pdf,并且它可以正常工作。即使在后台进程中也不会保持打开的 COM 对象。

Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
                    app.Visible = MsoTriState.msoTrue;
                    Presentations presentations = app.Presentations;
                    Presentation presentation = presentations.Open(fileLocation, ReadOnly: MsoTriState.msoCTrue);
                    presentation.ExportAsFixedFormat(outLocation, PpFixedFormatType.ppFixedFormatTypePDF);

                    Marshal.ReleaseComObject(presentations);
                    presentation.Close();
                    Marshal.ReleaseComObject(presentation);
                    app.Quit();
                    Marshal.ReleaseComObject(app);

              
于 2020-09-03T08:26:39.953 回答