我在 Windows Server 2008 R2 和 Office 2007 上成功使用 Office 自动化,以便将 Office 文档转换为 PDF。代码相当简单:
public class WordConvert
{
/// <summary>
/// Converts a word file to PDF
/// </summary>
/// <param name="sourceFilePath">The path of the word file to convert</param>
/// <param name="targetFilePath">The path of the PDF output file</param>
public static void ConvertWord(string sourceFilePath, string targetFilePath)
{
object objTragetFileName = targetFilePath;
Word.Application wordDocument = new Word.Application();
try
{
OpenWord(sourceFilePath, wordDocument);
SaveAsPDF(ref objTragetFileName, wordDocument);
}
finally
{
CloseWord(wordDocument);
}
}
private static void OpenWord(object sourceFileName, Word.Application wordDocument)
{
wordDocument.Documents.Open(ref sourceFileName);
}
private static void SaveAsPDF(ref object targetFileName, Word.Application wordDocument)
{
object format = Word.WdSaveFormat.wdFormatPDF;
wordDocument.ActiveDocument.SaveAs(ref targetFileName, ref format);
}
private static void CloseWord(Word.Application wordDocument)
{
if (wordDocument != null)
{
GC.Collect();
GC.WaitForPendingFinalizers();
// 2nd time to be safe
GC.Collect();
GC.WaitForPendingFinalizers();
Word.Documents documents = wordDocument.Documents;
documents.Close();
Marshal.ReleaseComObject(documents);
documents = null;
Word.Application application = wordDocument.Application;
application.Quit();
Marshal.ReleaseComObject(application);
application = null;
}
}
}
问题是此代码在 Windows Server 2012 上不起作用。收到的错误是:
System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
以交互式用户(控制台应用程序)身份运行代码工作正常,但从 IIS Web 应用程序或 Windows 服务运行时失败(即使使用“允许服务与桌面交互”)。运行应用程序的用户具有足够的权限(管理员),并且代码在 Office 2010 中运行良好。
有任何想法吗?