我成功地以Office文档转换为PDF文件使用办公自动化的Windows Server 2008 R2与Office 2007。 该代码是相当简单:
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服务运行(即使有“alow服务与桌面交互”),当它失败。 运行该应用程序的用户有足够的权限(管理员)和代码工作正常使用Office 2010。
有任何想法吗?