2013-01-20 71 views
2

爲了將Office文檔轉換爲PDF,我在Windows Server 2008 R2和Office 2007上成功使用Office自動化。 的代碼很簡單:Windows Server 2012上的辦公自動化(Interop)

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的代碼可以正常工作。

任何想法?

回答

1

發現的唯一的解決方案是讓調用API辦公室運行互動的過程。 只需運行控制檯應用程序(不是服務器解決方案最明智的想法),或創建一些後臺服務(例如,Windows服務)並將其設置爲工作站(SetProcessWindowStation)即可完成。

2

我可能會因爲這個答案而被低估,但是我在一個使用Office自動化的產品的企業環境中工作,而且這是非常有問題的。

我已經在這個舞臺做過研究,並且微軟本身建議不要做Office自動化。

以下是直接從微軟的MSDN知識庫

Microsoft不建議或Office的支持服務器端自動化。

而且

微軟目前並不提倡,不支持,Microsoft Office應用程序自動化從任何無人蔘與的非交互式客戶端應用程序或組件(包括ASP,ASP.NET,DCOM,和NT服務),因爲Office在此環境中運行時可能會出現不穩定的行爲和/或死鎖。

來源:http://support.microsoft.com/kb/257757

+0

顯然我意識到這一點。但它不會改變使用Office的要求。原因是Office最準確地將其文檔轉換爲pdf。 – basdanny