Автоматизация делопроизводства (Interop) на Windows Server 2012
Я успешно использую автоматизацию Office на Windows Server 2008 R2 с Office 2007 для преобразования документов 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 или из службы Windows (даже с «разрешенной службой для взаимодействия с рабочим столом»). Пользователь, запускающий приложение, имеет достаточные разрешения (администратор), и код отлично работает с Office 2010.
Есть идеи?