Automatyzacja biura (Interop) na Windows Server 2012

Z powodzeniem używam automatyzacji pakietu Office w systemie Windows Server 2008 R2 z pakietem Office 2007 w celu konwersji dokumentów pakietu Office na pliki PDF. Kod jest dość prosty:

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;
        }
    }
}

Problem polega na tym, że ten kod nie działa w systemie Windows Server 2012. Otrzymany błąd to:

System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Uruchamianie kodu jako użytkownik interaktywny (aplikacja konsolowa) działa dobrze, ale kończy się niepowodzeniem podczas uruchamiania z aplikacji internetowej IIS lub z usługi systemu Windows (nawet z „alow service interaction with desktop”). Użytkownik uruchamiający aplikację ma wystarczające uprawnienia (administrator), a kod działa poprawnie w pakiecie Office 2010.

Jakieś pomysły?

questionAnswers(3)

yourAnswerToTheQuestion