尝试使用 Microsoft.Office.Interop.PowerPoint 打开 PPT 文件并保存为 PDF(或其他文件类型)以进行大批量作业。适用于没有密码的文件。对于有密码的文件,我永远不会知道,我只想优雅地失败。但是,PowerPoint 将打开对话框提示,即使我的代码中止了该线程的打开线程,我也无法使用 PowerPoint,直到手动关闭该提示并阻止对其他文件的进一步处理。
建议?
我的代码的基础如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using Microsoft.Office;
using Microsoft.Office.Interop.PowerPoint;
using MT = Microsoft.Office.Core.MsoTriState;
namespace PowerPointConverter
{
public class PowerPointConverter : IDisposable
{
Application app;
public PowerPointConverter()
{
app = new Microsoft.Office.Interop.PowerPoint.Application();
app.DisplayAlerts = PpAlertLevel.ppAlertsNone;
app.ShowWindowsInTaskbar = MT.msoFalse;
app.WindowState = PpWindowState.ppWindowMinimized;
}
public bool ConvertToPDF(FileInfo sourceFile, DirectoryInfo destDir)
{
bool success = true;
FileInfo destFile = new FileInfo(destDir.Name + "\\" +
Path.GetFileNameWithoutExtension(sourceFile.Name) + ".pdf");
Thread pptThread = new Thread(delegate()
{
try
{
Presentation ppt = null;
ppt = app.Presentations.Open(sourceFile.FullName, MT.msoTrue, MT.msoTrue, MT.msoFalse);
ppt.SaveAs(destFile.FullName, PpSaveAsFileType.ppSaveAsPDF, MT.msoFalse);
ppt.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ppt);
}
catch (System.Runtime.InteropServices.COMException comEx)
{
success = false;
}
});
pptThread.Start();
if (!pptThread.Join(20000))
{
pptThread.Abort();
success = false;
}
return success;
}
public void Dispose()
{
Thread appThread = new Thread(delegate()
{
try
{
if (null != app)
{
app.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
}
}
catch (System.Runtime.InteropServices.COMException) { }
});
appThread.Start();
if (!appThread.Join(10000))
{
appThread.Abort();
}
}
}
}