使用c#将ppsx转换为pdf

时间:2013-02-06 15:13:05

标签: c# pdf powerpoint

我想使用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上运行)

谢谢你,以及最好的问候

3 个答案:

答案 0 :(得分:1)

以下(可以说是愚蠢愚蠢)的解决方法为我做了诀窍:

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

编辑:谢谢杰西:)

答案 1 :(得分:0)

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

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

否则文档和应用程序仍然打开,无法访问

答案 2 :(得分:0)

您可以尝试使用此代码通过interop将任何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);