爲了將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的代碼可以正常工作。
任何想法?
顯然我意識到這一點。但它不會改變使用Office的要求。原因是Office最準確地將其文檔轉換爲pdf。 – basdanny