OfficeドキュメントをPDFに変換するために、Office2007を搭載したWindowsServer2008R2でOfficeオートメーションを正常に使用しています。コードはかなり単純です:
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;
}
}
}
問題は、このコードがWindowsServer2012では機能しないことです。受け取ったエラーは次のとおりです。
System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
対話型ユーザー(コンソールアプリ)としてコードを実行することは正常に機能しますが、IIS WebアプリまたはWindowsサービスから実行すると失敗します(「デスクトップと対話するためのサービスが少ない」場合でも)。アプリを実行しているユーザーには十分な権限(管理者)があり、コードはOffice2010で正常に機能します。
何か案は?